iOS RSA+AES 加惶室、解密

年前忙著趕項目,也沒時間更新玄货,現(xiàn)在告一段落皇钞,因為是貸款類項目,涉及到用戶的銀行卡松捉,身份證等信息鹅士,不可避免的使用到了加密相關(guān)技術(shù),這里就來聊聊RSA與AES加密吧

1. 有關(guān)對稱加密與非對稱加密的區(qū)別:

參考之前寫的文章(1.3-1.4-1.5)

http://www.reibang.com/p/4112bc3334af

RSA(非對稱加密惩坑,公鑰加密,私鑰解密也拜,涉及數(shù)字簽名等以舒,速度相對較慢)
AES(對稱加密,公慢哈、私鑰相同蔓钟,速度相對較快,如DES卵贱、RC5滥沫、RC6)

相對安全的HTTPS就同時使用了對稱加密及非對稱加密.

2. RSA 加、解密

加密流程:

一種是根據(jù)服務(wù)端提供給你的.cer或.der證書(不管是.cer還是.der其實只是一個公鑰的載體)進(jìn)行加密键俱,根據(jù).p12文件進(jìn)行解密;
另一種就是根據(jù)服務(wù)端直接提供給你的公兰绣、私鑰(字符串)進(jìn)行加、解密;
我們使用的是證書加编振、解密缀辩,所以只做此演示.
1. 服務(wù)端會給你生成一個cer或者der證書,直接拖進(jìn)項目即可(選中copy選項).
2. 根據(jù)證書路徑生成公鑰
3. 使用生成的公鑰對文件(文件的生成:是字典->json字符串->UTF8)進(jìn)行加密踪央,將加密后生成的NSData轉(zhuǎn)成base64碼(字符串)傳給服務(wù)端即可;


這里先來看看RSA加密相關(guān)類SXRSAEncryptor(直接拷貝可用)

其中 SXRSAEncryptor.h

#import <Foundation/Foundation.h>

@interface SXRSAEncryptor : NSObject

/**
 *  加密方法
 *
 *  @param str   需要加密的字符串
 *  @param path  '.der'格式的公鑰文件路徑
 */
+ (NSString *)encryptString:(NSString *)str publicKeyWithContentsOfFile:(NSString *)path;

/**
 *  解密方法
 *
 *  @param str       需要解密的字符串
 *  @param path      '.p12'格式的私鑰文件路徑
 *  @param password  私鑰文件密碼
 */
+ (NSString *)decryptString:(NSString *)str privateKeyWithContentsOfFile:(NSString *)path password:(NSString *)password;

/**
 *  加密方法
 *
 *  @param str    需要加密的字符串
 *  @param pubKey 公鑰字符串
 */
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;

/**
 *  解密方法
 *
 *  @param str     需要解密的字符串
 *  @param privKey 私鑰字符串
 */
+ (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey;



@end


SXRSAEncryptor.m

#import "SXRSAEncryptor.h"
#import <Security/Security.h>
@implementation SXRSAEncryptor

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;
}

#pragma mark - 使用'.der'公鑰文件加密

//加密
+ (NSString *)encryptString:(NSString *)str publicKeyWithContentsOfFile:(NSString *)path{
    if (!str || !path)  return nil;
    return [self encryptString:str publicKeyRef:[self getPublicKeyRefWithContentsOfFile:path]];
}

//獲取公鑰
+ (SecKeyRef)getPublicKeyRefWithContentsOfFile:(NSString *)filePath
{
    NSData *certData = [NSData dataWithContentsOfFile:filePath];
    if (!certData) {
    return nil;
    }
    SecCertificateRef cert = SecCertificateCreateWithData(NULL, (CFDataRef)certData);
    SecKeyRef key = NULL;
    SecTrustRef trust = NULL;
    SecPolicyRef policy = NULL;
    if (cert != NULL) {
        policy = SecPolicyCreateBasicX509();
        if (policy) {
            if (SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) == noErr) {
                SecTrustResultType result;
                if (SecTrustEvaluate(trust, &result) == noErr) {
                    key = SecTrustCopyPublicKey(trust);
                }
            }
        }
    }
    if (policy) CFRelease(policy);
    if (trust) CFRelease(trust);
    if (cert) CFRelease(cert);
    return key;
}

