AES加密错误:javax.crypto.BadPaddingException

时间:2015-02-14 19:47:14

标签: java encryption aes javax.crypto badpaddingexception

我在这段代码中遇到以下错误: javax.crypto.BadPaddingException:给定最终块没有正确填充。我指出了程序中发生错误的位置。

package aes;

import javax.crypto.*;
import java.security.*;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.*;


public class AESencrpytion {

  //private static final byte[] keyValue = new byte[]{'S','e','c','r','e','t'};


  public static String encrypt(String data) throws Exception{
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    SecureRandom rand = new SecureRandom();
    keyGen.init(rand);
    Key key = keyGen.generateKey();
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encValue = cipher.doFinal(data.getBytes());
    String encryptedValue = new BASE64Encoder().encode(encValue);
    return encryptedValue;
  }

  public static String decrypt(String encData) throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    SecureRandom rand = new SecureRandom();
    keyGen.init(rand);
    Key key = keyGen.generateKey();
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decodedValue = new BASE64Decoder().decodeBuffer(encData);
    //ERROR HAPPENS HERE
    byte[] decValue = cipher.doFinal(decodedValue);
    String decryptedVal = new String(decValue);
    return decryptedVal;
  }

主要班级:

package aes;

public class AEStest {

  public static void main(String[] args) throws Exception {

    String password = "mypassword";
    String passwordEnc = AESencrpytion.encrypt(password);
    String passwordDec = AESencrpytion.decrypt(passwordEnc);

    System.out.println("Plain Text : " + password);
    System.out.println("Encrypted Text : " + passwordEnc);
    System.out.println("Decrypted Text : " + passwordDec);
  }
}

我是AES和加密的新手,这是一项家庭作业。感谢您的帮助!我很感激。

1 个答案:

答案 0 :(得分:0)

您在加密和解密期间使用不同的密钥,因为它们是在两种方法中随机生成的。您必须使用相同的键。

在类中添加init方法以生成密钥一次,或者在类之外生成密钥并将其传递给两个方法。