使用方法 先导入头文件 #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. Python 爬虫笔记、多线程、xml解析、基础笔记(不定时更新)

    1  Python学习网址:http://www.runoob.com/python/python-multithreading.html

  2. 【转载】Ubuntu 系列安装 Docker

    系统要求 Docker 支持以下版本的Ubuntu操作系统: Ubuntu Xenial 16.04 (LTS) Ubuntu Wily 15.10 Ubuntu Trusty 14.04 (LTS) ...

  3. Apache中,同一IP使用多域名对应多个网站的方法

    首先dns中确定有相应的A记录, abc  IN A   211.154.2.5 mail IN A   211.154.2.5 这个讲的是在windows下面配置apache虚拟主机: 一.配置虚拟 ...

  4. vector族函数

     本文原创,转载请注明出处,本人Q1273314690 vector(mode = "logical", length = 0) as.vector(x, mode = " ...

  5. superF12

    superF12是开发内嵌ie内核的桌面客户端时的一个调试工具

  6. lua练手基础

    lua的库文件地址: http://luaforge.net/projects/lua官网 http://lua.org --[[ print string. multiple line commen ...

  7. CodeForces 615B Longtail Hedgehog

    题目: http://codeforces.com/problemset/problem/615/B 题意:题目描述很复杂,但实际上很简单.大意就是连续的几个点组成尾巴,要求尾巴的长度乘以尾巴终点的分 ...

  8. JVM内存模型和关键参数设置

    一. JVM内存模型: Jvm内存模型是学好Java很重要的一部分,该部分学习能让我们在系统运维的时候,或者优化服务器的时候能够有方法,懂原理. 二. Jvm关键参数: 1. 堆大小设置参数: -Xm ...

  9. maven工程通过命令打包

    dos下cd到pom.xml所在的目录,输入maven命令:mvn clean package,回车即可. 会打成一个.war包在target文件夹下.

  10. python os.path模块常用方法详解:转:http://wangwei007.blog.51cto.com/68019/1104940

    1.os.path.abspath(path) 返回path规范化的绝对路径. >>> os.path.abspath('test.csv') 'C:\\Python25\\test ...