0

我使用 bouncycastle 解密 RSA 加密字符串,数据以 Base64 编码,但是当我 javac Decrypt.java 和 java Decrypt 时,它显示错误“avax.crypto.BadPaddingException: Decryption error”,这是代码:

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);
}
}

当我运行代码时,我收到此错误:

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)

我确信密钥是正确的,因为当我用 Python 解密它时,它运行良好。

谁能帮我解决这个错误?谢谢。

4

0 回答 0