RSA decypt失败,javax.crypto.BadPaddingException:解密错误

时间:2017-08-28 12:03:44

标签: java encryption rsa badpaddingexception

我使用bouncycastle解密RSA加密字符串,并且数据在Base64中编码,但是当我javac Decrypt.java和java Decrypt时,它显示错误表示" avax.crypto.BadPaddingException:解密错误&#34 ; ,这是代码:

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解密它时,它运行良好。

谁可以帮我解决这个错误?感谢。

0 个答案:

没有答案