iOS RSA非对称加密证书的生成(简洁明了)

前言
iOS中使用RSA加密解密,需要用到.der和.p12后缀格式的文件,其中.der格式的文件存放的是公钥(Public key)用于加密,.p12格式的文件存放的是私钥(Private key)用于解密. 首先需要先生成这些文件,然后再将文件导入工程使用。
数字证书则是由证书认证机构(CA)对证书申请者真实身份验证之后,用CA的根证书对申请人的一些基本信息以及申请人的公钥进行签名(相当于加盖发证书机 构的公章)后形成的一个数字文件。CA完成签发证书后,会将证书发布在CA的证书库(目录服务器)中,任何人都可以查询和下载,因此数字证书和公钥一样是公开的。实际上,数字证书就是经过CA认证过的公钥。

原则:
1、一个公钥对应一个私钥。
2、密钥对中,让大家都知道的是公钥,不告诉大家,只有自己知道的,是私钥。
3、如果用其中一个密钥加密数据,则只有对应的那个密钥才可以解密。
4、如果用其中一个密钥可以进行解密数据,则该数据必然是对应的那个密钥进行的加密。
5、非对称密钥密码的主要应用就是公钥加密和公钥认证,而公钥加密的过程和公钥认证的过程是不一样的。

正题
一、使用openssl生成所需秘钥文件 (Mac 安装openssl)
生成环境是在mac系统下,使用openssl进行生成,首先打开终端,按下面这些步骤依次来做:
1.生成模长为1024bit的私钥文件private_key.pem

$ openssl genrsa -out private_key.pem 1024

如图操作结果:
这里写图片描述

2.生成证书请求文件rsaCertReq.csr

$ openssl req -new -key private_key.pem -out rsaCerReq.csr
//注意:这一步会提示输入国家、省份、mail等信息,可以根据实际情况填写,或者全部不用填写,直接全部敲回车.(PS:注意还得设置密码即:私钥文件设置密码,在解密时,private_key.p12文件需要和这里设置的密码配合使用,因此需要牢记此密码)

如图操作结果:
这里写图片描述

3.生成证书rsaCert.crt,并设置有效时间为10年

$ openssl x509 -req -days 3650 -in rsaCerReq.csr -signkey private_key.pem -out rsaCert.crt

如图操作结果:
这里写图片描述

4.生成供iOS使用的公钥文件public_key.der

$ openssl x509 -outform der -in rsaCert.crt -out public_key.der

如图操作结果:
这里写图片描述

5.生成供iOS使用的私钥文件private_key.p12

$ openssl pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt
//PS:这里需要输入上边私钥文件设置密码,和再次确认密码;然后敲回车,完毕!

如图操作结果:
这里写图片描述

6.生成供Java使用的公钥rsa_public_key.pem

$ openssl rsa -in private_key.pem -out rsa_public_key.pem -pubout
writing RSA key

如图操作结果:
这里写图片描述

7.生成供Java使用的私钥pkcs8_private_key.pem

$ openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt

如图显示结果
这里写图片描述

8.生成JAVA支持的PKCS8二进制类型的私钥:(ps:用于java解密)

$ openssl pkcs8 -topk8 -inform PEM -in private_key.pem -outform DER -nocrypt -out pkcs8_private_key.der

如图显示:
这里写图片描述

全部执行成功后,会生成如下文件,其中public_key.der和private_key.p12就是iOS需要用到的文件(PS:在所在的目录下生成了6个文件,其中pem的文件都是文本类型的,都可以使用文本编辑器或者cat命令查看,der的都是二进制的文件了,不能看)
如下图:生成的文件
这里写图片描述
这里写图片描述

最后:将文件导入工程使用
以下是iOS的加密和解密使用 (java解密链接:java RSA非对称加密-解密(简洁明了)
1.并导入Security.framework框架,新建工程并添加框架
2.导入秘钥文件
代码示例:

 NSString *publicPath = [[NSBundle mainBundle] pathForResource:@"public_key.der" ofType:nil];
    [[LNRASTool rasInstance] loadPublicKeyWithPath:publicPath];
    NSString *encryptString = [[LNRASTool rasInstance] rsaEncryptText:@"我是铭文,请把我非对称加密"];
    NSLog(@"加密:我是铭文,请把我非对称加密:%@", encryptString);

    NSString *privatePath = [[NSBundle mainBundle] pathForResource:@"private_key.p12" ofType:nil];
    [[LNRASTool rasInstance] loadPrivateKeyWithPath:privatePath password:@"lining123456"];
    NSString *string = [[LNRASTool rasInstance] rsaDecryptText:encryptString];
    NSLog(@"解密结果为:%@", string);

运行结果:
这里写图片描述

公共类:

//
//  LNRASTool.h
//  MVVMDemo
//
//  Created by baiwei on 2018/2/5.
//  Copyright © 2018年 Li Ning. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface LNRASTool : NSObject

+(instancetype)rasInstance;

#pragma mark - 加密
/**
 通过路径生成 SecKeyRef _publicKey(即公钥);

 @param derFilePath derFilePath文件path
 */
- (void)loadPublicKeyWithPath:(NSString *)derFilePath;


/**
 生成密文:根据传入明文生成密文

 @param text 传入需要加密的明文
 @return 密文
 */
- (NSString *)rsaEncryptText:(NSString *)text;

- (void)loadPublicKeyWithData:(NSData *)derData;
- (NSData *)rsaEncryptData:(NSData *)data;


#pragma mark - 解密
/**
 通过路径生成 SecKeyRef _privateKey(即秘钥);

 @param p12FilePath p12File的路径
 @param p12Password p12File的密码
 */
- (void)loadPrivateKeyWithPath:(NSString *)p12FilePath password:(NSString *)p12Password;

/**
 解密:根据传入的密文解密成铭文

 @param text 传入需要解密的密文
 @return 铭文
 */
- (NSString *)rsaDecryptText:(NSString *)text;

- (void)loadPrivateKeyWithData:(NSData *)p12Data password:(NSString *)p12Password;
- (NSData *)rsaDecryptData:(NSData *)data;

@end
//
//  LNRASTool.m
//  MVVMDemo
//
//  Created by baiwei on 2018/2/5.
//  Copyright © 2018年 Li Ning. All rights reserved.
//

#import "LNRASTool.h"

@interface LNRASTool () {
    SecKeyRef _publicKey;
    SecKeyRef _privateKey;
}
@end

@implementation LNRASTool

+(instancetype)rasInstance
{
    static LNRASTool *ras = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ras = [[LNRASTool alloc] init];
    });
    return ras;
}

