I have an Android app which encrypts a text using RSA 2048 bit key.
Encryption and Decryption are working fine on the app.
My problem is that i am trying to encrypt on the application and then send the cipher to an external Java program for decryption.
Here is how it is done:
public static PrivateKey getPrivateKey(String key) {
try {
/* Add PKCS#8 formatting */
byte[] byteKey = Base64.getDecoder().decode(key.getBytes());
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(0));
ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.rsaEncryption.getId()));
v2.add(DERNull.INSTANCE);
v.add(new DERSequence(v2));
v.add(new DEROctetString(byteKey));
ASN1Sequence seq = new DERSequence(v);
byte[] privKey = seq.getEncoded("DER");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String cipherString,PrivateKey privateKey){
try{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainByte = cipher.doFinal(Base64.getDecoder().decode(cipherString));
return Base64.getEncoder().encodeToString(plainByte);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
But when i am trying to decryption the cipher i am getting error:
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at RSA.decrypt(RSA.java:94)
at RSA.main(RSA.java:116)
what am i missing?
UPDATE i regenerated a new pair of keys within Java itself and got rid of the part:
/* Add PKCS#8 formatting */
byte[] byteKey = Base64.getDecoder().decode(key.getBytes());
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(0));
ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.rsaEncryption.getId()));
v2.add(DERNull.INSTANCE);
v.add(new DERSequence(v2));
v.add(new DEROctetString(byteKey));
ASN1Sequence seq = new DERSequence(v);
byte[] privKey = seq.getEncoded("DER");
but I'm stuck with the same error!
Your padding is either not being set or set wrong.
Try changing Cipher cipher = Cipher.getInstance("RSA");
to Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
If that doesn't work you can see here for other padding modes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.