I'm implementing the following steps:
- Bob encrypts a message with AES
- Bob encodes the encryption to a base64 string
- Bob writes the string to a file
- Alice reads the file
- Alice converts the string to byte
- Alice decrypts the message
However, I'm failing at the last step.
Heres the encryption:
public void sendHelloWorld() {
String msg = "hello world!";
try {
SecretKeySpec AesKeySpec = new SecretKeySpec(aesKeyBytes, "AES");
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, AesKeySpec);
aesEncryptedHello = c.doFinal(msg.getBytes());
} catch (BadPaddingException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
String s = new String(aesEncryptedHello, StandardCharsets.UTF_8);
System.out.println("Message = " + s);
sendMessage(Base64.getEncoder().encodeToString(aesEncryptedHello));
}
Here's the decrypt:
public void decryptAESMessage(byte[] encryptedMessage) {
try {
String s = new String(encryptedMessage, StandardCharsets.UTF_8);
System.out.println("Message = " + s);
SecretKeySpec AesKeySpec = new SecretKeySpec(bobAesKey, "AES");
Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, AesKeySpec);
byte[] aesMessage = c.doFinal(encryptedMessage);
String message = new String(aesMessage, StandardCharsets.UTF_8);
System.out.println("Message is " + message);
} catch (BadPaddingException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
Here's the write to file:
public void sendMessage(String msg) {
try {
FileWriter myWriter = new FileWriter(<myredactedfilepath>);
myWriter.write(msg);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");}
}
Here's stage 5, just to show the decode isn't missed:
alice.decryptAESMessage(Base64.getDecoder().decode(alice.readEncryptedMessage()));
I print the keys and the encrypted messages at both ends and they match.