ios中生成RSA密钥字符串

作者: TimmyR | 来源:发表于2016-10-25 13:28 被阅读2046次

    嘟哝嘟哝:最近接到一个任务:在客户端动态生成RSA密钥对,然后向服务器发送这个密钥对中的公钥字符串,由服务器进行公钥加密,返回加密后的信息,再由客户端使用私钥进行解密。我在网上查阅了大量的资料,但是大多是利用公钥私钥文件,或者直接接收RSA公私钥字符串进行加密解密,没有生成并转换成字符串,这里我们就介绍一下我是如何实现这个功能的,以备后用。

           我今天要介绍的RSA加密属于非对称加密。对于安全性来说显然非对称加密更优于对称加密。在使用中,甲方需要同时生成公开密钥(公钥)和私有密钥(私钥),把其中的公钥发送给乙方,乙方利用传过来的私钥,对发送文本进行加密回传给甲方,甲方接收到加密后的文本后用此前生成的私钥进行解密,从而得到加密前的文本。但加密和解密花费时间长、速度慢,它不适合于对文件加密而只适用于对少量数据进行加密。

    首先介绍利用终端生成公钥私钥

    1、生成私钥

    openssl genrsa -out rsa_private_key.pem1024

    2、将原始私钥转换为pkcs8格式

    openssl pkcs8 -topk8 -inform PEM -inrsa_private_key.pem -outform PEM -nocrypt

    3、根据私钥生成公钥

    openssl rsa -in rsa_private_key.pem -pubout-out ras_public_key.pem

    RSAPEM文件格式

    1. PEM私钥格式文件

    -----BEGIN RSA PRIVATE KEY-----

    -----END RSA PRIVATE KEY-----

    2. PEM公钥格式文件

    -----BEGIN PUBLIC KEY-----

    -----END PUBLIC KEY-----

    3. PEM RSAPublicKey公钥格式文件

    -----BEGIN RSA PUBLIC KEY-----

    -----END RSA PUBLIC KEY-----

    回归正题:我们开始实现生成密钥字符串。在这里我们使用的是openssl框架来生成密钥对。

    头文件中引入

    #import <openssl/rsa.h>

    #import <openssl/pem.h>

    1,生成密钥对

    /*产生RSA密钥*/

    RSA*rsa =NULL;

    rsa =RSA_new();

    //产生一个模为num位的密钥对,e为公开的加密指数,一般为65537(0x10001)

    rsa =RSA_generate_key(1024,0x10001,NULL,NULL);

           这里需要说明一下,加密长度是1024位。加密长度是指理论上最大允许”被加密的信息“长度的限制,也就是明文的长度限制。随着这个参数的增大(比方说2048),允许的明文长度也会增加,但同时也会造成计算复杂度的极速增长。一般推荐的长度就是1024位(128字节)。

           这种算法非常可靠,密钥越长,它就越难破解。根据已经披露的文献,目前被破解的最长RSA密钥是768个二进制位。也就是说,长度超过768位的密钥,还无法破解(至少没人公开宣布)。因此可以认为,1024位的RSA密钥基本安全,2048位的密钥极其安全。

           由于我并没有在框架中找到方法转换出密钥字符串,所以这里用了个比较笨拙的方法,将公钥私钥保存为txt文件,然后将这个txt文件读出,读出后就是需要的字符串了。

    上方加粗函数虽然已经过时,但是目前还可以用,下方加粗部分是替代方法

    BIGNUM*bne =BN_new();

    unsignedinte =RSA_3;

    intresult =BN_set_word(bne, e);

    result =RSA_generate_key_ex(rsa,1024, bne,NULL);

    rsa就是得到的密钥对

    //路径

    NSString*documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];

    /*提取公钥字符串*/

    //最终存储的地方,所以需要创建一个路径去存储字符串

    NSString*pubPath = [documentsPathstringByAppendingPathComponent:@"PubFile.txt"];

    FILE* pubWrite =NULL;

    pubWrite =fopen([pubPathUTF8String],"wb");

    if(pubWrite ==NULL)

    NSLog(@"Read Filed.");

    else

    {

    PEM_write_RSA_PUBKEY(pubWrite,rsa);

    fclose(pubWrite);

    }

           拿出字符串之后对字符串进行处理,这样就得到了我们需要的字符串了。

    NSString*str=[NSStringstringWithContentsOfFile:pubPathencoding:NSUTF8StringEncodingerror:nil];

    str = [strstringByReplacingOccurrencesOfString:@"-----BEGIN

    PUBLIC KEY-----"withString:@""];

    str = [strstringByReplacingOccurrencesOfString:@"-----END

    PUBLIC KEY-----"withString:@""];

    str = [strstringByReplacingOccurrencesOfString:@"\n"withString:@""];

    /*提取私钥字符串*/

    NSString*priPath =

    [documentsPathstringByAppendingPathComponent:@"PriFile.txt"];

    FILE*priWtire =NULL;

    priWtire =fopen([priPathUTF8String],"wb");

    EVP_PKEY*pkey =NULL;

    if(priWtire ==NULL) {

    NSLog(@"Read

    Filed.");

    }else{

    //函数使用PKCS#8标准保存EVP_PKEY里面的私钥到文件或者BIO中,并采用PKCS#5

    //v2.0的标准加密私钥。enc参数定义了使用的加密算法。跟其他PEM的IO函数不一样的是,本函数的加密是基于PKCS#8层次上的,而不是基于PEM信息字段的,所以这两个函数也是单独实现的函数,而不是宏定义函数。如果enc参数为NULL,那么就不会执行加密操作,只是使用PKCS#8私钥 信息结构。成功执行返回大于0的数,否则返回0。

    pkey =EVP_PKEY_new();

    EVP_PKEY_assign_RSA(pkey, rsa);

    PEM_write_PKCS8PrivateKey(priWtire, pkey,NULL,NULL,0,0,NULL);

    fclose(priWtire);

    }

    NSString*priStr=[NSStringstringWithContentsOfFile:priPathencoding:NSUTF8StringEncodingerror:nil];

    priStr = [priStrstringByReplacingOccurrencesOfString:@"-----BEGIN

    PRIVATE KEY-----"withString:@""];

    priStr = [priStrstringByReplacingOccurrencesOfString:@"-----END

    PRIVATE KEY-----"withString:@""];

    priStr = [priStrstringByReplacingOccurrencesOfString:@"\n"withString:@""];

    得到私钥字符串。

    以下是问题记录:

    1.利用PEM_write_RSA_PUBKEY函数保存密钥后,无法获得密钥,原因是我在设置文件的时候,参考网上的资料,写成了文件名称,获取的时候也是利用框架中的函数获取到的RSA,还是没有转换成字符串。所以我将设置文件的地方,写入了文件路径,然后我再用自己的方式读取这个txt文件,这样就得到了我想要的字符串了。

    2.保存密钥的时候,开始的时候得到的公钥私钥都是不能正确加密解密的,原因是我在保存密钥文件的时候,选错了文件的格式,这里有两个函数很容易让人混淆:

    PEM_write_RSAPublicKey(<#FILE *fp#>,<#const RSA *x#>)

    由这个函数得到的文件是PRM RSAPublicKey公钥格式文件,而我们需要的文件是PEM公钥格式文件,所以要看好函数指定的文件格式。利用PEM_write_RSA_PUBKEY函数。

    PEM_write_RSAPrivateKey(<#FILE *fp#>, <#RSA *x#>, <#constEVP_CIPHER *enc#>, <#unsigned char *kstr#>, <#int klen#>,<#pem_password_cb *cb#>, <#void *u#>)

    通过这个函数我们虽然可以得到私钥文件,但是却是PKCS1格式的,但是我需要的是PKCS8格式的。所以需要改用这个函数PEM_write_PKCS8PrivateKey。

    选择了正确的文件格式,生成的公钥私钥就可以使用了。

    这篇博文中有关于文件格式的大体介绍

    http://blog.csdn.net/tuhuolong/article/details/42778945

           这篇文章并没有对原理进行剖析,只是说明了一下使用方法,而且使用方法不是很好,我想框架中应该也有可以实现的方法,但是目前还没有找到,如果有哪位朋友找到了,一定要记得私信告诉我,谢谢。

    不知道怎么传文件 贴一份源码吧 (源码中包括生成动态key 以及加密解密可能会有多余的方法,因为是在别人的源码基础上修改的)

    需要引入:

    libcrypto.a

    libssl.a

    以及openssl框架(我直接从支付宝的框架里搞来的)

    需要导入框架

    //

    //RYTRSAEncryptor.h

    //SMSCodeTest

    //Created by timmy on 16/10/19.

    //Copyright © 2016年 timmy. All rights reserved.

    //

    #import <Foundation/Foundation.h>

    #import <openssl/rsa.h>

    @interface RYTRSAEncryptor : NSObject

    + (void)keyWith:(void(^)(NSString *pubKey, NSString *priKey))block;

    /**

    *加密方法

    *

    *@param str需要加密的字符串

    *@param pubKey公钥字符串

    */

    + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;

    + (SecKeyRef)addPublicKey:(NSString *)key;

    /**

    *解密方法

    *

    *@param str需要解密的字符串

    *@param privKey私钥字符串

    */

    + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey;

    + (SecKeyRef)addPrivateKey:(NSString *)key;

    @end

    //RYTRSAEncryptor.m

    //SMSCodeTest

    //Created by timmy on 16/10/19.

    //Copyright © 2016年 timmy. All rights reserved.

    #import "RYTRSAEncryptor.h"

    #import <Security/Security.h>

    #import <openssl/rsa.h>

    #import <openssl/pem.h>

    #import "RYTBase64.h"

    @implementation  RYTRSAEncryptor

    staticNSString *base64_encode_data(NSData *data){

    data = [data base64EncodedDataWithOptions:0];

    NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    returnret;

    }

    staticNSData *base64_decode(NSString *str){

    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];

    returndata;

    }

    #pragma mark -生成密钥

    /* START: creat keys */

    + (void)keyWith:(void(^)(NSString *pubKey, NSString *priKey))block {

    /* 产生RSA密钥 */

    RSA *rsa =NULL;

    rsa = RSA_new();

    //产生一个模为num位的密钥对,e为公开的加密指数,一般为65537(0x10001)

    rsa = RSA_generate_key(1024,0x10001,NULL,NULL);

    // 路径

    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];

    /* 提取公钥字符串 */

    // 最终存储的地方,所以需要创建一个路径去存储字符串

    NSString *pubPath = [documentsPath stringByAppendingPathComponent:@"PubFile.txt"];

    FILE* pubWrite =NULL;

    pubWrite = fopen([pubPath UTF8String],"wb");

    if(pubWrite ==NULL)

    NSLog(@"Read Filed.");

    else

    {

    PEM_write_RSA_PUBKEY(pubWrite,rsa);

    fclose(pubWrite);

    }

    NSString *str=[NSString stringWithContentsOfFile:pubPath encoding:NSUTF8StringEncoding error:nil];

    str = [str stringByReplacingOccurrencesOfString:@"-----BEGIN PUBLIC KEY-----"withString:@""];

    str = [str stringByReplacingOccurrencesOfString:@"-----END PUBLIC KEY-----"withString:@""];

    str = [str stringByReplacingOccurrencesOfString:@"\n"withString:@""];

    /*提取私钥字符串*/

    NSString *priPath = [documentsPath stringByAppendingPathComponent:@"PriFile.txt"];

    FILE *priWtire =NULL;

    priWtire = fopen([priPath UTF8String],"wb");

    EVP_PKEY *pkey =NULL;

    if(priWtire ==NULL) {

    NSLog(@"Read Filed.");

    }else{

    //函数使用PKCS#8标准保存EVP_PKEY里面的私钥到文件或者BIO中,并采用PKCS#5

    //v2.0的标准加密私钥。enc参数定义了使用的加密算法。跟其他PEM的IO函数不一样的是,本函数的加密是基于PKCS#8层次上的,而不是基于PEM信息字段的,所以这两个函数也是单独实现的函数,而不是宏定义函数。如果enc参数为NULL,那么就不会执行加密操作,只是使用PKCS#8私钥 信息结构。成功执行返回大于0 的数,否则返回0。

    pkey = EVP_PKEY_new();

    EVP_PKEY_assign_RSA(pkey, rsa);

    PEM_write_PKCS8PrivateKey(priWtire, pkey,NULL,NULL,0,0,NULL);

    fclose(priWtire);

    }

    NSString *priStr=[NSString stringWithContentsOfFile:priPath encoding:NSUTF8StringEncoding error:nil];

    priStr = [priStr stringByReplacingOccurrencesOfString:@"-----BEGIN PRIVATE KEY-----"withString:@""];

    priStr = [priStr stringByReplacingOccurrencesOfString:@"-----END PRIVATE KEY-----"withString:@""];

    priStr = [priStr stringByReplacingOccurrencesOfString:@"\n"withString:@""];

    block(str,priStr);

    }

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

    /* START: Encryption with RSA public key */

    //使用公钥字符串加密(PKCS8格式)

    + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey{

    NSData *data = [selfencryptData:[str dataUsingEncoding:NSUTF8StringEncoding] publicKey:pubKey];

    NSString *ret = base64_encode_data(data);

    returnret;

    }

    + (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey{

    if(!data || !pubKey){

    returnnil;

    }

    SecKeyRef keyRef = [selfaddPublicKey:pubKey];

    if(!keyRef){

    returnnil;

    }

    return[selfencryptData:data withKeyRef:keyRef];

    }

    //构建公钥(PKCS8格式)

    + (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:@""];

    //key经过base64编码 解码

    NSData *data = base64_decode(key);

    data = [selfstripPublicKeyHeader:data];

    if(!data){

    returnnil;

    }

    //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:(__bridgeid) kSecClassKey forKey:(__bridgeid)kSecClass];

    [publicKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];

    [publicKey setObject:d_tag forKey:(__bridgeid)kSecAttrApplicationTag];

    SecItemDelete((__bridgeCFDictionaryRef)publicKey);

    // Add persistent version of the key to system keychain

    [publicKey setObject:data forKey:(__bridgeid)kSecValueData];

    [publicKey setObject:(__bridgeid) kSecAttrKeyClassPublic forKey:(__bridgeid)

    kSecAttrKeyClass];

    [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridgeid)

    kSecReturnPersistentRef];

    CFTypeRef persistKey =nil;

    OSStatus status = SecItemAdd((__bridgeCFDictionaryRef)publicKey, &persistKey);

    if(persistKey !=nil){

    CFRelease(persistKey);

    }

    if((status != noErr) && (status != errSecDuplicateItem)) {

    returnnil;

    }

    [publicKey removeObjectForKey:(__bridgeid)kSecValueData];

    [publicKey removeObjectForKey:(__bridgeid)kSecReturnPersistentRef];

    [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridgeid)kSecReturnRef];

    [publicKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];

    // Now fetch the SecKeyRef version of the key

    SecKeyRef keyRef =nil;

    status = SecItemCopyMatching((__bridgeCFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);

    if(status != noErr){

    returnnil;

    }

    returnkeyRef;

    }

    + (NSData *)stripPublicKeyHeader:(NSData *)d_key{

    // Skip ASN.1 public key header

    if(d_key ==nil)return(nil);

    unsignedlonglen = [d_key length];

    if(!len)return(nil);

    unsignedchar*c_key = (unsignedchar*)[d_key bytes];

    unsignedintidx=0;

    if(c_key[idx++] !=0x30)return(nil);

    if(c_key[idx] >0x80) idx += c_key[idx] -0x80+1;

    elseidx++;

    // PKCS #1 rsaEncryption szOID_RSA_RSA

    staticunsignedcharseqiod[] =

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

    elseidx++;

    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{

    constuint8_t *srcbuf = (constuint8_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(intidx=0; idx

    //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);

    returnret;

    }

    /* END: Encryption with RSA public key */

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

    /* START: Decryption with RSA private key */

    //使用私钥字符串解密

    + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey{

    if(!str)returnnil;

    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];

    data = [selfdecryptData:data privateKey:privKey];

    NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    returnret;

    }

    + (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey{

    if(!data || !privKey){

    returnnil;

    }

    SecKeyRef keyRef = [selfaddPrivateKey:privKey];

    if(!keyRef){

    returnnil;

    }

    return[selfdecryptData:data withKeyRef:keyRef];

    }

    //(PKCS8格式)

    + (SecKeyRef)addPrivateKey:(NSString *)key{

    NSRange spos = [key rangeOfString:@"-----BEGIN PRIVATE KEY-----"];

    NSRange epos = [key rangeOfString:@"-----END 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 = [selfstripPrivateKeyHeader:data];

    if(!data){

    returnnil;

    }

    //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:(__bridgeid) kSecClassKey forKey:(__bridgeid)kSecClass];

    [privateKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];

    [privateKey setObject:d_tag forKey:(__bridgeid)kSecAttrApplicationTag];

    SecItemDelete((__bridgeCFDictionaryRef)privateKey);

    // Add persistent version of the key to system keychain

    [privateKey setObject:data forKey:(__bridgeid)kSecValueData];

    [privateKey setObject:(__bridgeid) kSecAttrKeyClassPrivate forKey:(__bridgeid)

    kSecAttrKeyClass];

    [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridgeid)

    kSecReturnPersistentRef];

    CFTypeRef persistKey =nil;

    OSStatus status = SecItemAdd((__bridgeCFDictionaryRef)privateKey, &persistKey);

    if(persistKey !=nil){

    CFRelease(persistKey);

    }

    if((status != noErr) && (status != errSecDuplicateItem)) {

    returnnil;

    }

    [privateKey removeObjectForKey:(__bridgeid)kSecValueData];

    [privateKey removeObjectForKey:(__bridgeid)kSecReturnPersistentRef];

    [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridgeid)kSecReturnRef];

    [privateKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];

    // Now fetch the SecKeyRef version of the key

    SecKeyRef keyRef =nil;

    status = SecItemCopyMatching((__bridgeCFDictionaryRef)privateKey, (CFTypeRef *)&keyRef);

    if(status != noErr){

    returnnil;

    }

    returnkeyRef;

    }

    + (NSData *)stripPrivateKeyHeader:(NSData *)d_key{

    // Skip ASN.1 private key header

    if(d_key ==nil)return(nil);

    unsignedlonglen = [d_key length];

    if(!len)return(nil);

    unsignedchar*c_key = (unsignedchar*)[d_key bytes];

    unsignedintidx=22;//magic byte at offset 22

    if(0x04!= c_key[idx++])returnnil;

    //calculate length of the key

    unsignedintc_len = c_key[idx++];

    intdet = c_len &0x80;

    if(!det) {

    c_len = c_len &0x7f;

    }else{

    intbyteCount = c_len &0x7f;

    if(byteCount + idx > len) {

    //rsa length field longer than buffer

    returnnil;

    }

    unsignedintaccum =0;

    unsignedchar*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{

    constuint8_t *srcbuf = (constuint8_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(intidx=0; idx

    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,

    kSecPaddingPKCS1,

    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!

    intidxFirstZero = -1;

    intidxNextZero = (int)outlen;

    for(inti =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);

    returnret;

    }

    @end

    比起码源码,还是放项目比较直接,这个是项目地址,有兴趣的同学可以看看。

    https://git.oschina.net/euagore/smscodeframework.git

    相关文章

      网友评论

      • 鱼尾巴_e472:大佬,怎么改成使用私钥加密, 公钥解密,我尝试改,但是没有成功
      • 冰三尺:请问下, demo中是使用公钥加密, 使用私钥解密, 怎么改成使用私钥加密, 公钥解密呢?
        TimmyR:你把相应的加密函数中的私钥和公钥对换,把其中的获取公钥私钥的方法换一下应该就可以了,但是我还没有尝试:grin:
      • 雨影:"但是大多是利用公钥私钥文件,或者直接接收RSA公私钥字符串进行加密解密,没有生成并转换成字符串,这里我们就介绍一下我是如何实现这个功能的,以备后用。"
        可是,你第一部分,在终端操作生成公钥私钥文件的还是在 PC 端做的呀?
        TimmyR:@雨影 :smile:
        雨影:@TimmyR 哦哦,没仔细看,抱歉
        TimmyR:对 因为我第一部分说的是:首先介绍利用终端生成公钥私钥
        再下面,有在工程中动态生成公钥私钥的方法呢

      本文标题:ios中生成RSA密钥字符串

      本文链接:https://www.haomeiwen.com/subject/munzdttx.html