【发布时间】:2020-04-14 10:42:19
【问题描述】:
我正在尝试创建一个简单的类来显示要编码的消息、编码的消息和解码的消息。但我认为我的课是错误的。以下是我对函数的解释:
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。
【问题讨论】:
-
您不仅要对其进行编码,还要对其进行加密,然后对其进行 base64 编码。为什么您认为加密和编码的消息应该与源具有相同的长度?即使只有base64编码,没有加密,也会产生至少3个字符,通常是increase of 33% compared to the source
-
似乎在我的头脑中编码等于加密。我很惭愧...感谢指针:)
标签: java encoding base64 decoding