在我的iOS库中,我有一个包含X.509 RSA 2048位公钥的Base64编码字符串。我想使用此公钥加密字符串。任何人都可以提供一些Objective C代码参考,提到我需要包含的库吗?
等效的Java代码如下所示:
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);
答案 0 :(得分:0)
试试这段代码:
// 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