使用方法 先导入头文件 #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. css外边距合并和z-index的问题

    参考这篇文章, 将外边距的 折叠 参考这篇文章, 将bfc的生成, bfc的应用 参考这篇文章 position: absolute的元素, 仍然具有内填充padding和border边框属性样式, ...

  2. 关于Windows下安装mongodb和加入Windows系统启动项

    .首先:在http://www.mongodb.org/downloads官网下载最新的win版本的mongodb下载包(我下载到d盘) .加压缩,修改文件夹名字为mongodb,建立放数据库文件夹w ...

  3. jquery音乐播放器(歌词滚动版)

    好久没出来水了!!!忙忙碌碌的找工作~然后中秋节也算过了,祝各位coding们,直接觉醒第七感小宇宙,直接用心就能找到bug-_-// 最后如题这是一篇很正规的coding的文章 大概么比以前的加了个 ...

  4. IGV软件

    它支持各种各样的数据类型,包括基于芯片测序.二代测序数据和基因组注释数据等.整合基因组浏览器(IGV,Integrative Genomics Viewer)进行可视化浏览,它支持各种各式的数据类型, ...

  5. ajax异步提交数据动态更改select选项

    <!DOCTYPE html> <html> <head> <title></title> <script src="../ ...

  6. XH

    1.  又到父亲节,那就给老爹做顿饭呗,让他开心开心. 老爸吃了一口我炒的菜,流露出感动的泪花说:儿呀,你能为爸爸做饭,爸爸感到特别开心,但是你这个菜,看在今天是父亲节 我能不能不吃呀! 2.  一哥 ...

  7. 京东云、新浪微博等专家畅谈Docker未来格局:开放与竞争(下)

    在上次推送的文章中(传送门),田琪老师分享了他的DockerCon 2015峰会见闻.在“QCon高可用架构群”中,田老师分享之后,几位专家也参与了讨论.他们是: 闫国旗:京东资深架构师,京东架构技术 ...

  8. DAY3 python群发短信

    手机轰炸,burpsuit 抓取注册页面输入的手机号,然后每点击一次forword ,都开开始放行,发短信.也可以发到repeat 里面进行 ,重复发送短信. import requests impo ...

  9. 使用 Github Pages 发布你的项目文档

    导读 你可能比较熟悉如何用 Github Pages 来分享你的工作,又或许你看过一堂教你建立你的第一个 Github Pages 网站的教程.近期 Github Pages 的改进使得从不同的数据源 ...

  10. python del 注意点

    >>> del a[:] >>> a [] del也可以用于删除整个变量: >>> >>> del a 之后再引用名称 a 将会 ...