第四篇:非对称加密及RSA加密算法

目录

一、非对称加密
 1、什么是非对称加密?
 2、对称加密的工作过程
 3、非对称加密的优点
 4、非对称加密的不足
二、RSA加密算法
 1、什么是RSA加密算法
 2、RSA的加密原理
 3、RSA加密的代码
 4、实际开发中使用RSA加密需要注意的地方


一、非对称加密


1、什么是非对称加密?

非对称加密是指,需要用一对儿密钥,即公钥和私钥,来完成加解密的方式。如果用公钥加密,则只能用对应的私钥才能解密;而如果用私钥加密,则只能用对应的公钥才能解密。

非对称加密主要是为了解决对称加密的两大不足密钥传输问题密钥管理问题提出的。

2、对称加密的工作过程

假设A要给B发数据。

第一步:首先B生成一对儿密钥,我们称之为B私钥和B公钥,B私钥保存在B自己手里,B公钥发布给A。

第二步:A用B公钥把明文加密生成密文,发给B,B用B私钥把密文解密成明文阅读。

但这并不是说只有公钥可以用来加密,私钥也是可以用来加密的。

3、非对称加密的优点
  • 解决了密钥传输问题:第二篇中我们说到对称加密面临的一个关键问题就是密钥的传输,因为加解密双方用的是同一个密钥,所以一旦一方的密钥泄漏了,那么整个信息传输的安全性就没有保证了。而非对称加密,使用的是两个、一对儿密钥,只要双方事先发布好,密钥就不必参与传输,因此非对称加密相对对称加密更加安全。

  • 解决了密钥管理问题:第二篇中我们说到对称加密要给每一对用户单独维护一个密钥,这样随着密钥数量的增多,管理起来麻烦。而非对称加密是一对儿密钥,自己保存私钥,公钥可以发布给很多人,这样就达到了一对多的效果,不必维护很多密钥。

4、非对称加密的不足

加密计算量大、速度慢,适合对少量数据进行加密的场景。(这个也请记住,刚好和对称加密是反着来的)


二、RSA加密算法


1、什么是RSA加密算法

RSA加密算法是非对称加密算法的一种,为了保证加密的安全性,RSA密钥的长度一般都是1024位或者2048位,这就使得RSA加密的计算量大、加密速度慢。

2、RSA的加密原理

RSA的加密原理基于四个数学知识,公钥和私钥的生成就是基于这四个数学知识,经过这四个数学知识得到的公钥和私钥非常的大,而RSA的安全性就是依赖于大数难以轻易的分解,数字越大越难分解。实际上目前被破解的RSA密钥的最长长度为768位,1024位密钥或者2048位密钥现在可以认为是无法被破解的:

  • 互质关系:如果两个正整数除1以外,没有其它的公约数,那么我们就称这两个数为互质关系。
  • 欧拉函数:假设有一个正整数n,那么欧拉函数就是用来求小于n的正整数中与n互质的数的个数的。
  • 欧拉定理:欧拉函数的应用在于欧拉定理,欧拉定理是指假设有两个正整数a和n,并且a和n互质,那么a和n可以满足如下关系式

    即a的φ(n)次幂减1,可以被n整除。欧拉定理是RSA加密算法的核心。
  • 模反元素:模反元素是说,假设有两个正整数a和n,并且a和n互质,那么就一定能找到一个整数b,使得ab-1,可以被n整除,那么b就叫作a的模反元素。

详细的RSA加密原理,可参看:

3、RSA加密的代码

参考文章:iOS和Java RSA加密

(1)首先生成必要的公钥、私钥、证书

第一步:打开终端,cd,拖一个文件夹进去,指定将来生成文件的存储路径;

第二步:openssl

第三步:req -new -key private_key.pem -out rsaCertReq.csr

第四步:x509 -req -days 3650 -in rsaCertReq.csr -signkey private_key.pem -out rsaCert.crt

第五步:x509 -outform der -in rsaCert.crt -out public_key.der

