Просто напоминание для тех, кто получает исключение Padding. Убедитесь, что вы используете правильную длину ключа. Подсказка: посмотрите на пост Мартена: его гекс ровно 32;) Это не случайно :)

у конвертировать String в secretKey

public void generateCode(String keyStr){ 
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
secretKey skey=keyStr;  //How can I make the casting here
//SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
}

Я пытаюсь использовать BASE64Decoder вместо secretKey, но я сталкиваюсь с проблемой, которая заключается в том, что я не могу указать длину ключа.

РЕДАКТИРОВАТЬ: Я хочу вызвать эту функцию из другого места

 static public String encrypt(String message , String key , int keyLength) throws Exception {
     // Get the KeyGenerator
   KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(keyLength); // 192 and 256 bits may not be available
    // Generate the secret key specs.
     SecretKey skey = key; //here is the error
   byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    // Instantiate the cipher
    Cipher cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    System.out.println("msg is" + message + "\n raw is" + raw);
    byte[] encrypted = cipher.doFinal(message.getBytes());
    String cryptedValue = new String(encrypted);
    System.out.println("encrypted string: " + cryptedValue);
    return cryptedValue;
}

Если бы кто-нибудь мог помочь, я был бы очень благодарен.

Ответы на вопрос(0)

Ваш ответ на вопрос