2017-04-03 200 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(); 

注意,如果你想以後生成密碼相同的密鑰,你必須存儲在隨機鹽。