简体   繁体   中英

AES Encryption error: javax.crypto.BadPaddingException

I'm getting the following error with this code: javax.crypto.BadPaddingException: Given final block not properly padded . I pointed out where the error is occurring in the program.

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

The main class:

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

I'm new to AES and encryption and this is for a homework assignment. Thank you for the help! I appreciate it.

You use different keys during encryption and decryption, because they are randomly generated in both methods. You have to use the same key.

Either add an init method to your class to generate the key once or generate the key outside of the class and pass it into both methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM