消息编码的可能错误

问题描述 投票:0回答:1

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

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一起使用。

java encoding base64 decoding
1个回答
0
投票

所见即所得。

AES是一种分组密码:它以16字节为一组对数据进行加密。如果输入数据不是16字节的偶数倍,则将其填充。我希望以某种方式包括数据的原始长度,因此如果在AES中加密单个字节的输出比16字节长一点,也不会令我感到惊讶。

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

© www.soinside.com 2019 - 2024. All rights reserved.