iOS AES加密解密实现方法

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

//AES测试
//用来密钥
NSString *key = @"123456";
//用来发送的原始数据
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+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:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
    return g;
}

@end
时间: 2024-10-23 15:42:24

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

ios常见加密解密方法

在其他平台中经常会计算MD5值,在iOS平台中也提供了该方法,首先需要导入头文件 [cpp] view plain copy #import <CommonCrypto/CommonDigest.h> 方法CC_MD5可以获取MD5的16个字符的数组,再通过%02X的形式输出即可获取32位MD5值. [cpp] view plain copy @implementation NSString (CCCryptUtil) -(NSString*) md5 { const char * cStrV

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

package com.mstf.aes; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypt

iOS之AES加密解密

//AES加密解密#import <CommonCrypto/CommonCrypto.h>#import <CommonCrypto/CommonDigest.h> //AES128位加密 base64编码 注:kCCKeySizeAES128点进去可以更换256位加密 -(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key { char keyPtr[kCCKeySizeAES128+1];//

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

项目中又遇到了加密问题,又去翻了半天,然后做测试,干脆就把常用的两类小结一下. 1.第一种所谓的MD5加密 其实也不算加密,只是基于Hash算法的不可逆编码而已,等于说,一旦经过MD5处理,是不可能从编码后的字符串反推回去的. MD5的方法是基于散列的.本身信息不全.理论上是不能还原成唯一字符串的. 网上所谓的解密,也只是拥有一个足够大的字典映射,将编码前的源字符和编码后的目标字符关联起来而已,大多数常见的还行,复杂点的估计就会话费很长时间,有兴趣的可以试试. 至于MD5的用法,在初次录入的时候

ruby AES加密解密

最近和京东合作做一个项目,在接口对接传递参数时,参数需要通过AES加密解密. 本来想到用gem 'aescrypt'处理,但是aescrypt的编码方式用的base64,而京东那边用的是16进制.所以就自己写了加密解密方法. AES 加密 def aes_encrypt(key, encrypted_string) aes = OpenSSL::Cipher::Cipher.new("AES-128-ECB") aes.encrypt aes.key = key txt = aes.u

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

以下是网上普遍能收到的JAVA AES加密解密方法. 因为里面用到了KeyGenerator 和 SecureRandom,但是.NET 里面没有这2个类.无法使用安全随机数生成KEY. 我们在接收JAVA发送的AES加密字符串后,在.NET没有对应的KeyGenerator 和 SecureRandom去生成AES 的 KEY值,导致无法直接解密. 1 import java.security.SecureRandom; 2 import java.util.Base64; 3 4 impor

unity3d与flash交互、aes加密解密

众所周知,unity在2013年就放弃flash了,但是有时候,真的会需要到flash,比如web端需要unity web player插件,很多浏览器都拦截了,flash倒不会,因为他是微软的. u3d在打包flash的时候api是不可以修改的,默认就是flash的api,打包出来就是as(ActionScript代码)编译.所以很多net2.0的api都不能使用,比如System.Security.Cryptography这个库,注:这个库是C#集成好的加密解密 u3d导出flash会报错,

ios RSA加密解密一些相关问题

前言: 最近在做一个类似支付宝的理财项目,涉及到了RSA加解密方面的知识,在这里也遇到了不少的问题.写出来与大家分享心得. 1.什么是RSA加密解密(ios RSA加密解密过程) 这些网上都说的很清楚,大家可以从网上查找一下. 理论上是可以用公钥加密,私钥解密,或者是私钥加密,公钥解密. 我的理解是:A向B请求数据:A把自己的信息用私钥签名,并且把自己的公钥传送给B, B受到A的数据:B将A的公钥取出,并且用A的公钥确认签名, B向A发送数据:B将自己的数据用A公钥加密,再将自己的公钥暴露给A,

【加密解密】-AES加密解密实现

先看实现效果,测试代码如下: package org.iti.algorithm; public class AESDemo { public static void main(String[] args) { // 明文 String mingWen = "zhuwenfei"; // 密钥 String pwd = "123"; // 明文加密得到的密文 String miWen = AESUtils.encrypt(pwd, mingWen); // 输出密文