二、对称加密AES,非对称加密RSA

目录

一、对称加密
 1、对称加密是什么
 2、对称加密的优点
 3、对称加密的问题
 4、对称加密的应用场景
 5、对称加密AES的代码
二、非对称加密
 1、非对称加密是什么
 2、非对称加密的优点
 3、非对称加密的问题
 4、非对称加密的应用场景
 5、非对称加密RSA的代码


一、对称加密


1、对称加密是什么

对称加密是指加密和解密用的是同一个密钥的加密方式。

2、对称加密的优点

对称加密的特点是加密计算量小、速度快。

3、对称加密的问题

对称加密的问题是密钥传输问题,因为对称加密的做法一般是解密方生成密钥传输给加密方,加密方对明文加密,然后把密文发送给解密方,解密方使用密钥对密文解密,得到明文,而密钥在传输过程中很可能被攻击者截获,因此对称加密的安全性就不仅仅取决于加密算法本身的强度,更取决于密钥是否被安全地传输。

4、对称加密的应用场景

对称加密适用于对大量数据进行加密的场景。

5、对称加密AES的代码

AES(Advanced Encryption Standard),高级加密标准,是对称加密的一种,用来代替DES、3DES。AES采用分组密码体制,密钥长度可以是128位16个字节、192位或256位,一共有四种加密模式。

  • 分组密码体制:所谓分组密码体制是指AES会首先把明文切成一段一段的,每段的长度必须是128位16个字节,如果最后一段不够16个字节了,就要用Padding来把这段数据填满16个字节,然后分别对每段数据进行加密,最后再把每段加密数据拼接起来形成最终的密文。而Padding也有三种模式PKCS5、PKCS7和NOPADDING,PKCS5和PKCS7是指分组数据缺少几个字节,就在数据的末尾填充几个字节的几,比如缺少5个字节,就在末尾填充5个字节的5;NoPadding是指不需要填充,也就是说数据的发送方肯定会保证最后一段数据也正好是16个字节。那如果在PKCS5模式下,最后一段数据的内容刚好就是16个16怎么办?那解密端就不知道这一段数据到底是有效数据还是填充数据了,因此对于这种情况,PKCS5模式会自动帮我们在最后一段数据后再添加16个字节的数据,而且填充数据也是16个16,这样解密段就能知道谁是有效数据谁是填充数据了。解密方需要使用和加密方同样的Padding模式,才能准确的识别有效数据和填充数据,我们开发通常采用PKCS7 Padding模式。

  • 密钥:AES要求密钥长度可以是128位16个字节、192位或者256位,位数越高,加密强度自然越大,但是加密的效率自然会低一些。我们开发通常采用128位16个字节的密钥,密钥来源为服务端随机生成、然后发送给客户端,解密方需要使用和加密方同样的密钥。

  • 加密模式:AES一共有四种加密模式,分别是ECB(电子密码本模式)、CBC(密码分组链接模式)、CFB、OFB,我们通常采用CBC加密模式,解密方需要使用和加密方同样的加密模式。

ECB模式:最基本的加密模式,即仅仅使用明文和密钥来加密数据,相同的明文块会被加密成相同的密文块,这样明文和密文的结构将是完全一样的,就会更容易被破解,相对来说不是那么安全,因此很少使用。
CBC模式:比ECB模式多了一个初始向量IV,加密的时候,第一个明文块会首先和初始向量IV做异或操作,然后再经过密钥加密,然后第一个密文块又会作为第二个明文块的加密向量来异或,依次类推下去,这样相同的明文块加密出的密文块就是不同的,明文的结构和密文的结构也将是不同的,因此更加安全,我们常用的就是CBC加密模式。
//
//  EncryptUtil.h
//

#import <Foundation/Foundation.h>

@interface EncryptUtil : NSObject

/**
 * AES128加密,输出Base64编码
 *
 * @param plainText 明文
 * @param secretKey 密钥
 *
 * @return 密文
 */
