java - 消息编码可能存在错误

标签 java encoding base64 decoding

我正在尝试创建一个简单的类,它显示要编码的消息、编码的消息和解码的消息。但我认为我的课是错误的。这是我对该函数的解释:

String messageToEncode = "a";

try {
    //We create a key
    SecretKey key = KeyGenerator.getInstance("AES").generateKey();
    // We choose method AES in order to encode message
    Cipher cipher = Cipher.getInstance("AES");
    //We enter the encoding phase of the message
    cipher.init(Cipher.ENCRYPT_MODE, key);
    //We transform the encoded message from String to Byte
    byte[] res = cipher.doFinal(messageToEncode.getBytes());
    //We transform the encoded message from Byte to String. Here we have a coded message that needs the key to be read
    String codedMessage = Base64.getEncoder().encodeToString(res);
    //We enter the decoding phase of the message
    cipher.init(Cipher.DECRYPT_MODE, key);
    //We decode the encoded message
    byte[] res2 = cipher.doFinal(Base64.getDecoder().decode(codedMessage));
    //We display the decoded message
    String decodedMessage = new String(res2);
    //We display the message sent at the beggin
    System.out.println("Message:" + messageToEncode);
    //We display the encoded message
    System.out.println("Encoded message:" + codedMessage);
    //We display the decoded message
    System.out.println("Decoded message:" + decodedMessage);
    //We recover the key 
    byte[] keyByte = key.getEncoded();
    //We display the key
    System.out.println(Base64.getEncoder().encodeToString(keyByte));
} catch (Exception ex) {
}

}

我的输出是:

Message to code:a
Encoded message:oIgc5kuv8ROgCqNkpndCPQ==
Decoded message:a
u645vsT3RP5FRHLtGfIhrA==

我认为我的类是错误的,因为要编码的消息仅由一个字母组成,但编码后的消息由 26 个字母组成!它不应该也是由一个字母组成吗?所以我想知道我得到的是否正常。

预先感谢所有花时间帮助我的人。

P.S:我将 JDK 12 与 NetBeans 11 一起使用。

最佳答案

你所看到的就是你应该期待的。

AES 是一种分组密码:它以 16 字节的 block 来加密数据。如果输入数据不是 16 字节的偶数倍,则会进行填充。我希望以某种方式包含数据的原始长度,因此如果 AES 中加密单个字节的输出略长于 16 个字节,我不会感到惊讶。

Base64 对于输入中的每个 3 字节 block 输出 4 字节。在 16 个输入字节中,有 6 个这样的 block ,因此加密消息在 Base64 中至少变为 24 个字节。

关于java - 消息编码可能存在错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61205805/

相关文章:

java - AbsListView$RecycleBin.addScrapView() 问题中的 SectionedAdapter ArrayIndexOutOfBoundsException?

java - 如何使用抽象从方法更新数组

sql - 奇怪的编码问题 ¶

css - 从网页或 CSS 中替换/删除 base64 编码的图像和链接

base64 - 为什么 SHA256 哈希值以 "= "结尾?

java - 将 JTextField 输入限制为整数

java - JUnit 测试 : Improvement to test case, 测试数组列表的长度?

c# - 在 Silverlight 中将 windows-1252 编码转换为 UTF-8

java - 当我使用 bufferedReader 时如何检测编码

Android BitmapFactory 在 Base64 解码字节数组上返回 null