在 iOS 中使用 X.509 2048 位公钥加密 [英] Encryption using X.509 2048 bit public key in iOS

查看:76
本文介绍了在 iOS 中使用 X.509 2048 位公钥加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 iOS 库中,我有一个 Base64 编码的字符串,其中包含 X.509 RSA 2048 位公钥.我想用这个公钥加密一个字符串.任何人都可以提供一些 Objective C 代码参考,提到我需要包含的库吗?

In my iOS library, I have a Base64 encoded string containing the X.509 RSA 2048 bit public key. I want to encrypt a string using this public key. Can anyone please provide some Objective C code reference, mentioning the libraries I need to include?

等效的java代码如下:

The equivalent java code looks as below:

byte[] keyBytes = Base64.decodeBase64(publicKeyData);
// Get Public Key
X509EncodedKeySpec rsaPublicKeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
encryptedData = cipher.doFinal(dataToEncrypt);   

推荐答案

试试这个代码:

// publicKeyBase64 is your public key string
NSData *publicKeyFileContent = [[NSData alloc] initWithBase64EncodedString:publicKeyBase64 options:0];

// get your public key
SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)publicKeyFileContent);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trust;
OSStatus status = SecTrustCreateWithCertificates(cert, policy, &trust);
SecTrustResultType trustResult;
if (status == noErr) {
    status = SecTrustEvaluate(trust, &trustResult);
}
SecKeyRef keyRef = SecTrustCopyPublicKey(trust);

// encrypt your data
// with this code you can encrypt only one block
// if you need to encrypt more data you need to use some chunking logic
const uint8_t *srcbuf = (const uint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t outlen = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
if(srclen > outlen - 11){
    CFRelease(keyRef);
    return nil;
}
void *outbuf = malloc(outlen);

OSStatus status = noErr;
status = SecKeyEncrypt(keyRef,
                       kSecPaddingPKCS1,
                       srcbuf,
                       srclen,
                       outbuf,
                       &outlen
                       );
NSData *ret = nil;
if (status != 0) {
    NSLog(@"SecKeyEncrypt fail. Error Code: %ld", status);
}else{
    ret = [NSData dataWithBytes:outbuf length:outlen];
}
free(outbuf);
CFRelease(cert);
CFRelease(policy);
CFRelease(trust);
CFRelease(keyRef);
// your encrypted data is in ret

这篇关于在 iOS 中使用 X.509 2048 位公钥加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