2017-04-03 202 views
-2

我想如下AES加密,InvalidKeyException:不支持的密钥大小:6个字节?

public class AES256Cipher { 
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}; 
static String EncryptionKey = "abc123"; 

public static byte[] encrypt(String plainText) 
     throws java.io.UnsupportedEncodingException, 
     NoSuchAlgorithmException, 
     NoSuchPaddingException, 
     InvalidKeyException, 
     InvalidAlgorithmParameterException, 
     IllegalBlockSizeException, 
     BadPaddingException { 
    byte[] keyBytes = EncryptionKey.getBytes("UTF-8"); 

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); 
    SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES"); 
    Cipher cipher = null; 
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec); 
    byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8")); 
    Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT)); 
    return cipher.doFinal(plainText.getBytes("UTF-8")); 
} 
} 

我得到这个例外

java.security.InvalidKeyException: Unsupported key size: 6 bytes 
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686) 
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442) 
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272) 
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608) 
at javax.crypto.Cipher.tryCombinations(Cipher.java:532) 
at javax.crypto.Cipher.getSpi(Cipher.java:437) 
at javax.crypto.Cipher.init(Cipher.java:909) 
at javax.crypto.Cipher.init(Cipher.java:859) 
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36) 
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61) 
at android.app.Activity.performCreate(Activity.java:6321) 

字符串加密

AES256Cipher.encrypt("12345"); 
+1

可能的重复[如何解决无效的AES密钥长度?](http://stackoverflow.com/questions/29354133/how-to-fix-invalid-aes-key-length) – Tom

+1

错误“无效密钥大小为6个字节“是否更清楚?我不明白你为什么需要问这个问题? –

回答

0

AES允许128192和密钥长度的256 bit加密字符串。 换句话说16,2432 byte

4

AES只支持16,24或32字节的密钥大小......所以你必须改变你的EncryptionKey。

SecureRandom random = new SecureRandom(); 
byte[] EncryptionKey = new byte[16]; 
random.nextBytes(EncryptionKey); 

您可以使用上面的代码示例。

+0

你应该说一些关键处理。如果没有正确的密钥处理,这不是很有用。 –

1

如果你想使用密码,你应该从你的密码派生一个AES密钥,而不是直接将密码用作密钥。

最简单的方法是使用SHA-256对密码进行哈希处理,并将哈希密码用作AES密钥。

常用的方法(首选)是使用PBKDF2例如与HMAC-SHA1产生从密码AES密钥(一百九十二分之一百二十八或256位):

byte[] salt = new byte[8]; 
random.nextBytes(salt); 
KeySpec spec = new PBEKeySpec(EncryptionKey.toCharArray(), salt, 65536, 128); 
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
byte[] keyBytes = f.generateSecret(spec).getEncoded(); 

注意,如果你想以后生成密码相同的密钥,你必须存储在随机盐。