Last active
April 18, 2023 16:48
-
-
Save arturotena/9235042 to your computer and use it in GitHub Desktop.
Cifrar y descifrar en Java (encriptar y desencriptar)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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; | |
} |
gracias, me resulto muy útil tu código, muy amable por compartir
obtieneCypher explicame esta parte como funciona
Muchas gracias mi buen :D
jeje buen codigo
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
De mucha utilidad