+ (NSString *)encryptString:(NSString *)str publicKeyRef:(SecKeyRef)publicKeyRef
{
    if(![str dataUsingEncoding:NSUTF8StringEncoding]){
        return nil;
    }
    if(!publicKeyRef){
        return nil;
    }
    NSData *data = [self encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] withKeyRef:publicKeyRef];
    NSString *ret = base64_encode_data(data);
    return ret;
}

#pragma mark - 使用'.12'私鑰文件解密

//解密
+ (NSString *)decryptString:(NSString *)str privateKeyWithContentsOfFile:(NSString *)path password:(NSString *)password
{
    if (!str || !path) return nil;
    if (!password) password = @"";
    return [self decryptString:str privateKeyRef:[self getPrivateKeyRefWithContentsOfFile:path password:password]];
}

//獲取私鑰
+ (SecKeyRef)getPrivateKeyRefWithContentsOfFile:(NSString *)filePath password:(NSString*)password
{
    NSData *p12Data = [NSData dataWithContentsOfFile:filePath];
    if (!p12Data) {
        return nil;
    }
    SecKeyRef privateKeyRef = 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, &privateKeyRef);
        if (securityError != noErr) {
            privateKeyRef = NULL;
        }
    }
    CFRelease(items);
    return privateKeyRef;
}

+ (NSString *)decryptString:(NSString *)str privateKeyRef:(SecKeyRef)privKeyRef
{
    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
    if (!privKeyRef) {
        return nil;
    }
    data = [self decryptData:data withKeyRef:privKeyRef];
    NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return ret;
}

#pragma mark - 使用公鑰字符串加密

/* START: Encryption with RSA public key */

//使用公鑰字符串加密
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey
{
    NSData *data = [self encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] publicKey:pubKey];
    NSString *ret = base64_encode_data(data);
    return ret;
}

+ (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey
{
    if(!data || !pubKey){
        return nil;
    }
    SecKeyRef keyRef = [self addPublicKey:pubKey];
    if(!keyRef){
        return nil;
    }
    return [self encryptData:data withKeyRef:keyRef];
}

+ (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 = [self stripPublicKeyHeader:data];
    if(!data){
        return nil;
    }

    //a tag to read/write keychain storage
    NSString *tag = @"RSAUtil_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;
}

+ (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]);
}

+ (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;
  }

 /* END: Encryption with RSA public key */

#pragma mark - 使用私鑰字符串解密

/* START: Decryption with RSA private key */

