当前位置: 首页 > news >正文

aes加密iOS 实现

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

Encryption.h文件 

 

#import <Foundation/Foundation.h> 

@class NSString; 

@interface NSData (Encryption) 

- (NSData *)AES256EncryptWithKey:(NSString *)key;   //加密- (NSData *)AES256DecryptWithKey:(NSString *)key;   //解密- (NSString *)newStringInBase64FromData;            //追加64编码+ (NSString*)base64encode:(NSString*)str;           //同上64编码

 @end

 ------------------------------------------------------------------------------------------------

 Encryption.m文件 

#import "Encryption.h"#import <CommonCrypto/CommonCryptor.h> 

 

static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 

@implementation NSData (Encryption) 

- (NSData *)AES256EncryptWithKey:(NSString *)key {    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // 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 = 0;
    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+1]; // 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 = 0;
    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=0; i<srcLen; i += 3) {        for (int nib=0; nib<4; nib++) {            int byt = (nib == 0)?0:nib-1;            int ix = (nib+1)*2;            if (i+byt >= srcLen) break;

            unsigned char curr = ((working[i+byt] << (8-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] == 0)        return @"";    const char *source = [str UTF8String];    int strlength  = strlen(source);    char *characters = malloc(((strlength + 2) / 3) * 4);    if (characters == NULL)        return nil;

    NSUInteger length = 0;

    NSUInteger i = 0;    while (i < strlength) {        char buffer[3] = {0,0,0};        short bufferLength = 0;        while (bufferLength < 3 && i < strlength)

            buffer[bufferLength++] = source[i++];

        characters[length++] = base64[(buffer[0] & 0xFC) >> 2];

        characters[length++] = base64[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];        if (bufferLength > 1)

            characters[length++] = base64[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];        else characters[length++] = '=';        if (bufferLength > 2)

            characters[length++] = base64[buffer[2] & 0x3F];        else characters[length++] = '=';

    }

    NSString *g = [[[NSString alloc] initWithBytesNoCopy:characters length:lengthencoding:NSASCIIStringEncoding freeWhenDone:YES] autorelease];    return g;

} 

 

@end

 ------------------------------------------------------------------------------------------------

 测试代码 

 

#import "Encryption.h"
 

    NSString *key = @"my password";

    NSString *secret = @"text to encrypt";    //加密
    NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];

    NSData *cipher = [plain AES256EncryptWithKey:key];

    NSLog(@"%@",[[cipher newStringInBase64FromData] autorelease]);

    printf("%s\n", [[cipher description] UTF8String]);

    NSLog(@"%@", [[[NSString alloc] initWithData:cipher encoding:NSUTF8StringEncoding] autorelease]);//打印出null,这是因为没有解密。    //解密
    plain = [cipher AES256DecryptWithKey:key];

    printf("%s\n", [[plain description] UTF8String]);

    NSLog(@"%@", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] autorelease]);    //打印出secret的内容,用密码解密过了。如果使用错误的密码,则打印null

复制代码

  • AESEncryption.zip (53.8 KB)

  • 下载次数: 22

 

 

复制代码

i am new in Objective c.My problem is how to convert image to Byte array[Encoding].Similarly how to convert Byte array to Image[Decoding]...In C i am using the Following code for Encoding and Decoding purpose...
#include <stdio.h>#include <stdlib.h>/*** Translation Table as described in RFC1113*/static const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz0123456789+/";/*** Translation Table to decode (created by author)*/static const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW $$$$$$XYZ[\\]^_`abcdefghijklmnopq";/*** encodeblock
**
** encode 3 8-bit binary bytes as 4 '6-bit' characters*/void encodeblock( unsigned char in[3], unsigned char out[4], int len )
{out[0] = cb64[ in[0] >> 2 ];out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];out[2] = (unsigned char) (len > 1 ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '=');out[3] = (unsigned char) (len > 2 ? cb64[ in[2] & 0x3f ] : '=');
}/*** encode
**
** base64 encode a stream adding padding and line breaks as per spec.*/void encode( FILE *infile, FILE *outfile, int linesize )
{
unsigned char in[3], out[4];int i, len, blocksout = 0;while( !feof( infile ) ) {
len = 0;for( i = 0; i < 3; i++ ) {in[i] = (unsigned char) getc( infile );if( !feof( infile ) ) {
len++;
}else {in[i] = 0;
}
}if( len ) {
encodeblock( in, out, len );for( i = 0; i < 4; i++ ) {
putc( out[i], outfile );
}
blocksout++;
}if( blocksout >= (linesize/4) || feof( infile ) ) {if( blocksout ) {
fprintf( outfile, "\r\n" );
}
blocksout = 0;
}
}
}/*** decodeblock
**
** decode 4 '6-bit' characters into 3 8-bit binary bytes*/void decodeblock( unsigned char in[4], unsigned char out[3] )
{ 
out[ 0 ] = (unsigned char ) (in[0] << 2 | in[1] >> 4);out[ 1 ] = (unsigned char ) (in[1] << 4 | in[2] >> 2);out[ 2 ] = (unsigned char ) (((in[2] << 6) & 0xc0) | in[3]);
}/*** decode
**
** decode a base64 encoded stream discarding padding, line breaks and noise*/void decode( FILE *infile, FILE *outfile )
{
unsigned char in[4], out[3], v;int i, len;while( !feof( infile ) ) {for( len = 0, i = 0; i < 4 && !feof( infile ); i++ ) {
v = 0;while( !feof( infile ) && v == 0 ) {
v = (unsigned char) getc( infile );
v = (unsigned char) ((v < 43 || v > 122) ? 0 : cd64[ v - 43 ]);if( v ) {
v = (unsigned char) ((v == '$') ? 0 : v - 61);
}
}if( !feof( infile ) ) {
len++;if( v ) {in[ i ] = (unsigned char) (v - 1);
}
}else {in[i] = 0;
}
}if( len ) {
decodeblock( in, out );for( i = 0; i < len - 1; i++ ) {
putc( out[i], outfile );
}
}
}
}