第六步:pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt(这一步,需要记住你输入的密码,咱们iOS代码里会用到

第七步:rsa -in private_key.pem -out rsa_public_key.pem -pubout

第八步:pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt

第九步:这时到事先指定的文件夹下就可以看到七个文件,其中public_key.derprivate_key.p12这对公私钥是给我们iOS用的,拖到工程里就可以了;rsa_public_key.pempkcs8_private_key.pem是给后台用的,发给他们;它们的根源都来自一个私钥private_key.pem,所以iOS端加密的数据后台可以解密,反过来同理。

(2)RSA加密的代码
//
//  RSAEncrypt.h
//  EncryptDemo
//
//  Created by 意一yiyi on 2018/6/5.
//  Copyright © 2018年 意一yiyi. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface RSAEncrypt : NSObject

#pragma mark - 加载公私钥

/**
 *  加载公钥
 *
 *  @param  derFilePath 公钥文件路径
 */
+ (void)loadPublicKeyFromFilePath:(NSString *)derFilePath;

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


#pragma mark - 公钥解密

/**
 *  公钥加密字符串,Base64编码输出
 *
 *  @param  plaintext   明文
 *
 *  @return RSA加密后的密文
 */
+ (NSString *)rsaCiphertextFromPlaintext:(NSString *)plaintext;

/**
 *  公钥加密data,data输出
 *
 *  @param  plaindata   明文
 *
 *  @return RSA加密后的密文
 */
+ (NSData *)rsaCipherdataFromPlaindata:(NSData *)plaindata;


#pragma mark - 私钥解密

/**
 *  私钥解密字符串,Base64编码输入
 *
 *  @param  ciphertext  密文
 *
 *  @return RSA解密后的明文
 */
+ (NSString *)rsaPlaintextFromCiphertext:(NSString *)ciphertext;

/**
 *  私钥解密data,data输入
 *
 *  @param  cipherdata  密文
 *
 *  @return RSA解密后的明文
 */
+ (NSData *)rsaPlaindataFromCipherdata:(NSData *)cipherdata;

@end
//
//  RSAEncrypt.m
//  EncryptDemo
//
//  Created by 意一yiyi on 2018/6/5.
//  Copyright © 2018年 意一yiyi. All rights reserved.
//

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

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

@implementation RSAEncrypt

+ (void)loadPublicKeyFromFilePath:(NSString *)derFilePath {
    
    NSData *derData = [[NSData alloc] initWithContentsOfFile:derFilePath];
    [RSAEncrypt getPublicKeyRefrenceFromeData:derData];
}

+ (void)loadPrivateKeyFromFilePath:(NSString *)p12FilePath
                          password:(NSString *)password {
    
    NSData *p12Data = [NSData dataWithContentsOfFile:p12FilePath];
    [RSAEncrypt getPrivateKeyRefrenceFromData:p12Data password:password];
}


#pragma mark - 公钥解密

+ (NSString *)rsaCiphertextFromPlaintext:(NSString *)plaintext {
    
    NSData *data = [RSAEncrypt rsaCipherdataFromPlaindata:[plaintext dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *encryptString = base64_encode_data(data);
    
    return encryptString;
}

+ (NSData *)rsaCipherdataFromPlaindata:(NSData *)plaindata {
    
    if (!plaindata){
        
        return nil;
    }
    
    if (!publicKeyRef) {
        
        return nil;
    }
    
    return [RSAEncrypt encryptData:plaindata withKeyRef:publicKeyRef];
}


#pragma mark - 私钥解密

+ (NSString *)rsaPlaintextFromCiphertext:(NSString *)ciphertext {
    
    NSData *data = [[NSData alloc] initWithBase64EncodedString:ciphertext options:NSDataBase64DecodingIgnoreUnknownCharacters];
    data = [RSAEncrypt rsaPlaindataFromCipherdata:data];

    NSString *decryptString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return decryptString;
}

+ (NSData *)rsaPlaindataFromCipherdata:(NSData *)cipherdata {
    
    if (!cipherdata){
        
        return nil;
    }
    
    if (!privateKeyRef) {
        
        return nil;
    }
    
    return [RSAEncrypt decryptData:cipherdata withKeyRef:privateKeyRef];
}


// 来源于网络,忘了来源了
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]);
}

+ (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 = [RSAEncrypt 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 = [RSAEncrypt 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 = [RSAEncrypt 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 = [RSAEncrypt addPrivateKey:privKey];
    if(!keyRef){
        return nil;
    }
    return [RSAEncrypt 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
4、实际开发中使用RSA加密需要注意的地方

针对非对称加密加密计算量大、速度慢,只适合对少量数据进行加密这个不足,实际开发中,我们如果遇到要对大量数据加密,那就一定要采用RSA+AES加密相结合的方式,用AES加密数据,而用RSA加密AES的密钥。当然,需要加密的数据如果数据量不大的话,可以直接用RSA加密。

到这里,我们也可以看出AES对称加密和RSA非对称加密其实是互补的,我们经常把它俩结合起来使用。

推荐阅读更多精彩内容