Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES using Base64 Encryption

Tags:

java

base64

aes

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?

like image 444
Frederik Avatar asked Apr 08 '11 13:04

Frederik


People also ask

Does AES use Base64?

AES Secret KeyBy default, the encrypted text will be base64 encoded but you have options to select the output format as HEX too.

Can Base64 used as an encryption method?

Sometimes Base64 is used to encrypt the plaintext, but it does not have the key. Everyone can decrypt the message by knowing the table pattern. This study describes the process of encryption and decryption using Base64.

How do you encrypt using AES?

The AES Encryption algorithm (also known as the Rijndael algorithm) is a symmetric block cipher algorithm with a block/chunk size of 128 bits. It converts these individual blocks using keys of 128, 192, and 256 bits. Once it encrypts these blocks, it joins them together to form the ciphertext.

Can we decrypt AES without key?

With symmetric encryption, only one secret key is used for both encryption and decryption, so if the key is not known, then AES-encrypted data cannot be read or understood.


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")
like image 108
Jon Skeet Avatar answered Oct 14 '22 09:10

Jon Skeet


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");
like image 42
SLaks Avatar answered Oct 14 '22 08:10

SLaks