But i don't know in objective c...Pls help me to sort out this issue...



转载于:https://my.oschina.net/u/2329800/blog/512322

相关文章:

  • iOS视频录制,裁剪(输出指定大小)
  • KMP,深入讲解next数组的求解(转载)
  • 初步swift语言学习笔记9(OC与Swift杂)
  • Mysql事务处理
  • UVA 11769 All Souls Night 的三维凸包要求的表面面积
  • html: Table合并行和列
  • win10升级提示图标的四种关闭方法
  • window平台下的MySQL快速安装。(不好意思,未完成待续,请飘过)
  • 教您如何检查oracle死锁,决解死锁
  • openlayers限制地图拖动区域
  • 测试人员的职业修养
  • 批生产数据库
  • 彩色图像--色彩空间 HSI(HSL)、HSV(HSB)
  • java中Map,List与Set的区别
  • 利用print2flashsetup.exe文档转swf
  • CentOS7简单部署NFS
  • CSS 提示工具(Tooltip)
  • es6
  • Hexo+码云+git快速搭建免费的静态Blog
  • JavaScript 一些 DOM 的知识点
  • Java深入 - 深入理解Java集合
  • js中的正则表达式入门
  • k8s 面向应用开发者的基础命令
  • 基于OpenResty的Lua Web框架lor0.0.2预览版发布
  • 聚簇索引和非聚簇索引
  • 开发了一款写作软件(OSX,Windows),附带Electron开发指南
  • 如何选择开源的机器学习框架?
  • 我有几个粽子,和一个故事
  • 移动端解决方案学习记录
  • [地铁译]使用SSD缓存应用数据——Moneta项目: 低成本优化的下一代EVCache ...
  • 如何通过报表单元格右键控制报表跳转到不同链接地址 ...
  • ​LeetCode解法汇总307. 区域和检索 - 数组可修改
  • ​学习一下,什么是预包装食品?​
  • # Swust 12th acm 邀请赛# [ K ] 三角形判定 [题解]
  • #100天计划# 2013年9月29日
  • #QT(一种朴素的计算器实现方法)
  • (C语言)输入自定义个数的整数,打印出最大值和最小值
  • (delphi11最新学习资料) Object Pascal 学习笔记---第5章第5节(delphi中的指针)
  • (第61天)多租户架构(CDB/PDB)
  • (附源码)ssm基于jsp的在线点餐系统 毕业设计 111016
  • (剑指Offer)面试题34:丑数
  • (蓝桥杯每日一题)love
  • (转)Android学习笔记 --- android任务栈和启动模式
  • (转)Java socket中关闭IO流后,发生什么事?(以关闭输出流为例) .
  • (转)jQuery 基础
  • (转)Oracle 9i 数据库设计指引全集(1)
  • (转)母版页和相对路径
  • .NET core 自定义过滤器 Filter 实现webapi RestFul 统一接口数据返回格式
  • .NET Framework与.NET Framework SDK有什么不同?
  • .Net Web窗口页属性
  • .net 验证控件和javaScript的冲突问题
  • .NET/C# 如何获取当前进程的 CPU 和内存占用?如何获取全局 CPU 和内存占用?
  • /usr/lib/mysql/plugin权限_给数据库增加密码策略遇到的权限问题
  • @Conditional注解详解
  • @Responsebody与@RequestBody