java AES 使用 Base64 加密
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5596040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AES using Base64 Encryption
提问by Frederik
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
我的目标是使用 AES 加密字符串我使用 Base64 进行加密,因为 AES 需要一个字节数组作为输入。此外,我希望正确存储每个可能的字符(包括中文和德语符号)
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
我认为应该打印“一些输入”。而是打印“someinpu”。我不可能使用 sun.misc.* 相反我使用 apache.commons.codec
Does someone has a clue what's going wrong?
有人知道出了什么问题吗?
回答by Jon Skeet
Yes - "some input" isn't a valid base64 encoded string.
是的 - “某些输入”不是有效的 base64 编码字符串。
The idea of base64 is that you encode binarydata into text. You then decode that textdata 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.
base64 的想法是将二进制数据编码为text。然后将该文本数据解码为字节数组。您不能像尝试将 mp3 解码为 jpeg 图像一样,将任意文本视为完整的 base64 消息进行解码。
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
- 将字符串编码为二进制数据,例如使用 UTF-8 (
text.getBytes("UTF-8")
) - 使用 AES 加密二进制数据
- 使用 Base64 对密文进行编码以获取文本
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")
- 将base64文本解码为二进制密文
- 解密密文得到二进制明文
- 使用与上述第一步相同的编码将二进制明文解码为字符串,例如
new String(bytes, "UTF-8")
回答by SLaks
You cannot use Base64 to turn arbitrary text into bytes; that's not what it's designed to do.
您不能使用 Base64 将任意文本转换为字节;这不是它的设计目的。
Instead, you should use UTF8:
相反,您应该使用 UTF8:
byte[] plainTextBytes = inputString.getBytes("UTF8");
String output = new String(plainTextBytes, "UTF8");