I am having problems with Java Cryptography. I get this error: java.security.InvalidKeyException: Invalid key length: 12 bytes when I try to decrypt the message with skeySpec. However, if I use key it works fine. I think I used the same formats to encode the secretkeySpec. I want to use the secretkeySpec so that I can create my own key when I just pass a string to my decryptor later on. Please help me solve this problem of mine. Thanks. Below is my code:-
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.BadPaddingException;
import java.security.Key;
import java.security.Security;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import javax.crypto.spec.SecretKeySpec;
public class DESCryptoTest {
public static void main(String[] args) {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
try {
//generate key on SENDER
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
//String temp = new String("aaaaaa");
//key = stringToKey(temp);
//convert the byte array in key to a string
String st = new String(key.getEncoded());
System.out.println("key:" + st);
System.out.println("Key format: " + key.getFormat());
System.out.println("Key algorithm: " + key.getAlgorithm());
byte b[] = null;
//convert the string back to a byte array
b = st.getBytes();
//using the byte array it creates a secret key (i think it's something like a key
SecretKeySpec skeySpec = new SecretKeySpec(b, "DES");
System.out.println("key" + key.toString());
System.out.println("secret key: " + skeySpec);
System.out.println("secret key algo: " + skeySpec.getAlgorithm());
System.out.println("secret key format: " + skeySpec.getFormat());
//if u check the key and skeySpec are the same
String st2 = new String(skeySpec.getEncoded());
System.out.println("secretkey:" + st);
Cipher cipher = Cipher.getInstance("DES");
byte[] data = "try others!".getBytes();
System.out.println("Original data : " + new String(data));
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(data);
System.out.println("Encrypted data: " + new String(result));
//I tried to change the key to skeySpec since it seems the same, but got an error maybe it's the type of the class...
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(result);
System.out.println("Decrypted data: " + new String(original));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
}