AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



corejava-exception-handling: Exception in thread main java.security.InvalidKeyException-Invalid AES key length-8 bytes


public class Test {

private static final String ALGORITHM = "AES";
private static final int ITERATIONS = 2;
private final static byte[] SALT = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8,
(byte) 0x32, (byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03 };

public static void main(String[] args) throws Exception {
String password = "mypassword";
String salt = "this is a simple clear salt";
String passwordEnc = Test.encrypt(password, salt);
String passwordDec = Test.decrypt(passwordEnc, salt);
System.out.println("Salt Text : " + salt);
System.out.println("Plain Text : " + password);
System.out.println("Encrypted : " + passwordEnc);
System.out.println("Decrypted : " + passwordDec);
}

public static String encrypt(String value, String salt) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
String valueToEnc = null;
String eValue = value;
for (int i = 0; i < ITERATIONS; i++) {
valueToEnc = salt + eValue;
byte[] encValue = c.doFinal(valueToEnc.getBytes());
eValue = new BASE64Encoder().encode(encValue);
}
return eValue;
}

public static String decrypt(String value, String salt) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
String dValue = null;
String valueToDecrypt = value;
for (int i = 0; i < ITERATIONS; i++) {
byte[] decordedValue = new BASE64Decoder()
.decodeBuffer(valueToDecrypt);
byte[] decValue = c.doFinal(decordedValue);
dValue = new String(decValue).substring(salt.length());
valueToDecrypt = dValue;
}
return dValue;
}

private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(SALT, ALGORITHM);
return key;
}

}

corejava x 353
exception-handling x 24
Posted On : 2015-03-13 17:38:09.0
profile Adarsh S - anyforum.in Adarsh S
3100
up-rate
3
down-rate

Answers


8 bytes would imply a 64-bit key - but there´s no such mode in AES. Try a 16 byte key for AES-128. There is a minimum key length of 128 bits (16 bytes).

Also, you should always specify an encoding when using String.getBytes. It´s just dangerous practice not to do that; don´t get in the habit.


To learn more about AES you can prefer this link: http://en.wikipedia.org/wiki/Advanced_Encryption_Standard

Posted On : 2015-03-13 18:27:09
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188250050
Reply This Thread
up-rate
3
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in