RSA

加密—非对称加密
非对称加密算法需要两个密钥:公开密钥(publickey) 和私有密(privatekey)
公开密钥和私有密钥是一对
如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密。
如果用私有密钥对数据进行加密,只有用对应的公开密钥才能解密。
特点
算法强度复杂,安全性依赖于算法与密钥。
加密解密速度慢。
使用
证书生成
http://blog.csdn.net/lining1041204250/article/details/79259920参考该博文

导入生成的private_key.p12(私钥)和public_key.der2(公钥)个文件

-(void)RSA{
NSString *publicPath = [[NSBundle mainBundle] pathForResource:@”public_key.der” ofType:nil];
[[RASTool rasInstance]loadPublicKeyWithPath:publicPath];

NSString *encryptString = [[RASTool rasInstance]rsaEncryptText:@"我是测试明文,你能把我加密成功吗,成功的话我就让你啪啪啪"];
NSLog(@"明文非对称加密过后的:%@",encryptString);

  NSString *privatePath = [[NSBundle mainBundle] pathForResource:@"private_key.p12" ofType:nil];
//生成证书的密码
 [[RASTool rasInstance] loadPrivateKeyWithPath:privatePath password:@"123456"];
NSString *string = [[RASTool rasInstance] rsaDecryptText:encryptString];
NSLog(@"非对称解密过后的结果:%@",string);

}
rastool
+(instancetype)rasInstance
{
static RASTool *ras = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ras = [[RASTool 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;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值