使用方法 先导入头文件 #import "NSData+AES.h"

//AES测试
//用来密钥
NSString *key = @"";
//用来发送的原始数据
NSString *secret = @"I Love You";
//数据转码
NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
//用密钥加密
NSData *cipher = [plain AES256EncryptWithKey:key]; //输出测试
NSLog(@"%@",[cipher newStringInBase64FromData]);
printf("%s\n", [[cipher description] UTF8String]);
//打印出null,这是因为没有解密
NSLog(@"%@", [[NSString alloc] initWithData:cipher encoding:NSUTF8StringEncoding]); //解密方法
plain = [cipher AES256DecryptWithKey:key];
printf("%s\n", [[plain description] UTF8String]);
NSLog(@"%@", [[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding]);

自建NSData类别 命名AES

NSData+AES.h

#import <Foundation/Foundation.h>

@interface NSData (AES)

- (NSData *)AES256EncryptWithKey:(NSString *)key;   //加密

- (NSData *)AES256DecryptWithKey:(NSString *)key;   //解密

- (NSString *)newStringInBase64FromData;            //追加64编码

+ (NSString*)base64encode:(NSString*)str;           //同上64编码

@end

NSData+AES.m

#import "NSData+AES.h"
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h> static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; @implementation NSData (AES) - (NSData *)AES256EncryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding) // fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [self length]; //See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize); size_t numBytesEncrypted = ;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
} free(buffer); //free the buffer;
return nil;
} - (NSData *)AES256DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding) // fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [self length]; //See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize); size_t numBytesDecrypted = ;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted); if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
} free(buffer); //free the buffer;
return nil;
} - (NSString *)newStringInBase64FromData //追加64编码
{
NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
unsigned char * working = (unsigned char *)[self bytes];
int srcLen = [self length];
for (int i=; i<srcLen; i += ) {
for (int nib=; nib<; nib++) {
int byt = (nib == )?:nib-;
int ix = (nib+)*;
if (i+byt >= srcLen) break;
unsigned char curr = ((working[i+byt] << (-ix)) & 0x3F);
if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
[dest appendFormat:@"%c", base64[curr]];
}
}
return dest;
} + (NSString*)base64encode:(NSString*)str
{
if ([str length] == )
return @"";
const char *source = [str UTF8String];
int strlength = strlen(source);
char *characters = malloc(((strlength + ) / ) * );
if (characters == NULL)
return nil;
NSUInteger length = ;
NSUInteger i = ;
while (i < strlength) {
char buffer[] = {,,};
short bufferLength = ;
while (bufferLength < && i < strlength)
buffer[bufferLength++] = source[i++];
characters[length++] = base64[(buffer[] & 0xFC) >> ];
characters[length++] = base64[((buffer[] & 0x03) << ) | ((buffer[] & 0xF0) >> )];
if (bufferLength > )
characters[length++] = base64[((buffer[] & 0x0F) << ) | ((buffer[] & 0xC0) >> )];
else characters[length++] = '=';
if (bufferLength > )
characters[length++] = base64[buffer[] & 0x3F];
else characters[length++] = '=';
}
NSString *g = [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
return g;
} @end

iOS AES加密解密实现方法的更多相关文章

  1. ios常见加密解密方法

    在其他平台中经常会计算MD5值,在iOS平台中也提供了该方法,首先需要导入头文件 #import <CommonCrypto/CommonDigest.h> 方法CC_MD5可以获取MD5 ...

  2. AES简单加密解密的方法实现

    package com.mstf.aes; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyEx ...

  3. ruby AES加密解密

    最近和京东合作做一个项目,在接口对接传递参数时,参数需要通过AES加密解密. 本来想到用gem 'aescrypt'处理,但是aescrypt的编码方式用的base64,而京东那边用的是16进制.所以 ...

  4. openssl与cryptoAPI交互AES加密解密

    继上次只有CryptoAPI的加密后,这次要实现openssl的了 动机:利用CryptoAPI制作windows的IE,火狐和chrome加密控件后,这次得加上与android的加密信息交互 先前有 ...

  5. AES加密解密——AES在JavaWeb项目中前台JS加密,后台Java解密的使用

    一:前言 在软件开发中,经常要对数据进行传输,数据在传输的过程中可能被拦截,被监听,所以在传输数据的时候使用数据的原始内容进行传输的话,安全隐患是非常大的.因此就要对需要传输的数据进行在客户端进行加密 ...

  6. Java 关于密码处理的工具类[MD5编码][AES加密/解密]

    项目中又遇到了加密问题,又去翻了半天,然后做测试,干脆就把常用的两类小结一下. 1.第一种所谓的MD5加密 其实也不算加密,只是基于Hash算法的不可逆编码而已,等于说,一旦经过MD5处理,是不可能从 ...

  7. C# 实现 JAVA AES加密解密[原创]

    以下是网上普遍能收到的JAVA AES加密解密方法. 因为里面用到了KeyGenerator 和 SecureRandom,但是.NET 里面没有这2个类.无法使用安全随机数生成KEY. 我们在接收J ...

  8. 你真的了解字典(Dictionary)吗? C# Memory Cache 踩坑记录 .net 泛型 结构化CSS设计思维 WinForm POST上传与后台接收 高效实用的.NET开源项目 .net 笔试面试总结(3) .net 笔试面试总结(2) 依赖注入 C# RSA 加密 C#与Java AES 加密解密

    你真的了解字典(Dictionary)吗?   从一道亲身经历的面试题说起 半年前,我参加我现在所在公司的面试,面试官给了一道题,说有一个Y形的链表,知道起始节点,找出交叉节点.为了便于描述,我把上面 ...

  9. Aes 加密解密 java加密解密

    使用AES加密解密代码详解 首先,如果是使用nodejs + vue 写的前端, 那么你需要npm 加载一个js文件 npm i crypto-js --save --save-exact npm i ...

随机推荐

  1. firefox的plugin-container.exe进程如何关闭?

    为什么要关闭container进程? 查看firefox所消耗的资源: ff本身: cpu一般是0-10%, 内存一般是400MB左右 plugin-container: cpu所占的比例很高, 可达 ...

  2. 一次关于使用status作为变量引发的bug及思考

    这个bug出现在一年前,当时自己大学还没毕业,刚刚进入一家公司实习.那个时候还没有用seajs或者requirejs那样的模块化管理的库,也没有用一个自执行的函数将要执行的代码包裹起来,于是bug就在 ...

  3. POJ 2155 Matrix

    二维树状数组....                          Matrix Time Limit: 3000MS   Memory Limit: 65536K Total Submissio ...

  4. Codeforces Round #270 1002

    Codeforces Round #270 1002 B. Design Tutorial: Learn from Life time limit per test 1 second memory l ...

  5. Inno Setup制作应用程序安装包

    我最近写了一个MFC应用程序,想发给其他的小伙伴玩一玩,直接发了个exe文件过去,结果发现小伙伴那边打不开.原来这个exe文件虽然是MFC静态编译的,但是还依赖了其他几个.dll文件,需要把这几个dl ...

  6. 第一天 django

    全栈增长工程师实战 http://growth-in-action.phodal.com/ 生成的代码和示例不一样,static 也要加上 from django.conf.urls import u ...

  7. SQL按指定文字顺序进行排序(中文或数字等)

    在有些情况下我们需要按指定顺序输出数据,比如选择了ID in(3,1,2,5,4)我们希望按这个3,1,2,5,4的顺序输出,这样只使用order by ID是无法实现的, 但是我们可以使用order ...

  8. UOJ#35 —— 后缀排序

    1.题目大意:后缀数组模板题 2.分析:汝佳的书上的代码的有bug,还有那个n是字符串长度+1,''也要加入排序的 存个模板QAQ #include <cstdio> #include & ...

  9. 关于JavaScript的浅拷贝和深拷贝

    在 JS 中有一些基本类型像是Number.String.Boolean,而对象就是像这样的东西{ name: 'Larry', skill: 'Node.js' },对象跟基本类型最大的不同就在于他 ...

  10. angularjs入门基础一

    app.controller('firstController',function($scope,$rootScope){ $scope.name='张三'; $rootScope.age='30'; ...