- (void)dealloc {
    if (nil != _publicKey) {
        CFRelease(_publicKey);
    }

    if (nil != _privateKey) {
        CFRelease(_privateKey);
    }
}


#pragma mark - 加密
- (void)loadPublicKeyWithPath:(NSString *)derFilePath {
    NSData *derData = [[NSData alloc] initWithContentsOfFile:derFilePath];
    if (derData.length > 0) {
        [self loadPublicKeyWithData:derData];
    } else {
        NSLog(@"load public key fail with path: %@", derFilePath);
    }
}

- (void)loadPublicKeyWithData:(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);
    _publicKey = securityKey;
}

- (NSString *)rsaEncryptText:(NSString *)text {
    NSData *encryptedData = [self rsaEncryptData:[text dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *base64EncryptedString = [encryptedData base64EncodedStringWithOptions:0];
    return base64EncryptedString;
}

- (NSData *)rsaEncryptData:(NSData *)data {
    SecKeyRef key = _publicKey;

    size_t cipherBufferSize = SecKeyGetBlockSize(key);
    uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
    size_t blockSize = cipherBufferSize - 11;
    size_t blockCount = (size_t)ceil([data length] / (double)blockSize);

    NSMutableData *encryptedData = [[NSMutableData alloc] init] ;
    for (int i = 0; i < blockCount; i++) {
        size_t bufferSize = MIN(blockSize,[data length] - i * blockSize);
        NSData *buffer = [data subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
        OSStatus status = SecKeyEncrypt(key,
                                        kSecPaddingPKCS1,
                                        (const uint8_t *)[buffer bytes],
                                        [buffer length],
                                        cipherBuffer,
                                        &cipherBufferSize);
        if (status == noErr) {
            NSData *encryptedBytes = [[NSData alloc] initWithBytes:(const void *)cipherBuffer
                                                            length:cipherBufferSize];
            [encryptedData appendData:encryptedBytes];
        } else {
            if (cipherBuffer) {
                free(cipherBuffer);
            }

            return nil;
        }
    }

    if (cipherBuffer){
        free(cipherBuffer);
    }

    return encryptedData;
}

#pragma mark - 解密
- (void)loadPrivateKeyWithPath:(NSString *)p12FilePath password:(NSString *)p12Password {
    NSData *data = [NSData dataWithContentsOfFile:p12FilePath];

    if (data.length > 0) {
        [self loadPrivateKeyWithData:data password:p12Password];
    } else {
        NSLog(@"load private key fail with path: %@", p12FilePath);
    }
}

- (void)loadPrivateKeyWithData:(NSData *)p12Data password:(NSString *)p12Password {
    SecKeyRef privateKeyRef = NULL;
    NSMutableDictionary * options = [[NSMutableDictionary alloc] init];

    [options setObject:p12Password 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);
    _privateKey = privateKeyRef;


}

- (NSString *)rsaDecryptText:(NSString *)text {
    NSData *data = [[NSData alloc] initWithBase64EncodedString:text options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSData *decryptData = [self rsaDecryptData:data];
    NSString *result = [[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding];
    return result;
}

- (NSData *)rsaDecryptData:(NSData *)data {
    SecKeyRef key = _privateKey;

    size_t cipherLen = [data length];
    void *cipher = malloc(cipherLen);

    [data getBytes:cipher length:cipherLen];
    size_t plainLen = SecKeyGetBlockSize(key) - 12;

    void *plain = malloc(plainLen);
    OSStatus status = SecKeyDecrypt(key, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);

    if (status != noErr) {
        return nil;
    }

    NSData *decryptedData = [[NSData alloc] initWithBytes:(const void *)plain length:plainLen];

    return decryptedData;
}


@end

下一篇文章java解密:java RSA非对称加密-解密(简洁明了)

猜你喜欢

转载自blog.csdn.net/lining1041204250/article/details/79259920
今日推荐