Aes Using Base64 Encryption

Aes Using Base64 Encryption

my target is to encrypt a String with AES I am using Base64 for encryption, because AES needs a byte array as input. Moreover i want every possible Char(including chinese and german Symbols) to be stored correctly

    byte[] encryptedBytes = Base64.decodeBase64 ("some input");
System.out.println(new Base64().encodeToString(encryptedBytes));

I thought "some input" should be printed. Instead "someinpu" is printed. It is impossible for me to use sun.misc.* Instead i am using apache.commons.codec

Does someone has a clue what's going wrong?

2 Answers

Yes - "some input" isn't a valid base64 encoded string.

The idea of base64 is that you encode binary data into text. You then decode that text data to a byte array. You can't just decode any arbitrary text as if it were a complete base64 message any more than you can try to decode an mp3 as a jpeg image.

Encrypting a string should be this process:

  • Encode the string to binary data, e.g. using UTF-8 (text.getBytes("UTF-8"))
  • Encrypt the binary data using AES
  • Encode the cyphertext using Base64 to get text

Decryption is then a matter of:

  • Decode the base64 text to the binary cyphertext
  • Decrypt the cyphertext to get the binary plaintext
  • Decode the binary plaintext into a string using the same encoding as the first step above, e.g. new String(bytes, "UTF-8")

You cannot use Base64 to turn arbitrary text into bytes; that's not what it's designed to do.

Instead, you should use UTF8:

byte[] plainTextBytes = inputString.getBytes("UTF8");

String output = new String(plainTextBytes, "UTF8");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.