开发者

invalid AES key length error

this code give invalid AES key length error. how can i correct it ? ( i want 128 bit key AES encryption )

package org.temp2.cod1;
import java.security.*;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;

public class Code1 {

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    String s = "9882623867";
    byte[] plaintext = s.getBytes("UTF-16");
    String s2 = "supernova";
    byte[] key = s2.getBytes("UTF-16");
    Cipher c = Cipher.getInstance("AES");
    SecretKeySpec开发者_StackOverflow中文版 k =  new SecretKeySpec(key, "AES");
    c.init(Cipher.ENCRYPT_MODE, k);
    byte[] encryptedData = c.doFinal(plaintext);
    System.out.println(encryptedData);
}
}

any help appreciated


Use a SecretKeyFactory to derive key bytes from a password.You can see a detailed example here. Note that you'll need to specify a key length of 128 bits key instead of 256 bits as shown in that example.

The next problem that you will run into is that you have not specified a padding scheme. Unless your messages are a multiple of 16 bytes (the AES block size), that will raise an error. Use PKCS5Padding as shown in the example.

Use of CBC mode on the cipher will require a new initialization vector to be chosen for each message. This unique IV must be sent along with the encrypted message to the recipient.

Trying to perform cryptography without a thorough understanding of the concepts raised here (and a lot more) is likely to result in an insecure system.


You can't typically use any arbitrary key length (such as you're doing here with "supernova") for a block cipher like AES. You must use a supported key length (128, 192, 256, etc) appropriate for your algorithm of choice.

One common way to do this is to hash your passphrase (e.g., via SHA) and extract the first N bytes. This is better anyhow, as it allows you to "salt" your password with an initialization value such that no two users' "keys" are identical even if their passphrases are the same. If you're really interested in this stuff, the seminal work is Applied Cryptography by Bruce Schneier.

For practical implementation details, see


You can get this error when the key you're trying to use isn't the right length.

So in psuedocode, you're trying something like this:

String key = "123";
SecretKeySpec k =  new SecretKeySpec(key, "AES");

but the key is too short - it needs to be something like, say 31 characters long.

So check your key value -> it's probably stored somewhere incorrectly.


Use a key Value string with 16 bytes for Smooth encryption e.g. The key "thebestsecretkey" will work on base64

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