RSA算法在iOS 客户端的使用 加密方法代码

参考资料  http://blog.csdn.net/justinjing0612/article/details/7770315




+(void)initialize {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        //可选项1。根据证书的路径获取public_key

        NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];

        NSData *publicKeyData = [[NSData alloc] initWithContentsOfFile:publicKeyPath];

        

        //可选项2。直接用静态(经base64加密)的公钥得到public_key

//        NSData *publicKeyData = [GTMBase64 decodeString:RSA_KEY_BASE64];

        

        SecCertificateRef certificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)publicKeyData);

        if ( certificate ) {

            SecPolicyRef policy = SecPolicyCreateBasicX509();

            SecTrustRef trust;

            SecTrustResultType trustResult;

            OSStatus status = SecTrustCreateWithCertificates(certificate, policy, &trust);

            if ( status == noErr ) {

                status = SecTrustEvaluate(trust, &trustResult);//校验自签名证书问题

            }

            _public_key = SecTrustCopyPublicKey(trust);

            CFRelease(certificate);

            CFRelease(policy);

            CFRelease(trust);

        }

    });

}


// 获取公钥

+ (SecKeyRef)getPublicKey {

    return _public_key;

}


// RSA加密文本

+ (NSData *)rsaEncryptString:(NSString*)plainText {

    NSData *encryptedData = nil;

    

    SecKeyRef publicKey = [self getPublicKey];//获取公钥

    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);//公钥的长度

    uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));//分配空间

    memset(cipherBuffer, 0, cipherBufferSize * sizeof(uint8_t));//初始化0

    uint8_t *nonce = (uint8_t *) [plainText UTF8String];//文本转化

    OSStatus status = SecKeyEncrypt(publicKey,

                                    kSecPaddingPKCS1,

                                    nonce,

                                    strlen((char *) nonce),

                                    &cipherBuffer[0],

                                    &cipherBufferSize);//公钥和文本融合加密

    if (status == noErr) {

        encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];//如果转化成功就会转化成nsdata

    }

    if ( cipherBuffer ) {

        free(cipherBuffer);//释放空间

    }

    NSLog(@"Encrypted text (%@ bytes): %@", @(encryptedData.length), encryptedData.description);

    return encryptedData;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值