2014-03-12 40 views
1

我正在爲AES算法做一個簡單的實現。AES算法JAVA Giving:java.lang.IllegalArgumentException:無效的密鑰大小

// Get the Key Generator 
    KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
    kgen.init(128); // 192 and 256 bits may not be available 
     // Generate the secret key specs. 
     SecretKey secret = kgen.generateKey(); 
     byte[] raw = secret.getEncoded(); 

String key = new String(Base64.encodeBase64(raw)); 

我在數據庫中保存了"key"。 現在再次在另一個操作中,我從數據庫n中獲取一個「密鑰」,試圖解密數據。我叫解密功能

String dencryptReq = Utils.decrypt2(new String(Base64.decodeBase64(secretKeyInformation.getSecretKey().getBytes())),Base64.decodeBase64(encryptReq.getBytes())); 


public static String decrypt2(String key, byte[] encrypted) 
     throws GeneralSecurityException { 

    byte[] raw = Base64.decodeBase64(key.getBytes()); 
    if (raw.length != 16) { 
     throw new IllegalArgumentException("Invalid key size."); 
    } 
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, 
      new IvParameterSpec(new byte[16])); 
    byte[] original = cipher.doFinal(encrypted); 

    return new String(original, Charset.forName("US-ASCII")); 
} 

But it is throwing me invalid key size exception. 

If i do in one time this without saving in databse and fetching from database it is working fine. 

回答

0

我曾嘗試你的代碼有一些修改我用阿帕奇公地編解碼器庫支持Base64轉換,

/* Derive the key, given password and salt. */ 
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
KeySpec spec = new PBEKeySpec("password".toCharArray(), "salt".getBytes(), 65536, 128); 
SecretKey tmp = factory.generateSecret(spec); 
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); 


/* Encrypt the message. */ 
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
cipher.init(Cipher.ENCRYPT_MODE, secret); 
AlgorithmParameters params = cipher.getParameters(); 
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); 
byte[] ciphertext = cipher.doFinal("Hello, World! My data is here.. !".getBytes("UTF-8")); 
System.out.println("cipher :"+new String(ciphertext)); 






/*String-key convertion */ 
String stringKey=Base64.encodeBase64String(secret.getEncoded());//To String key 
byte[] encodedKey  = Base64.decodeBase64(stringKey.getBytes()); 
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");// Convert from string 



/* Decrypt the message, given derived key and initialization vector. */ 
Cipher cipher1 = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
cipher1.init(Cipher.DECRYPT_MODE, originalKey, new IvParameterSpec(iv)); 
String plaintext = new String(cipher1.doFinal(ciphertext), "UTF-8"); 
System.out.println(plaintext); 

這段代碼在我的系統非常完美。