my first post.
I'm trying to asymmetrically encrypt data in JavaScript (in the user's browser), using the existing public key that I've used to successfully encrypt data in our native iOS and Android app.
I created the keys this way:
openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -keyout private_key.pem -days 3650
(Thanks to http://jslim.net/blog/2013/01/05/rsa-encryption-in-ios-and-decrypt-it-using-php/)
When I use these wonderful JavaScipt examples:
When I paste in my PEM formatted key, and encrypt a short string, I get what appears to be legitimate ciphertext in Base64, but it doesn't decrypt (I get a blank string). The decryption code works perfectly with the Base64 ciphertext from Android / iPhone.
The PEM public keys in these tutorials are generated with:
openssl genrsa -out rsa.pem 1024
openssl rsa -in rsa.pem -pubout
I converted my existing DER public key to PEM this way:
openssl x509 -in public_key.der -out nopass_public_with_cert.pem -inform DER -outform PEM
openssl x509 -pubkey -in nopass_public_with_cert.pem > public.pem
I believe the problem is the format/type of keys and files. Or misunderstanding of why certificates are involved / what I've actually created using the above openssl command. (What is PKCS?)
My question: How can I encrypt in Javascript using the existing keys, or convert these files into a format usable by JavaScript libraries?
If it helps to explain what I've done, here is the successful encryption in Android:
import java.security.(...);
import javax.crypto.Cipher;
String publickeybase64 = go_get_file_bytes_as_base64("public_key.der");
byte[]decode = Base64.decode(publickeybase64, Base64.DEFAULT);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(decode));
PublicKey publicKey = certificate.getPublicKey();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
String plaintext = "hello world";
String encryptedstring = new String(Base64.encode(cipher.doFinal(plaintext.getBytes()),Base64.NO_WRAP));
Thankyou all!