Skip to content

Instantly share code, notes, and snippets.

@arturotena
Last active April 18, 2023 16:48
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save arturotena/9235042 to your computer and use it in GitHub Desktop.
Save arturotena/9235042 to your computer and use it in GitHub Desktop.
Cifrar y descifrar en Java (encriptar y desencriptar)
/*
* Código fácil para cifrar y descifrar en Java ("encriptar" y "desencriptar").
* No ha sido auditado, ni garantizo su seguridad.
*/
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public byte[] cifra(String sinCifrar) throws Exception {
final byte[] bytes = sinCifrar.getBytes("UTF-8");
final Cipher aes = obtieneCipher(true);
final byte[] cifrado = aes.doFinal(bytes);
return cifrado;
}
public String descifra(byte[] cifrado) throws Exception {
final Cipher aes = obtieneCipher(false);
final byte[] bytes = aes.doFinal(cifrado);
final String sinCifrar = new String(bytes, "UTF-8");
return sinCifrar;
}
private Cipher obtieneCipher(boolean paraCifrar) throws Exception {
final String frase = "FraseLargaConDiferentesLetrasNumerosYCaracteresEspeciales_áÁéÉíÍóÓúÚüÜñÑ1234567890!#%$&()=%_NO_USAR_ESTA_FRASE!_";
final MessageDigest digest = MessageDigest.getInstance("SHA");
digest.update(frase.getBytes("UTF-8"));
final SecretKeySpec key = new SecretKeySpec(digest.digest(), 0, 16, "AES");
final Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
if (paraCifrar) {
aes.init(Cipher.ENCRYPT_MODE, key);
} else {
aes.init(Cipher.DECRYPT_MODE, key);
}
return aes;
}
@rclaros
Copy link

rclaros commented Aug 31, 2017

De mucha utilidad

@seanjamu
Copy link

gracias, me resulto muy útil tu código, muy amable por compartir

@codenine69
Copy link

obtieneCypher explicame esta parte como funciona

@gabrilr
Copy link

gabrilr commented Oct 30, 2019

Muchas gracias mi buen :D

@Guzmaneador
Copy link

jeje buen codigo

@jegaguado
Copy link

Hola, al usar el código obtengo este mensaje al desencriptar:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

¿Sabes qué puede ser?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment