import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.*;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.Arrays;
import java.util.*;
public class AES {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("Enter your 16 character key here:");
String EncryptionKey = input.next();
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
System.out.println("Enter text to encrypt or decrypt:");
String Text = input.next();
System.out.println("Do you want to encrypt or decrypt (e/d)");
String answer = input.next();
if (answer.equalsIgnoreCase("e")) {
byte[] byteKey = (EncryptionKey.getBytes());
byte[] byteText = (Text).getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
byte[] byteCipherText = AesCipher.doFinal(byteText);
System.out.println(byteCipherText);
} else if (answer.equalsIgnoreCase("d")) {
byte[] byteKey = (EncryptionKey.getBytes());
byte[] byteText = (Text).getBytes();
String decryptKeyString = input.nextLine();
Charset charset = StandardCharsets.UTF_16;
byte[] cipherText = decryptKeyString.getBytes(charset);
SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
//byte[] bytePlainText = AesCipher.doFinal(cipherText);
String plaintext = new String(AesCipher.doFinal(cipherText), "UTF-8");
//Files.write(Paths.get(FileName2), bytePlainText);
System.out.println(plaintext);
}
}
}
TERMINAL OUTPUT:
Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
helloworld
Do you want to encrypt or decrypt (e/d)
e
[B@504bae78
//SECOND RUN OF PROGRAM
Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
[B@504bae78
Do you want to encrypt or decrypt (e/d)
d
This code is largely repurposed from other code on StackExchange, I just wanted to adapt the code to not use files but to use the console instead. For some reason decryption always returns empty for me though.
If you could help me out with what specific line I have wrong that would be greatly appreciated. Thanks so much.