//使用私鑰字符串解密
+ (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey
{
    if (!str) return nil;
    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
    data = [self decryptData:data privateKey:privKey];
    NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return ret;
}

+ (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey
{
    if(!data || !privKey){
        return nil;
    }
    SecKeyRef keyRef = [self addPrivateKey:privKey];
    if(!keyRef){
        return nil;
    }
    return [self decryptData:data withKeyRef: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 = [self stripPrivateKeyHeader:data];
    if(!data){
        return nil;
    }

    //a tag to read/write keychain storage
    NSString *tag = @"RSAUtil_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;
}

+ (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)];
 }

+ (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;
}

@end


從上面的.h和.m文件可以看到臀玄,這里提供了上述兩種加解密的方法,請根據(jù)實際需求選擇.

3. AES 加畅蹂、解密

同樣的這里先來看看AES加密相關(guān)類SXAESEncryptor(直接拷貝可用)
SXAESEncryptor.h

#import <Foundation/Foundation.h>

@interface SXAESEncryptor : NSObject

// 普通AES加健无、解密
+(NSData *)AES256ParmEncryptWithKey:(NSString *)key Encrypttext:(NSData *)text;   //加密
+(NSData *)AES256ParmDecryptWithKey:(NSString *)key Decrypttext:(NSData *)text;   //解密
+(NSString *) aes256_encrypt:(NSString *)key Encrypttext:(NSString *)text;
+(NSString *) aes256_decrypt:(NSString *)key Decrypttext:(NSString *)text;

// 追加base64方式加密
+ (NSString *)encryptAES:(NSString *)content key:(NSString *)key;

// 追加base64方式解密
+ (NSDictionary *)decryptAES:(NSString *)content key:(NSString *)key;

@end


SXAESEncryptor.m

#import "SXAESEncryptor.h"
#import <CommonCrypto/CommonCryptor.h>
@implementation SXAESEncryptor

/** 初始向量*/
NSString *const kInitVector = @"16-Bytes--String";
/** 密鑰長度:AES-128*/
size_t const kKeySize = kCCKeySizeAES256;

************************* 普通AES 256 位加密,如果是 128液斜、192 直接修改 kKeySize即可 ********************

+(NSData *)AES256ParmEncryptWithKey:(NSString *)key Encrypttext:(NSData *)text  //加密
{
    char keyPtr[kKeySize +1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [text length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                      kCCOptionPKCS7Padding | kCCOptionECBMode,
                                      keyPtr, kCCBlockSizeAES128,
                                      NULL,
                                      [text bytes], dataLength,
                                      buffer, bufferSize,
                                      &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        // 對加密后的數(shù)據(jù)進(jìn)行 base64 編碼
        //        return [[NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}

+ (NSData *)AES256ParmDecryptWithKey:(NSString *)key Decrypttext:(NSData *)text  //解密
{
    char keyPtr[kKeySize +1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [text length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                      kCCOptionPKCS7Padding | kCCOptionECBMode,
                                      keyPtr, kCCBlockSizeAES128,
                                      NULL,
                                      [text bytes], dataLength,
                                      buffer, bufferSize,
                                      &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    free(buffer);
    return nil;
}

+(NSString *) aes256_encrypt:(NSString *)key Encrypttext:(NSString *)text
{
    const char *cstr = [text cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:text.length];
    //對數(shù)據(jù)進(jìn)行加密
    NSData *result = [SXAESEncryptor AES256ParmEncryptWithKey:key Encrypttext:data];

    //轉(zhuǎn)換為2進(jìn)制字符串
    if (result && result.length > 0) {
    
        Byte *datas = (Byte*)[result bytes];
        NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
        for(int i = 0; i < result.length; i++){
            [output appendFormat:@"%02x", datas[i]];
        }
        return output;
    }
    return nil;
}

+(NSString *) aes256_decrypt:(NSString *)key Decrypttext:(NSString *)text
{
    //轉(zhuǎn)換為2進(jìn)制Data
    NSMutableData *data = [NSMutableData dataWithCapacity:text.length / 2];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [text length] / 2; i++) {
        byte_chars[0] = [text characterAtIndex:i*2];
        byte_chars[1] = [text characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }

    //對數(shù)據(jù)進(jìn)行解密
    NSData* result = [SXAESEncryptor  AES256ParmDecryptWithKey:key Decrypttext:data];
    if (result && result.length > 0) {
        return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    }
    return nil;
}





************************** 追加base64加累贤、解密 *********************

// 項目中使用基于base64加密方法
+ (NSString *)encryptAES:(NSString *)content key:(NSString *)key 
{

    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = contentData.length;

    // 為結(jié)束符'\0' +1
    char keyPtr[kKeySize + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    // 密文長度 <= 明文長度 + BlockSize
    size_t encryptSize = dataLength + kCCBlockSizeAES128;
    void *encryptedBytes = malloc(encryptSize);
    size_t actualOutSize = 0;

    //    NSData *initVector = [kInitVector dataUsingEncoding:NSUTF8StringEncoding];

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                      kCCAlgorithmAES,
                                      kCCOptionPKCS7Padding | kCCOptionECBMode,  // 系統(tǒng)默認(rèn)使用 CBC叠穆,然后指明使用 PKCS7Padding
                                      keyPtr,
                                      kKeySize,
                                      NULL,
                                      contentData.bytes,
                                      dataLength,
                                      encryptedBytes,
                                      encryptSize,
                                      &actualOutSize);

    if (cryptStatus == kCCSuccess) {
        // 對加密后的數(shù)據(jù)進(jìn)行 base64 編碼
        return [[NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    free(encryptedBytes);
    return nil;
}


// 項目中使用基于base64解密方法
+ (NSDictionary *)decryptAES:(NSString *)content key:(NSString *)key
 {
    // 把 base64 String 轉(zhuǎn)換成 Data
    NSData *contentData = [[NSData alloc] initWithBase64EncodedString:content options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSUInteger dataLength = contentData.length;

    char keyPtr[kKeySize + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    size_t decryptSize = dataLength + kCCBlockSizeAES128;
    void *decryptedBytes = malloc(decryptSize);
    size_t actualOutSize = 0;

    // 這里不使用初始向量
    // NSData *initVector = [kInitVector dataUsingEncoding:NSUTF8StringEncoding];
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                      kCCAlgorithmAES,
                                      kCCOptionPKCS7Padding,
                                      keyPtr,
                                      kKeySize,
                                      NULL,
                                      contentData.bytes,
                                      dataLength,
                                      decryptedBytes,
                                      decryptSize,
                                      &actualOutSize);

    if (cryptStatus == kCCSuccess) {
        NSString *content = [[NSString alloc] initWithData:[NSData dataWithBytesNoCopy:decryptedBytes length:actualOutSize] encoding:NSUTF8StringEncoding];
        return [self dictionaryWithJsonString:content];
    }
    free(decryptedBytes);
    return nil;
}

// NSDictionary 轉(zhuǎn)換為 NSString
+ (NSString *)convertToJsonData:(NSDictionary *)dictionary
 {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的換行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

// NSString 轉(zhuǎn)換為 NSDictionary
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)content {
    if (content == nil) {
        return nil;
    }

    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingMutableContainers
                                                      error:&err];
    if(err){
        NSLog(@"json解析失敗:%@",err);
        return nil;
    }
    return dic;
}

@end

關(guān)于AES有幾個需要注意的點畦浓,首先你要搞清楚你們使用 的是128痹束、192、還是256位加密算法讶请,其次跟服務(wù)端商量好是普通AES加密還是追加base64的加密方式.

4. 項目中實際使用

我們項目中的邏輯是隨機(jī)生成一個16位字符串radomString祷嘶,對這個radomString進(jìn)行RSA加密生成參數(shù)encryptKey.
然后用這個radomString作為 AES加密的key(如果只是單純的AES,此key要與服務(wù)端商量好,定義一個死值)對要傳給服務(wù)端的參數(shù)(需將dic轉(zhuǎn)json)進(jìn)行AES加密生成字符串encryData.
最后將encryptKey和encryData傳給服務(wù)端夺溢。
服務(wù)端先使用RSA對encryptKey解密得到radomString论巍,再使用radomString作為key進(jìn)行AES對encryData解密得到我們最終傳的明文文件.

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.checkModel.name,@"applicantName",self.repayDetailModel.applyMoney,@"applyMoney",self.checkModel.bankNum,@"bankCardId",self.checkModel.originBank,@"bankName",self.unitModel.production,@"bizType",self.unitModel.uintName,@"bizWorkfor",self.checkModel.mobile,@"callNumber",self.checkModel.certNo,@"cardId",self.contactModel.phone,@"linkman1Cell",self.contactModel.name,@"linkman1Name",self.contactModel.useTo,@"loanReason",self.unitModel.email,@"mail",self.unitModel.detailAddress,@"bizAddr",self.repayDetailModel.refundPeriods,@"refundPeriods",userModel.token,@"token",userModel.mobile,@"mobile",@"00101",@"productionCode",self.caseNumModel.requestId,@"requestId",self.unitModel.unitAddress,@"addresCode",self.checkModel.originBank,@"depositBank", nil];
    
// 字典轉(zhuǎn)json
NSString *jsonString = [self convertToJsonData:dic];
// 隨機(jī)16位字符串
NSString *radomString = [self getRandomString];
// RSA加密
NSString *encryptKey = [SXRSAEncryptor encryptString:radomString publicKeyWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shuixiangjinrong" ofType:@"cer"]];
// AES加密
NSString *encryData = [SXAESEncryptor encryptAES:jsonString key:radomString];

SXEncryptorParam *param = [SXEncryptorParam encryptorParamWithData:encryData encryptKey:encryptKey serviceId:@"JUNCAI0029"];

[SXComplentTool complentToolWithParam:param success:^(SXComplentResult *result) {
    if ([result.code isEqualToString:SXRequestSuccess]) {
       // 成功
} failure:^(NSError *error) {
       // 失敗
}];


其中
// 返回16位大小寫字母和數(shù)字
-(NSString *)getRandomString{
    //定義一個包含數(shù)字,大小寫字母的字符串
    NSString * strAll = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //定義一個結(jié)果
    NSString * result = [[NSMutableString alloc]initWithCapacity:16];
    for (int i = 0; i < 16; i++)
    {
        //獲取隨機(jī)數(shù)
        NSInteger index = arc4random() % (strAll.length-1);
        char tempStr = [strAll characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    return result;
    }

#pragma mark - 字典轉(zhuǎn)json
-(NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString;

    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    //去掉字符串中的空格

    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRange range2 = {0,mutStr.length};

    //去掉字符串中的換行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;
}

如果有什么疑問风响,歡迎敲門騷擾嘉汰!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市状勤,隨后出現(xiàn)的幾起案子鞋怀,更是在濱河造成了極大的恐慌,老刑警劉巖持搜,帶你破解...
    沈念sama閱讀 217,907評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件密似,死亡現(xiàn)場離奇詭異,居然都是意外死亡葫盼,警方通過查閱死者的電腦和手機(jī)残腌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來贫导,“玉大人抛猫,你說我怎么就攤上這事『⒌疲” “怎么了闺金?”我有些...
    開封第一講書人閱讀 164,298評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長钱反。 經(jīng)常有香客問我掖看,道長,這世上最難降的妖魔是什么面哥? 我笑而不...
    開封第一講書人閱讀 58,586評論 1 293
  • 正文 為了忘掉前任哎壳,我火速辦了婚禮,結(jié)果婚禮上尚卫,老公的妹妹穿的比我還像新娘归榕。我一直安慰自己,他們只是感情好吱涉,可當(dāng)我...
    茶點故事閱讀 67,633評論 6 392
  • 文/花漫 我一把揭開白布刹泄。 她就那樣靜靜地躺著外里,像睡著了一般。 火紅的嫁衣襯著肌膚如雪特石。 梳的紋絲不亂的頭發(fā)上盅蝗,一...
    開封第一講書人閱讀 51,488評論 1 302
  • 那天,我揣著相機(jī)與錄音姆蘸,去河邊找鬼墩莫。 笑死,一個胖子當(dāng)著我的面吹牛逞敷,可吹牛的內(nèi)容都是我干的狂秦。 我是一名探鬼主播,決...
    沈念sama閱讀 40,275評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼推捐,長吁一口氣:“原來是場噩夢啊……” “哼裂问!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起牛柒,我...
    開封第一講書人閱讀 39,176評論 0 276
  • 序言:老撾萬榮一對情侶失蹤堪簿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后皮壁,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體戴甩,經(jīng)...
    沈念sama閱讀 45,619評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,819評論 3 336
  • 正文 我和宋清朗相戀三年闪彼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片协饲。...
    茶點故事閱讀 39,932評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡畏腕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出茉稠,到底是詐尸還是另有隱情描馅,我是刑警寧澤,帶...
    沈念sama閱讀 35,655評論 5 346
  • 正文 年R本政府宣布而线,位于F島的核電站铭污,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏膀篮。R本人自食惡果不足惜嘹狞,卻給世界環(huán)境...
    茶點故事閱讀 41,265評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望誓竿。 院中可真熱鬧磅网,春花似錦、人聲如沸筷屡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至燎潮,卻和暖如春喻鳄,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背确封。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評論 1 269
  • 我被黑心中介騙來泰國打工除呵, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人隅肥。 一個月前我還...
    沈念sama閱讀 48,095評論 3 370
  • 正文 我出身青樓竿奏,卻偏偏與公主長得像,于是被迫代替她去往敵國和親腥放。 傳聞我的和親對象是個殘疾皇子泛啸,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,884評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 參考資料: ①數(shù)字簽名是什么候址? ②基于HTTP在互聯(lián)網(wǎng)傳輸敏感數(shù)據(jù)的消息摘要、簽名與加密方案 ③RSA及AES加解...
    吵架魚閱讀 5,117評論 1 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理种柑,服務(wù)發(fā)現(xiàn)岗仑,斷路器,智...
    卡卡羅2017閱讀 134,656評論 18 139
  • 本文主要介紹移動端的加解密算法的分類聚请、其優(yōu)缺點特性及應(yīng)用荠雕,幫助讀者由淺入深地了解和選擇加解密算法。文中會包含算法的...
    蘋果粉閱讀 11,505評論 5 29
  • 1驶赏、通過第三方框架管理所有的鍵盤事件 2炸卑、通過監(jiān)聽鍵盤動作來獲取鍵盤 通過NSNotificationCenter...
    AlexLi_閱讀 655評論 0 0
  • 官方文檔: http://kotlinlang.org/docs/reference/exceptions.htm...
    lioilwin閱讀 3,145評論 0 3