DesUtil.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. //
  2. // DesUtil.m
  3. // jiaPei
  4. //
  5. // Created by apple on 2016/12/27.
  6. // Copyright © 2016年 JCZ. All rights reserved.
  7. //
  8. #import "DesUtil.h"
  9. #import <CommonCrypto/CommonCryptor.h>
  10. //空字符串
  11. #define LocalStr_None @""
  12. static const char encodingTable[] = "fujianxzz";
  13. @implementation DesUtil
  14. + (NSString *)base64StringFromText:(NSString *)text
  15. {
  16. if (text && ![text isEqualToString:LocalStr_None]) {
  17. //取项目的bundleIdentifier作为KEY
  18. NSString *key = [[NSBundle mainBundle] bundleIdentifier];
  19. NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
  20. //IOS 自带DES加密 Begin
  21. data = [self DESEncrypt:data WithKey:key];
  22. //IOS 自带DES加密 End
  23. return [self base64EncodedStringFrom:data];
  24. }
  25. else {
  26. return LocalStr_None;
  27. }
  28. }
  29. + (NSString *)textFromBase64String:(NSString *)base64
  30. {
  31. if (base64 && ![base64 isEqualToString:LocalStr_None]) {
  32. //取项目的bundleIdentifier作为KEY
  33. NSString *key = [[NSBundle mainBundle] bundleIdentifier];
  34. NSData *data = [self dataWithBase64EncodedString:base64];
  35. //IOS 自带DES解密 Begin
  36. data = [self DESDecrypt:data WithKey:key];
  37. //IOS 自带DES加密 End
  38. return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  39. }
  40. else {
  41. return LocalStr_None;
  42. }
  43. }
  44. /************************************************************
  45. 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
  46. 函数描述 : 文本数据进行DES加密
  47. 输入参数 : (NSData *)data
  48. (NSString *)key
  49. 输出参数 : N/A
  50. 返回参数 : (NSData *)
  51. 备注信息 : 此函数不可用于过长文本
  52. **********************************************************/
  53. + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
  54. {
  55. char keyPtr[kCCKeySizeAES256+1];
  56. bzero(keyPtr, sizeof(keyPtr));
  57. [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
  58. NSUInteger dataLength = [data length];
  59. size_t bufferSize = dataLength + kCCBlockSizeAES128;
  60. void *buffer = malloc(bufferSize);
  61. size_t numBytesEncrypted = 0;
  62. CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
  63. kCCOptionPKCS7Padding | kCCOptionECBMode,
  64. keyPtr, kCCBlockSizeDES,
  65. NULL,
  66. [data bytes], dataLength,
  67. buffer, bufferSize,
  68. &numBytesEncrypted);
  69. if (cryptStatus == kCCSuccess) {
  70. return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
  71. }
  72. free(buffer);
  73. return nil;
  74. }
  75. /************************************************************
  76. 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
  77. 函数描述 : 文本数据进行DES解密
  78. 输入参数 : (NSData *)data
  79. (NSString *)key
  80. 输出参数 : N/A
  81. 返回参数 : (NSData *)
  82. 备注信息 : 此函数不可用于过长文本
  83. **********************************************************/
  84. + (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key
  85. {
  86. char keyPtr[kCCKeySizeAES256+1];
  87. bzero(keyPtr, sizeof(keyPtr));
  88. [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
  89. NSUInteger dataLength = [data length];
  90. size_t bufferSize = dataLength + kCCBlockSizeAES128;
  91. void *buffer = malloc(bufferSize);
  92. size_t numBytesDecrypted = 0;
  93. CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
  94. kCCOptionPKCS7Padding | kCCOptionECBMode,
  95. keyPtr, kCCBlockSizeDES,
  96. NULL,
  97. [data bytes], dataLength,
  98. buffer, bufferSize,
  99. &numBytesDecrypted);
  100. if (cryptStatus == kCCSuccess) {
  101. return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
  102. }
  103. free(buffer);
  104. return nil;
  105. }
  106. /************************************************************
  107. 函数名称 : + (NSData *)dataWithBase64EncodedString:(NSString *)string
  108. 函数描述 : base64格式字符串转换为文本数据
  109. 输入参数 : (NSString *)string
  110. 输出参数 : N/A
  111. 返回参数 : (NSData *)
  112. 备注信息 :
  113. **********************************************************/
  114. + (NSData *)dataWithBase64EncodedString:(NSString *)string
  115. {
  116. if (string == nil)
  117. [NSException raise:NSInvalidArgumentException format:@""];
  118. if ([string length] == 0)
  119. return [NSData data];
  120. static char *decodingTable = NULL;
  121. if (decodingTable == NULL)
  122. {
  123. decodingTable = malloc(256);
  124. if (decodingTable == NULL)
  125. return nil;
  126. memset(decodingTable, CHAR_MAX, 256);
  127. NSUInteger i;
  128. for (i = 0; i < 64; i++)
  129. decodingTable[(short)encodingTable[i]] = i;
  130. }
  131. const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
  132. if (characters == NULL) // Not an ASCII string!
  133. return nil;
  134. char *bytes = malloc((([string length] + 3) / 4) * 3);
  135. if (bytes == NULL)
  136. return nil;
  137. NSUInteger length = 0;
  138. NSUInteger i = 0;
  139. while (YES)
  140. {
  141. char buffer[4];
  142. short bufferLength;
  143. for (bufferLength = 0; bufferLength < 4; i++)
  144. {
  145. if (characters[i] == '\0')
  146. break;
  147. if (isspace(characters[i]) || characters[i] == '=')
  148. continue;
  149. buffer[bufferLength] = decodingTable[(short)characters[i]];
  150. if (buffer[bufferLength++] == CHAR_MAX) // Illegal character!
  151. {
  152. free(bytes);
  153. return nil;
  154. }
  155. }
  156. if (bufferLength == 0)
  157. break;
  158. if (bufferLength == 1) // At least two characters are needed to produce one byte!
  159. {
  160. free(bytes);
  161. return nil;
  162. }
  163. // Decode the characters in the buffer to bytes.
  164. bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
  165. if (bufferLength > 2)
  166. bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
  167. if (bufferLength > 3)
  168. bytes[length++] = (buffer[2] << 6) | buffer[3];
  169. }
  170. bytes = realloc(bytes, length);
  171. return [NSData dataWithBytesNoCopy:bytes length:length];
  172. }
  173. /************************************************************
  174. 函数名称 : + (NSString *)base64EncodedStringFrom:(NSData *)data
  175. 函数描述 : 文本数据转换为base64格式字符串
  176. 输入参数 : (NSData *)data
  177. 输出参数 : N/A
  178. 返回参数 : (NSString *)
  179. 备注信息 :
  180. **********************************************************/
  181. + (NSString *)base64EncodedStringFrom:(NSData *)data
  182. {
  183. if ([data length] == 0)
  184. return @"";
  185. char *characters = malloc((([data length] + 2) / 3) * 4);
  186. if (characters == NULL)
  187. return nil;
  188. NSUInteger length = 0;
  189. NSUInteger i = 0;
  190. while (i < [data length])
  191. {
  192. char buffer[3] = {0,0,0};
  193. short bufferLength = 0;
  194. while (bufferLength < 3 && i < [data length])
  195. buffer[bufferLength++] = ((char *)[data bytes])[i++];
  196. // Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
  197. characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
  198. characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
  199. if (bufferLength > 1)
  200. characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
  201. else characters[length++] = '=';
  202. if (bufferLength > 2)
  203. characters[length++] = encodingTable[buffer[2] & 0x3F];
  204. else characters[length++] = '=';
  205. }
  206. return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
  207. }
  208. //加密
  209. +(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key;
  210. {
  211. NSString *ciphertext = nil;
  212. const char *textBytes = [plainText UTF8String];
  213. NSUInteger dataLength = [plainText length];
  214. unsigned char buffer[1024];
  215. memset(buffer, 0, sizeof(char));
  216. size_t numBytesEncrypted = 0;
  217. CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
  218. kCCOptionPKCS7Padding,
  219. [key UTF8String], kCCKeySizeDES,
  220. NULL,
  221. textBytes, dataLength,
  222. buffer, 1024,
  223. &numBytesEncrypted);
  224. if (cryptStatus == kCCSuccess) {
  225. NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
  226. ciphertext = [self dataTohexString:data];
  227. }
  228. return ciphertext;
  229. }
  230. //解密
  231. +(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key
  232. {
  233. NSString *cleartext = nil;
  234. NSData *textData = [self hexStringToData:plainText];
  235. NSUInteger dataLength = [textData length];
  236. unsigned char buffer[1024];
  237. memset(buffer, 0, sizeof(char));
  238. size_t numBytesEncrypted = 0;
  239. CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,kCCOptionPKCS7Padding,
  240. [key UTF8String], kCCKeySizeDES,
  241. NULL,
  242. [textData bytes] , dataLength,
  243. buffer, 1024,
  244. &numBytesEncrypted);
  245. if (cryptStatus == kCCSuccess) {
  246. //NSLog(@"DES解密成功");
  247. NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
  248. cleartext = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  249. }else{
  250. //NSLog(@"DES解密失败");
  251. }
  252. return cleartext;
  253. }
  254. + (NSString *)dataTohexString:(NSData*)data
  255. {
  256. Byte *bytes = (Byte *)[data bytes];
  257. NSString *hexStr=@"";
  258. for(int i=0;i<[data length];i++)
  259. {
  260. int intTmp = bytes[i];
  261. // 把负数转换为正数
  262. if (intTmp < 0) {
  263. intTmp = intTmp + 256;
  264. }
  265. NSString *newHexStr = [NSString stringWithFormat:@"%x",intTmp&0xff];//16进制数
  266. // 小于0F的数需要在前面补0
  267. if (intTmp < 16) {
  268. hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
  269. }else{
  270. hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
  271. }
  272. // NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];//16进制数
  273. // int intTmp = [newHexStr intValue];
  274. //
  275. // if (intTmp < 0) {
  276. // intTmp = intTmp + 256;
  277. // }
  278. // NSLog(@"---->%@---->%d",newHexStr,intTmp);
  279. //
  280. // newHexStr = [NSString stringWithFormat:@"%d",intTmp];
  281. //
  282. // if([newHexStr length]==1)
  283. // hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
  284. // else
  285. // hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
  286. }
  287. return hexStr;
  288. }
  289. + (NSData*)hexStringToData:(NSString*)hexString
  290. {
  291. //NSString *hexString = @"3e435fab9c34891f"; //16进制字符串
  292. int j=0;
  293. Byte bytes[hexString.length]; ///3ds key的Byte 数组, 128位
  294. for(int i=0;i<[hexString length];i++)
  295. {
  296. int int_ch; /// 两位16进制数转化后的10进制数
  297. unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
  298. int int_ch1;
  299. if(hex_char1 >= '0' && hex_char1 <='9')
  300. int_ch1 = (hex_char1-48)*16; //// 0 的Ascll - 48
  301. else if(hex_char1 >= 'A' && hex_char1 <='F')
  302. int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
  303. else
  304. int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
  305. i++;
  306. unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
  307. int int_ch2;
  308. if(hex_char2 >= '0' && hex_char2 <='9')
  309. int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
  310. else if(hex_char1 >= 'A' && hex_char1 <='F')
  311. int_ch2 = hex_char2-55; //// A 的Ascll - 65
  312. else
  313. int_ch2 = hex_char2-87; //// a 的Ascll - 97
  314. int_ch = int_ch1+int_ch2;
  315. //NSLog(@"int_ch=%x",int_ch);
  316. bytes[j] = int_ch; ///将转化后的数放入Byte数组里
  317. j++;
  318. }
  319. // NSData *newData = [[NSData alloc] initWithBytes:bytes length:j];
  320. NSData *newData = [[NSData alloc] initWithBytes:bytes length:j];
  321. //NSLog(@"newData=%@",newData);
  322. return newData;
  323. }
  324. @end