Encryption using X.509 2048 bit public key in iOS

╄→尐↘猪︶ㄣ 提交于 2019-12-24 03:28:04

问题


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?

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

回答1:


try this code:

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


来源:https://stackoverflow.com/questions/32887706/encryption-using-x-509-2048-bit-public-key-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!