开发者

AES using Base64 Encryption

my target is to encryp开发者_如何学编程t 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?


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