AES using Base64 Encryption

my goal is to encrypt the string with AES I use Base64 for encryption because AES requires an array of bytes as input. In addition, I want all possible Char (including Chinese and German characters) stored correctly

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

I thought “some input” should be typed. Instead, "someinpu" is printed. Unable to use sun.misc. * Instead, I use apache.commons.codec

Does anyone know what is going wrong?

+4
source share
2 answers

Yes - "some input" is not a valid base64 encoded string.

The idea of ​​base64 is that you encode binary data into text. Then you decode this text data into an array of bytes. You cannot simply decode any arbitrary text, as if it were a complete base64 message, moreover, you can try to decode mp3 as a jpeg image.

String encryption should be as follows:

  • Encode a string to binary data, for example. using UTF-8 ( text.getBytes("UTF-8") )
  • Encrypt binary data with AES
  • Encode cyphertext with Base64 to get text

Decryption is a question:

  • Decode base64 text to binary cyphertext
  • Decrypt cyphertext to get binary plaintext
  • Decoding binary plaintext to a string using the same encoding as the first step above, for example. new String(bytes, "UTF-8")
+18
source

You cannot use Base64 to turn arbitrary text into bytes; it is not what it is intended.

Instead, you should use UTF8:

 byte[] plainTextBytes = inputString.getBytes("UTF8"); String output = new String(plainTextBytes, "UTF8"); 
+1
source

Source: https://habr.com/ru/post/1347252/


All Articles