I am trying to encrypt phone numbers inside an android application using RSA keys with below steps. The encrypting keys are in X509 format and decrypting keys are in PKCS8 format.
PROBLEM FACED: The results of encryption a text and decrypting it back don't match.
Generate keys with:-
$ openssl genrsa -out privkey.pem 2048
$ openssl rsa -in privkey.pem -pubout > pubkey.pub
Convert private key into pkcs8 format:-
$ openssl pkcs8 -topk8 -inform PEM -outform PEM -in privkey.pem -out privkey.pkcs8 -nocrypt
Encryption code:-
String pubKeyPem = PUBKEY_X509.replace("-----BEGIN PUBLIC KEY-----\n", "")
.replace("-----END PUBLIC KEY-----", "");
byte [] encoded = Base64.decode(pubKeyPem, Base64.DEFAULT);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
privateKey = kf.generatePrivate(keySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
... encodedNum = cipher.doFinal(phNum);
Decryption code:
String privKeyPEM = PRIVATEKEY.replace("-----BEGIN PRIVATE KEY-----\n", "")
.replace("-----END PRIVATE KEY-----", "");
byte [] encoded = Base64.decode(privKeyPEM, Base64.DEFAULT);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
privateKey = kf.generatePrivate(keySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
... decNum = cipher.doFinal(encNum);
I am encoding a phone number. The encoded and decoded phone numbers dont match.
The algo encode 0000 to [B@4173bed8 .. and decodes the encoded bits back into [B@417412e8
As we can see the initial number (0000) and does not match the decrypted number ( [b41... ).
Please advice on how to correct this issue.
Thanks a lot.