Estou iniciando em criptografia e fazendo alguns testes para compreender melhor como funcionam as classes, algoritmos e etc… e gostaria de um auxilio pois estou criptografando a msg mas a criptografia está me dando saida com hex aleatórios e gostaria de saber como faço para que a criptografia saia com as mesma informações quando executada.
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AES {
public static String toHex(byte[]bytes){
String hex = "0123456789abcdef";
StringBuffer sb = new StringBuffer();
if(bytes ==null)
System.out.println("Bytes Nulos");
for (int i = 0; i < bytes.length; i++) {
int j = bytes[i] & 0xff;
sb.append(hex.charAt(j / 16));
sb.append(hex.charAt(j % 16));
}
return sb.toString();
}
public static void main(String[] args) {
String msg = "Example";
//Pegando o KeyGenerator
try{
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
//Gerando uma chave secreta
SecretKey secretKey= keygen.generateKey();
byte[]key = secretKey.getEncoded();
SecretKeySpec sks = new SecretKeySpec(key, "AES");
//Inicializando cipher para criptografar os dados.
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
byte[]encrypt = cipher.doFinal(msg.getBytes());
System.out.println("Encoded: " + toHex(encrypt));
cipher.init(Cipher.DECRYPT_MODE, sks);
byte[]original = cipher.doFinal(encrypt);
System.out.println("Decoded: " + new String(original));
}catch(Exception e){
System.out.println("Erro: " + e.getMessage());
e.printStackTrace();
}
}
}
Vlw