第四篇:非對稱加密及RSA加密演算法

weixin_33861800發表於2018-06-05

目錄

一、非對稱加密
 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可以滿足如下關係式
    1116725-58a5a8fd12b96c9c.png

    即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非對稱加密其實是互補的,我們經常把它倆結合起來使用。

相關文章