Reputation: 644
I need to encrypt a NSString using a public key from a webserver certificate on iOS. This is what I am doing on Android (works fine):
public byte[] Encrypt(String plain) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
publicKey = "MyPublicKeyStringExtractedFromACertificate"
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
return encryptedBytes;
}
This is what I am trying on iOS:
NSString *publicKey = @"MyPublicKeyStringExtractedFromACertificate"; // Base64 encoded key from my webserver certificate
NSData *keyData = [[NSData alloc] initWithBase64EncodedString:publicKey options:NSDataBase64DecodingIgnoreUnknownCharacters];
SecCertificateRef certificate = SecCertificateCreateWithData(kCFAllocatorDefault, ( __bridge CFDataRef) keyData); // this is returning nil
The publickey comes from a webservice certificate (on my app bundle).
What I am doing wrong? How could i use SecKeyEncrypt?
Upvotes: 0
Views: 3345
Reputation: 8467
You can't encrypt with Java Cipher using a string as the public key. You need a PublicKey object. For example:
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(der_bytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(publicSpec);
der_bytes needs to be in DER form, not PEM form, here.
Upvotes: 0