javax.crypto.BadPaddingException:解密错误[AES]

时间:2018-07-20 06:38:35

标签: java cypher aes badpaddingexception

我在网上搜索过,尝试了不同的方法来解决问题,但找不到解决方法! 这是给我那个错误的方法:

   public static void decode() throws Exception{

    //READ CODED PRIVATE KEY IN PKCS#8

    String privateKeystore ="C:\\Users\\dario\\Desktop\\Server\\chiaveprivata";
    FileInputStream fis = new FileInputStream (privateKeystore);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i=0;
    while ((i=fis.read()) != -1){
        baos.write(i);
    }
    fis.close();
    byte[] privateKeyBytes= baos.toByteArray();

    PKCS8EncodedKeySpec ks= new PKCS8EncodedKeySpec(privateKeyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = kf.generatePrivate(ks);

    //LEGGE FILE CODIFICATO

   String sorgente= "C:\\Users\\dario\\Desktop\\Client\\chiavecod";
   fis = new FileInputStream(sorgente);
   baos.reset(); 
   byte[] codFile;
   i = 0;
   while((i = fis.read()) != -1) {
    baos.write(i);
   }
   fis.close();
   codFile = baos.toByteArray();

   //DECODE

   System.out.print("\nDecoding");
   Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
   System.out.print(".");
   c.init(Cipher.DECRYPT_MODE, privateKey);
   System.out.print(".");
   byte [] plainFile= c.doFinal(codFile);
   System.out.println(". End!\n");

   //SAVE FILE


    String dest="C:\\Users\\dario\\Desktop\\Server\\chiavedecod";
    FileOutputStream fos = new FileOutputStream(dest);
    fos.write(plainFile);
    fos.close();

}//decode()

这给了我这个输出:

Decoding..Exception in thread "main" 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 tlcproject.RSAAlgorithm.decodifica(RSAAlgorithm.java:123)
    at tlcproject.Server.main(Server.java:34)

Process finished with exit code 1

问题似乎出在以下行代码上:byte [] plainFile= c.doFinal(codFile);,但我找不到解决方法!为什么应该出现填充错误? 我认为填充是正确的,所以当我尝试执行doFinal命令

时可能会出现问题

0 个答案:

没有答案