I used bouncycastle to decrypt RSA encrypted string, and the data is encoded in Base64, but when I javac Decrypt.java and java Decrypt, it shows an error said "avax.crypto.BadPaddingException: Decryption error" , this is the code:
import java.io.*;
import java.security.*;
import java.security.spec.*;
import sun.misc.BASE64Decoder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
class PemFile {
private PemObject pemObject;
public PemFile(String filename) throws FileNotFoundException, IOException {
PemReader pemReader = new PemReader(new InputStreamReader(
new FileInputStream(filename)));
try {
this.pemObject = pemReader.readPemObject();
} finally {
pemReader.close();
}
}
public PemObject getPemObject() {
return pemObject;
}
}
public class Decrypt {
public static void main(String[] args) throws Exception {
Security.addProvider(new
org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
PrivateKey privateKey = generatePrivateKey(factory, "pkcs8_rsa_private_key.pem");
// System.out.println(privateKey instanceof PrivateKey);
System.out.println(privateKey);
String encryptContent = new String(my_encrypt_content);
// System.out.println(Base64Utils.decode(encryptContent).length);
byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(encryptContent), privateKey);
System.out.println(decryptByte instanceof byte[]);
if (decryptByte != null){
String decryptStr = new String(decryptByte);
System.out.println(decryptStr);
}
else{
System.out.println("null");
}
}
// get the secret key
public static PrivateKey generatePrivateKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename);
byte[] content = pemFile.getPemObject().getContent();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
return factory.generatePrivate(privKeySpec);
}
}
when I run the code , I get this 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 RSAUtils.decryptData(RSAUtils.java:97)
at Decrypt.main(Decrypt.java:65)
I am sure that the secret key is correct, because when I decrypt this by Python, it works well.
Who can help me with this error? Thanks.