problema con encriptacion aes
Hola que tal, estoy tratando de encriptar una cadena, utilize como ejemplo el codigo que viene en la documentacion, pero no esta funcionando bien, ojala puedan ayudarme a resolver el problema, gracias
Codigo fuente:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
/**
* This program generates a AES key, retrieves its raw bytes, and
* then reinstantiates a AES key from the key bytes.
* The reinstantiated key is used to initialize a AES cipher for
* encryption and decryption.
*/
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(128); // 192 and 256 bits may not be available
// 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((args.length == 0 ?
"This is just an example" : args[0]).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));
}
}
En output me muestra esto
run:
encrypted string: cbb29b6d58852b61e7814fc429e3954e9edf4aebaf01c0937d5ee0659cf8393b
Original string: This is just an example 54686973206973206a75737420616e206578616d706c65
BUILD SUCCESSFUL (total time: 1 second)
- Inicie sesión o regístrese para enviar comentarios
hex
Y qué es lo que no te funciona según tú? Porque la cadena hexadecimal 54686973206973206a75737420616e206578616d706c65 si la conviertes a ASCII, los primeros caracteres por ejemplo 54686973 son T, h, i, s.
Si lo que quieres ver es la cadena original impresa, imprime originalString, no asHex(original).
Y luego que digas "ah que chido! sí funciona!" te pones a leer acerca de criptografía y lees algo de las cifras simétricas por bloques, como AES, para que sepas cómo funcionan y pienses cómo vas a manejar las llaves, qué es lo que vas a cifrar, si realmente es lo que necesitas, etc.
gracias
muchas gracias ezamudio, no me habia fijado en ese detalle, crei que asHex lo convertia a cadena, peor bueno, ya que veo que funcona checare lo que mencionas sobre los bloques y las llaves, muchas gracias