IOS加密 AES 256算法(EncryptAndDecrypt.h)

举报
清雨小竹 发表于 2022/09/25 04:16:12 2022/09/25
【摘要】 EncryptAndDecrypt.h#import <Foundation/Foundation.h> @class NSString; @interface NSData (Encryption) - (NSData *)AES256EncryptWithKey:(NSData *)key; //加密 - (NSDa...

  
  1. EncryptAndDecrypt.h
  2. #import <Foundation/Foundation.h>
  3. @class NSString;
  4. @interface NSData (Encryption)
  5. - (NSData *)AES256EncryptWithKey:(NSData *)key; //加密
  6. - (NSData *)AES256DecryptWithKey:(NSData *)key; //解密
  7. - (NSString *)newStringInBase64FromData; //追加64编码
  8. + (NSString*)base64encode:(NSString*)str; //同上64编码
  9. +(NSData*)stringToByte:(NSString*)string;
  10. +(NSString*)byteToString:(NSData*)data;
  11. @end




  
  1. ///EncryptAndDecrypt.m
  2. #import "EncryptAndDecrypt.h"
  3. #import <CommonCrypto/CommonCrypto.h>
  4. static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5. @implementation NSData (Encryption)
  6. - (NSData *)AES256EncryptWithKey:(NSData *)key //加密
  7. {
  8. //AES256加密,密钥应该是32位的
  9. const void * keyPtr2 = [key bytes];
  10. char (*keyPtr)[32] = keyPtr2;
  11. //对于块加密算法,输出大小总是等于或小于输入大小加上一个块的大小
  12. //所以在下边需要再加上一个块的大小
  13. NSUInteger dataLength = [self length];
  14. size_t bufferSize = dataLength + kCCBlockSizeAES128;
  15. void *buffer = malloc(bufferSize);
  16. size_t numBytesEncrypted = 0;
  17. CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
  18. kCCOptionPKCS7Padding/*这里就是刚才说到的PKCS7Padding填充了*/| kCCOptionECBMode,
  19. [key bytes], kCCKeySizeAES256,
  20. NULL,/* 初始化向量(可选) */
  21. [self bytes], dataLength,/*输入*/
  22. buffer, bufferSize,/* 输出 */
  23. &numBytesEncrypted);
  24. if (cryptStatus == kCCSuccess) {
  25. return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
  26. }
  27. free(buffer);//释放buffer
  28. return nil;
  29. }
  30. - (NSData *)AES256DecryptWithKey:(NSData *)key //解密
  31. {
  32. //同理,解密中,密钥也是32位的
  33. const void * keyPtr2 = [key bytes];
  34. char (*keyPtr)[32] = keyPtr2;
  35. //对于块加密算法,输出大小总是等于或小于输入大小加上一个块的大小
  36. //所以在下边需要再加上一个块的大小
  37. NSUInteger dataLength = [self length];
  38. size_t bufferSize = dataLength + kCCBlockSizeAES128;
  39. void *buffer = malloc(bufferSize);
  40. size_t numBytesDecrypted = 0;
  41. CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
  42. kCCOptionPKCS7Padding/*这里就是刚才说到的PKCS7Padding填充了*/| kCCOptionECBMode,
  43. keyPtr, kCCKeySizeAES256,
  44. NULL,/* 初始化向量(可选) */
  45. [self bytes], dataLength,/* 输入 */
  46. buffer, bufferSize,/* 输出 */
  47. &numBytesDecrypted);
  48. if (cryptStatus == kCCSuccess) {
  49. return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
  50. }
  51. free(buffer);
  52. return nil;
  53. }
  54. - (NSString *)newStringInBase64FromData //追加64编码
  55. {
  56. NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
  57. unsigned char * working = (unsigned char *)[self bytes];
  58. int srcLen = [self length];
  59. for (int i=0; i<srcLen; i += 3) {
  60. for (int nib=0; nib<4; nib++) {
  61. int byt = (nib == 0)?0:nib-1;
  62. int ix = (nib+1)*2;
  63. if (i+byt >= srcLen) break;
  64. unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);
  65. if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
  66. [dest appendFormat:@"%c", base64[curr]];
  67. }
  68. }
  69. return dest;
  70. }
  71. + (NSString*)base64encode:(NSString*)str
  72. {
  73. if ([str length] == 0)
  74. return @"";
  75. const char *source = [str UTF8String];
  76. int strlength = strlen(source);
  77. char *characters = malloc(((strlength + 2) / 3) * 4);
  78. if (characters == NULL)
  79. return nil;
  80. NSUInteger length = 0;
  81. NSUInteger i = 0;
  82. while (i < strlength) {
  83. char buffer[3] = {0,0,0};
  84. short bufferLength = 0;
  85. while (bufferLength < 3 && i < strlength)
  86. buffer[bufferLength++] = source[i++];
  87. characters[length++] = base64[(buffer[0] & 0xFC) >> 2];
  88. characters[length++] = base64[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
  89. if (bufferLength > 1)
  90. characters[length++] = base64[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
  91. else characters[length++] = '=';
  92. if (bufferLength > 2)
  93. characters[length++] = base64[buffer[2] & 0x3F];
  94. else characters[length++] = '=';
  95. }
  96. NSString *g = [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
  97. return g;
  98. }
  99. +(NSData*)stringToByte:(NSString*)string
  100. {
  101. NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
  102. if ([hexString length]%2!=0) {
  103. return nil;
  104. }
  105. Byte tempbyt[1]={0};
  106. NSMutableData* bytes=[NSMutableData data];
  107. for(int i=0;i<[hexString length];i++)
  108. {
  109. unichar hex_char1 = [hexString characterAtIndex:i]; 两位16进制数中的第一位(高位*16)
  110. int int_ch1;
  111. if(hex_char1 >= '0' && hex_char1 <='9')
  112. int_ch1 = (hex_char1-48)*16; 0 的Ascll - 48
  113. else if(hex_char1 >= 'A' && hex_char1 <='F')
  114. int_ch1 = (hex_char1-55)*16; A 的Ascll - 65
  115. else
  116. return nil;
  117. i++;
  118. unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
  119. int int_ch2;
  120. if(hex_char2 >= '0' && hex_char2 <='9')
  121. int_ch2 = (hex_char2-48); 0 的Ascll - 48
  122. else if(hex_char2 >= 'A' && hex_char2 <='F')
  123. int_ch2 = hex_char2-55; A 的Ascll - 65
  124. else
  125. return nil;
  126. tempbyt[0] = int_ch1+int_ch2; ///将转化后的数放入Byte数组里
  127. [bytes appendBytes:tempbyt length:1];
  128. }
  129. return bytes;
  130. }
  131. +(NSString*)byteToString:(NSData*)data
  132. {
  133. Byte *plainTextByte = (Byte *)[data bytes];
  134. NSString *hexStr=@"";
  135. for(int i=0;i<[data length];i++)
  136. {
  137. NSString *newHexStr = [NSString stringWithFormat:@"%x",plainTextByte[i]&0xff];///16进制数
  138. if([newHexStr length]==1)
  139. hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
  140. else
  141. hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
  142. }
  143. return hexStr;
  144. }
  145. @end


使用


  
  1. -(void)Jiami
  2. {
  3. NSString *plainText = @"AES中国";//明文
  4. NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
  5. NSString *keyStr = @"12345678901234567890123456789012";
  6. NSData *keyDataStr = [keyStr dataUsingEncoding:NSUTF8StringEncoding];
  7. NSData *cipherTextData = [plainTextData AES256EncryptWithKey:keyDataStr];
  8. NSString *hexStr = [NSData byteToString:cipherTextData];
  9. NSLog(@"密文:%@",hexStr);
  10. [self Jiemi:hexStr];
  11. }
  12. -(void)Jiemi:(NSString *)hexString
  13. {
  14. NSString *keyStr = @"12345678901234567890123456789012";
  15. NSData *keyDataStr = [keyStr dataUsingEncoding:NSUTF8StringEncoding];
  16. NSData *data = [NSData stringToByte:hexString];
  17. /
  18. NSData *datas = [data AES256DecryptWithKey:keyDataStr];
  19. NSLog([[NSString alloc]initWithData:datas encoding:NSUTF8StringEncoding]);
  20. }

http://blog.csdn.net/pjk1129/article/details/8489550

文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。

原文链接:zzzili.blog.csdn.net/article/details/8610060

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。