简体   繁体   中英

Possible error of the encoding of a message

I'm trying to make a simple class which display the message to be coded, the encoded message and the decoded message. But I think that my class is wrong. Here is what I did with the explenation of the function:

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) {
}

}

And I have at the output:

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

I think that my class is false because the message to be coded is composed of only one letter but the encoded message is composed of 26 letters? Shouldn't it be composed of also one letter. So I would like if what I got is normal please.

I thanks in advances for anyone who takes time to help me.

PS: I use JDK 12 with NetBeans 11.

What you see is what you should expect.

AES is a block cipher: it encrypts data in blocks of 16 bytes. If the input data is not an even multiple of 16 bytes, it's padded. I would expect the original length of the data to be included somehow so it wouldn't surprise me if the output from encrypting a single byte in AES was a little longer than 16 bytes.

Base64 outputs 4 bytes for every block of 3 bytes in the input. In 16 input bytes there are 6 such blocks, so the encrypted message becomes at least 24 bytes in base64.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM