0
votes

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?

2
The code on Android is not using hybrid encryption and uses the default platform encoding for getBytes(). Furthermore, since you cannot create your certificate you may need to look for methods of injecting your public key in a different manner. At least post your input if the current method is not working. - Maarten Bodewes

2 Answers

1
votes

MIHCrypto has everything i need. https://github.com/hohl/MIHCrypto

0
votes

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.