I'm making a program that can encrypt and decrypt text using various methods, for DES encryption, my program generates a key by doing
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
The string of text supplied is successfully encrypted, the key converted to string using the toString() method looks like something like this
com.sun.crypto.provider.DESKey@18738
However, when I supply the same key (the toString one), like this
byte[] decodedKey = com.sun.crypto.provider.DESKey@18738.getBytes();
it says "Invalid key length: 36 bytes" which is weird, because the same key was used to encrypt and decrypt the same string of text.
Here is how I encrypt:
try {
Cipher desCipher;
byte[] decodedKey = pass.getText().getBytes();//the password is supplied here
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "DES");
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
byte[] text = input.getText().getBytes();
desCipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] textDecrypted = desCipher.doFinal(input.getText().getBytes());
output.setText(Arrays.toString(textDecrypted));
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException ex) {
Error(ex.getMessage());
Logger(ex.getMessage());
}
Here is how I decrypt:
try {
Cipher desCipher;
byte[] decodedKey = pass.getText().getBytes();
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "DES");
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
byte[] text = input.getText().getBytes();
desCipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] textDecrypted = desCipher.doFinal(input.getText().getBytes());
output.setText(Arrays.toString(textDecrypted));
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException ex) {
Error(ex.getMessage());
Logger(ex.getMessage());
}
For some reason, the code is poorly indented even though I used netbeans to fix it, probably because it's in like 10 switch blocks...
Thank you for your help!