Boa noite pessoal,
Estou estudando criptografia AES-256 bits utilizando Java. Estou utilizando o seguinte source do site da Oracle.
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AES {
/**
* Turns array of bytes into string
*
* @param buf Array of bytes to convert to hex string
* @return Generated hex string
*/
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static void main(String[] args) throws Exception {
String message="This is just an example";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256);
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(message.getBytes());
System.out.println("encrypted string: " + asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " + originalString + " " + asHex(original));
}
}
No caso, a mensagem que seria criptografada é: "This is just an example"(1) (23 caracteres = 23 bytes)
Como estou mandando criptografar em 256 bits, teríamos que utilizar blocos de 256/8 = 32 bytes. Neste caso estaria “faltando” 9 bytes. A única vez que a mensagem original da criptografia é chamada é em:
byte[] encrypted = cipher.doFinal(message.getBytes());
Li em um site que para preencher os 9 bytes coloca-se espaços em branco no final da mensagem original, no nosso caso: “This is just an example + <9 espaços em branco>” (2)
Seria do modo (2) a mensagem original é tratada pelo método doFinal, ou seja, o método faz o tratamento dos blocos adicionando os espaços quando é necessário? Alguém poderia me esclarecer ou me dar algumas opiniões? Desde já agradeço!