+ (NSString *)aes128CiphertextFromString:(NSString *)plainText secretKey:(NSString *)secretKey iv:(NSString *)iv;

/**
 * AES128解密,输入Base64编码
 *
 * @param ciphertext 密文
 * @param secretKey 密钥
 *
 * @return 明文
 */
+ (NSString *)aes128PlainTextFromString:(NSString *)ciphertext secretKey:(NSString *)secretKey iv:(NSString *)iv;

@end
//
//  EncryptUtil.m
//

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

@implementation EncryptUtil

+ (NSString *)aes128CiphertextFromString:(NSString *)plainText secretKey:(NSString *)secretKey {
    
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [secretKey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSData *data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    
    int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
    NSUInteger newSize = 0;
    
    if(diff > 0) {
        
        newSize = dataLength + diff;
    }
    
    char dataPtr[newSize];
    memcpy(dataPtr, [data bytes], [data length]);
    for(int i = 0; i < diff; i ++) {
        
        dataPtr[i + dataLength] = 0x00;
    }
    
    size_t bufferSize = newSize + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    memset(buffer, 0, bufferSize);
    
    size_t numBytesCrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, // 加密
                                          kCCAlgorithmAES128, // AES128加密
                                          kCCOptionPKCS7Padding, // PKCS7 Padding模式,默认CBC加密模式
                                          keyPtr, // 密钥
                                          kCCKeySizeAES128, // 密钥长度
                                          NULL, // 初始向量
                                          dataPtr,
                                          sizeof(dataPtr),
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        // 转换成Base64并返回
        return [resultData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    free(buffer);
    return nil;
}

+ (NSString *)aes128PlainTextFromString:(NSString *)ciphertext secretKey:(NSString *)secretKey {
    
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [secretKey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSData *data = [[NSData alloc] initWithBase64EncodedData:[ciphertext dataUsingEncoding:NSUTF8StringEncoding] options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, // 解密
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        // 转换成普通字符串并返回
        return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    }
    free(buffer);
    return nil;
}

@end


二、非对称加密


1、非对称加密是什么

非对称加密是指加密和解密用的不是同一个密钥的加密方式。

2、非对称加密的优点

非对称加密的特点是不存在密钥传输问题,因为非对称加密的做法一般是解密方生成一对儿公私钥,自己保留私钥,把公钥公开,加密方拿到公钥对明文加密,然后把密文发送给解密方,解密方使用私钥对密文解密,得到明文,所以公钥是随便你什么人来拿都行、反正也是用来加密的、又不是用来解密的——即就算被截获了也不怕,只要保管好私钥就可以了。

3、非对称加密的问题

非对称加密的问题是加密计算量大、速度慢。

4、非对称加密的应用场景

非对称加密适用于对少量数据进行加密的场景。

5、非对称加密RSA的代码

RSA加密是非对称加密的一种,密钥长度一般是1024位或2048位。iOS中使用RSA加密解密,需要用到.der文件和.p12文件。其中.der文件存放的是公钥、用于加密,.p12文件存放的是私钥、用于解密。首先我们需要生成这些必要的文件(openssl是SSL/TLS协议的开源实现,可以用来生成公钥私钥、自签名证书等):

// 1、指定文件的存储路径
打开终端,cd一个文件夹

// 2、生成模长为1024位的私钥文件private_key.pem
openssl genrsa -out private_key.pem 1024

// 3、生成证书请求文件rsaCertReq.csr    
// 注意:这一步会提示输入国家、省份、邮箱等信息,可以根据实际情况选择性填写
openssl req -new -key private_key.pem -out rsaCerReq.csr

// 4、生成证书rsaCert.crt,并设置有效时间为10年
openssl x509 -req -days 3650 -in rsaCerReq.csr -signkey private_key.pem -out rsaCert.crt

// 5、生成供iOS使用的公钥文件public_key.der
openssl x509 -outform der -in rsaCert.crt -out public_key.der

// 6、生成供iOS使用的私钥文件private_key.p12  
// 注意:这一步会提示给私钥文件设置密码,保存下来。iOS代码里在解密时,private_key.p12文件需要和这里设置的密码配合使用
openssl pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt

// 7、生成供Java使用的公钥rsa_public_key.pem
openssl rsa -in private_key.pem -out rsa_public_key.pem -pubout

// 8、生成供Java使用的私钥pkcs8_private_key.pem
openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt

// 9、使用文件
这时到指定的文件夹下就可以看到七个文件,
其中public_key.der和private_key.p12这对儿公私钥是供iOS使用的,拖到项目里,
rsa_public_key.pem和pkcs8_private_key.pem这对儿公私钥是供Java使用的,发给他们
它们的根源都来自一个私钥private_key.pem,所以iOS端加密的数据后台可以解密,反过来同理。
//
//  WYRSAEncryptTools.h
//  WYEncryptDemo
//
//  Created by Mac mini on 16/8/23.
//  Copyright © 2016年 yiyi. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface WYRSAEncryptTools : NSObject

// 当我们使用 openssl 生成公钥和私钥之后, 把我们前端需要持有那对文件拖进工程里, 然后使用这个工具类里的几个方法操作起来就 ok 了


#pragma mark - 加载公钥和私钥
/**
 *  加载公钥
 *
 *  @param  string  公钥文件路径
 */
+ (void)loadPublicKeyWithFilePathString:(NSString *)string;

/**
 *  加载私钥
 *
 *  @param  string  私钥文件路径
 *  @param  string  创建私钥时的密码
 */
+ (void)loadPrivateKeyWithFilePathString:(NSString *)string
                                password:(NSString*)password;


#pragma mark - 公钥加密

/**
 *  用来加密字符串
 *
 *  @param  string  明文
 *
 *  return  密文, base64 码
 */
+ (NSString *)rsaEncryptSourceString:(NSString *)string;

/**
 *  用来加密二进制数据
 *
 *  @param  string  明文
 *
 *  return  密文
 */
+ (NSData *)rsaEncryptSourceData:(NSData *)data;


#pragma mark - 私钥解密

/**
 *  用来解密字符串密文
 *
 *  @param  string  密文
 *
 *  return  明文
 */
+ (NSString *)rsaDecryptDecryptString:(NSString *)string;

/**
 *  用来解密二进制数据密文
 *
 *  @param  data    密文
 *
 *  return  明文
 */
+ (NSData *)rsaDecryptDecryptData:(NSData *)data;

@end
//
//  WYRSAEncryptTools.m
//  WYEncryptDemo
//
//  Created by Mac mini on 16/8/23.
//  Copyright © 2016年 yiyi. All rights reserved.
//

#import "WYRSAEncryptTools.h"
#import <Security/Security.h>

static SecKeyRef publicKeyRef = nil;
static SecKeyRef privateKeyRef = nil;

@implementation WYRSAEncryptTools

+ (void)loadPublicKeyWithFilePathString:(NSString *)string {
    
    NSData *derData = [[NSData alloc] initWithContentsOfFile:string];
    
    [WYRSAEncryptTools getPublicKeyRefrenceFromeData:derData];
}

+ (void)loadPrivateKeyWithFilePathString:(NSString *)string
                                password:(NSString*)password {
    
    NSData *p12Data = [NSData dataWithContentsOfFile:string];
    
    [WYRSAEncryptTools getPrivateKeyRefrenceFromData:p12Data password:password];
}

+ (NSString *)rsaEncryptSourceString:(NSString *)string {
    
    NSData *data = [WYRSAEncryptTools rsaEncryptSourceData:[string dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSString *encryptString = base64_encode_data(data);
    
    return encryptString;
}

+ (NSData *)rsaEncryptSourceData:(NSData *)data {
    
    if (!data){
        
        return nil;
    }

    if (!publicKeyRef) {
        
        return nil;
    }
    
    return [WYRSAEncryptTools encryptData:data withKeyRef:publicKeyRef];
}

+ (NSString *)rsaDecryptDecryptString:(NSString *)string {
    
    NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    data = [WYRSAEncryptTools rsaDecryptDecryptData:data];
    
    NSString *decryptString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return decryptString;
}

+ (NSData *)rsaDecryptDecryptData:(NSData *)data {
    
    if (!data){
        
        return nil;
    }

    if (!privateKeyRef) {
        
        return nil;
    }
    
    return [WYRSAEncryptTools decryptData:data withKeyRef:privateKeyRef];
}

+ (NSString *)rsaVerifyDecryptString:(NSString *)string {
    
    NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    data = [WYRSAEncryptTools rsaVerifyDecryptData:data];
    
    NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return ret;
}

+ (NSData *)rsaVerifyDecryptData:(NSData *)data {
    
    if (!data) {
        
        return nil;
    }

    if (!publicKeyRef) {
        
        return nil;
    }
    
    return [WYRSAEncryptTools decryptData:data withKeyRef:publicKeyRef];
}

//static NSString *base64_encode(NSString *str){
//    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
//    if(!data){
//        return nil;
//    }
//    return base64_encode_data(data);
//}

static NSString *base64_encode_data(NSData *data){
    data = [data base64EncodedDataWithOptions:0];
    NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return ret;
}

static NSData *base64_decode(NSString *str){
    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return data;
}

+ (NSData *)stripPublicKeyHeader:(NSData *)d_key{
    // Skip ASN.1 public key header
    if (d_key == nil) return(nil);
    
    unsigned long len = [d_key length];
    if (!len) return(nil);
    
    unsigned char *c_key = (unsigned char *)[d_key bytes];
    unsigned int  idx    = 0;
    
    if (c_key[idx++] != 0x30) return(nil);
    
    if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
    else idx++;
    
    // PKCS #1 rsaEncryption szOID_RSA_RSA
    static unsigned char seqiod[] =
    { 0x30,   0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
        0x01, 0x05, 0x00 };
    if (memcmp(&c_key[idx], seqiod, 15)) return(nil);
    
    idx += 15;
    
    if (c_key[idx++] != 0x03) return(nil);
    
    if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
    else idx++;
    
    if (c_key[idx++] != '\0') return(nil);
    
    // Now make a new NSData from this buffer
    return([NSData dataWithBytes:&c_key[idx] length:len - idx]);
}

//credit: http://hg.mozilla.org/services/fx-home/file/tip/Sources/NetworkAndStorage/CryptoUtils.m#l1036
+ (NSData *)stripPrivateKeyHeader:(NSData *)d_key{
    // Skip ASN.1 private key header
    if (d_key == nil) return(nil);
    
    unsigned long len = [d_key length];
    if (!len) return(nil);
    
    unsigned char *c_key = (unsigned char *)[d_key bytes];
    unsigned int  idx    = 22; //magic byte at offset 22
    
    if (0x04 != c_key[idx++]) return nil;
    
    //calculate length of the key
    unsigned int c_len = c_key[idx++];
    int det = c_len & 0x80;
    if (!det) {
        c_len = c_len & 0x7f;
    } else {
        int byteCount = c_len & 0x7f;
        if (byteCount + idx > len) {
            //rsa length field longer than buffer
            return nil;
        }
        unsigned int accum = 0;
        unsigned char *ptr = &c_key[idx];
        idx += byteCount;
        while (byteCount) {
            accum = (accum << 8) + *ptr;
            ptr++;
            byteCount--;
        }
        c_len = accum;
    }
    
    // Now make a new NSData from this buffer
    return [d_key subdataWithRange:NSMakeRange(idx, c_len)];
}

+ (SecKeyRef)addPublicKey:(NSString *)key{
    NSRange spos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
    NSRange epos = [key rangeOfString:@"-----END PUBLIC KEY-----"];
    if(spos.location != NSNotFound && epos.location != NSNotFound){
        NSUInteger s = spos.location + spos.length;
        NSUInteger e = epos.location;
        NSRange range = NSMakeRange(s, e-s);
        key = [key substringWithRange:range];
    }
    key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@" "  withString:@""];
    
    // This will be base64 encoded, decode it.
    NSData *data = base64_decode(key);
    data = [WYRSAEncryptTools stripPublicKeyHeader:data];
    if(!data){
        return nil;
    }
    
    //a tag to read/write keychain storage
    NSString *tag = @"WYRSAEncryptTools_PubKey";
    NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
    
    // Delete any old lingering key with the same tag
    NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
    [publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
    [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
    [publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
    SecItemDelete((__bridge CFDictionaryRef)publicKey);
    
    // Add persistent version of the key to system keychain
    [publicKey setObject:data forKey:(__bridge id)kSecValueData];
    [publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)
     kSecAttrKeyClass];
    [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
     kSecReturnPersistentRef];
    
    CFTypeRef persistKey = nil;
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
    if (persistKey != nil){
        CFRelease(persistKey);
    }
    if ((status != noErr) && (status != errSecDuplicateItem)) {
        return nil;
    }
    
    [publicKey removeObjectForKey:(__bridge id)kSecValueData];
    [publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
    [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
    [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
    
    // Now fetch the SecKeyRef version of the key
    SecKeyRef keyRef = nil;
    status = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);
    if(status != noErr){
        return nil;
    }
    return keyRef;
}

+ (SecKeyRef)addPrivateKey:(NSString *)key{
    NSRange spos = [key rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];
    NSRange epos = [key rangeOfString:@"-----END RSA PRIVATE KEY-----"];
    if(spos.location != NSNotFound && epos.location != NSNotFound){
        NSUInteger s = spos.location + spos.length;
        NSUInteger e = epos.location;
        NSRange range = NSMakeRange(s, e-s);
        key = [key substringWithRange:range];
    }
    key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@" "  withString:@""];
    
    // This will be base64 encoded, decode it.
    NSData *data = base64_decode(key);
    data = [WYRSAEncryptTools stripPrivateKeyHeader:data];
    if(!data){
        return nil;
    }
    
    //a tag to read/write keychain storage
    NSString *tag = @"WYRSAEncryptTools_PrivKey";
    NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
    
    // Delete any old lingering key with the same tag
    NSMutableDictionary *privateKey = [[NSMutableDictionary alloc] init];
    [privateKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
    [privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
    [privateKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
    SecItemDelete((__bridge CFDictionaryRef)privateKey);
    
    // Add persistent version of the key to system keychain
    [privateKey setObject:data forKey:(__bridge id)kSecValueData];
    [privateKey setObject:(__bridge id) kSecAttrKeyClassPrivate forKey:(__bridge id)
     kSecAttrKeyClass];
    [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
     kSecReturnPersistentRef];
    
    CFTypeRef persistKey = nil;
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)privateKey, &persistKey);
    if (persistKey != nil){
        CFRelease(persistKey);
    }
    if ((status != noErr) && (status != errSecDuplicateItem)) {
        return nil;
    }
    
    [privateKey removeObjectForKey:(__bridge id)kSecValueData];
    [privateKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
    [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
    [privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
    
    // Now fetch the SecKeyRef version of the key
    SecKeyRef keyRef = nil;
    status = SecItemCopyMatching((__bridge CFDictionaryRef)privateKey, (CFTypeRef *)&keyRef);
    if(status != noErr){
        return nil;
    }
    return keyRef;
}

/* START: Encryption & Decryption with RSA private key */

+ (NSData *)encryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
    const uint8_t *srcbuf = (const uint8_t *)[data bytes];
    size_t srclen = (size_t)data.length;
    
    size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
    void *outbuf = malloc(block_size);
    size_t src_block_size = block_size - 11;
    
    NSMutableData *ret = [[NSMutableData alloc] init];
    for(int idx=0; idx<srclen; idx+=src_block_size){
        //NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
        size_t data_len = srclen - idx;
        if(data_len > src_block_size){
            data_len = src_block_size;
        }
        
        size_t outlen = block_size;
        OSStatus status = noErr;
        status = SecKeyEncrypt(keyRef,
                               kSecPaddingPKCS1,
                               srcbuf + idx,
                               data_len,
                               outbuf,
                               &outlen
                               );
        if (status != 0) {
            NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
            ret = nil;
            break;
        }else{
            [ret appendBytes:outbuf length:outlen];
        }
    }
    
    free(outbuf);
    CFRelease(keyRef);
    return ret;
}

+ (NSString *)encryptString:(NSString *)str privateKey:(NSString *)privKey{
    NSData *data = [WYRSAEncryptTools encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] privateKey:privKey];
    NSString *ret = base64_encode_data(data);
    return ret;
}

+ (NSData *)encryptData:(NSData *)data privateKey:(NSString *)privKey{
    if(!data || !privKey){
        return nil;
    }
    SecKeyRef keyRef = [WYRSAEncryptTools addPrivateKey:privKey];
    if(!keyRef){
        return nil;
    }
    return [WYRSAEncryptTools encryptData:data withKeyRef:keyRef];
}

+ (NSData *)decryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
    const uint8_t *srcbuf = (const uint8_t *)[data bytes];
    size_t srclen = (size_t)data.length;
    
    size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
    UInt8 *outbuf = malloc(block_size);
    size_t src_block_size = block_size;
    
    NSMutableData *ret = [[NSMutableData alloc] init];
    for(int idx=0; idx<srclen; idx+=src_block_size){
        //NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
        size_t data_len = srclen - idx;
        if(data_len > src_block_size){
            data_len = src_block_size;
        }
        
        size_t outlen = block_size;
        OSStatus status = noErr;
        status = SecKeyDecrypt(keyRef,
                               kSecPaddingNone,
                               srcbuf + idx,
                               data_len,
                               outbuf,
                               &outlen
                               );
        if (status != 0) {
            NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
            ret = nil;
            break;
        }else{
            //the actual decrypted data is in the middle, locate it!
            int idxFirstZero = -1;
            int idxNextZero = (int)outlen;
            for ( int i = 0; i < outlen; i++ ) {
                if ( outbuf[i] == 0 ) {
                    if ( idxFirstZero < 0 ) {
                        idxFirstZero = I;
                    } else {
                        idxNextZero = I;
                        break;
                    }
                }
            }
            
            [ret appendBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];
        }
    }
    
    free(outbuf);
    CFRelease(keyRef);
    return ret;
}

+ (void)getPublicKeyRefrenceFromeData:(NSData*)derData {
    
    SecCertificateRef myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)derData);
    SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
    SecTrustRef myTrust;
    OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);
    SecTrustResultType trustResult;
    if (status == noErr) {
        status = SecTrustEvaluate(myTrust, &trustResult);
    }
    SecKeyRef securityKey = SecTrustCopyPublicKey(myTrust);
    CFRelease(myCertificate);
    CFRelease(myPolicy);
    CFRelease(myTrust);
    
    publicKeyRef = securityKey;
}

+ (void) getPrivateKeyRefrenceFromData: (NSData*)p12Data password:(NSString*)password{
    SecKeyRef securityKey = NULL;
    NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
    [options setObject: password forKey:(__bridge id)kSecImportExportPassphrase];
    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data, (__bridge CFDictionaryRef)options, &items);
    if (securityError == noErr && CFArrayGetCount(items) > 0) {
        CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
        SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
        securityError = SecIdentityCopyPrivateKey(identityApp, &securityKey);
        if (securityError != noErr) {
            securityKey = NULL;
        }
    }
    CFRelease(items);
    
    privateKeyRef = securityKey;
}

@end

参考

1、AES加密原理:十分钟读懂AES加密算法
2、RSA加密原理:RSA加密算法原理(一)RSA加密算法原理(二)

推荐阅读更多精彩内容