Duda con algoritmo estándar avanzado (AES).
Hola a todos tengo una duda estoy desencriptando una cadena dada es el resultado de la codificación en base64 tengo el siguiente codigo
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import static org.apache.commons.codec.binary.Base64.decodeBase64;
import static org.apache.commons.codec.binary.Base64.encodeBase64;
public class AES {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 128);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception
{
final String secretKey = "passsupersegu";
String correo0 = "7TJRTBTlvEg0dfdse/snFOfmzhjd4xJbrLgo=";
String decryptedString0 = AES.decrypt(correo0, secretKey) ;
System.out.println(decryptedString0);
}
}
<blockcode>
pero me sale el siguiente error
Error while decrypting: java.security.InvalidKeyException: Invalid AES key length: 128 bytes
Alguna idea es la primera vez que hago esto
- Inicie sesión o regístrese para enviar comentarios
Puedes cambiar tu método
Puedes cambiar tu método setKey por este:
MessageDigest sha = null;
try {
if(null == secretKey)
{
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Tamaño de llave
El tamaño de llave de AES es 128 bits, no 128 bytes.
16
Por eso la linea debe quedar así:
1 Byte = 8 Bits
128/8=16
Saludos!