Skip to content

Instantly share code, notes, and snippets.

@oscarito9410
Created June 16, 2019 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oscarito9410/54ef979fb0f68ab37adba392c25e8637 to your computer and use it in GitHub Desktop.
Save oscarito9410/54ef979fb0f68ab37adba392c25e8637 to your computer and use it in GitHub Desktop.
package com.naat.codinaat.utils
import android.util.Base64
import android.util.Log
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
object Aes128 {
// Definición del tipo de algoritmo a utilizar (AES, DES, RSA)
private val alg = "AES"
// Definición del modo de cifrado a utilizar
private val cI = "AES/CBC/PKCS5Padding"
/**
* Función de tipo String que recibe una llave (key), un vector de inicialización (iv)
* y el texto que se desea cifrar
*
* @param key la llave en tipo String a utilizar
* @param iv el vector de inicialización a utilizar
* @param cleartext el texto sin cifrar a encriptar
* @return el texto cifrado en modo String♠
* @throws Exception puede devolver excepciones de los siguientes tipos: NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException
*/
@Throws(Exception::class)
fun encrypt(key: ByteArray, iv: ByteArray, cleartext: String): String {
val cipher: Cipher = Cipher.getInstance(cI)
val skeySpec = SecretKeySpec(key, alg)
val ivParameterSpec = IvParameterSpec(iv)
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec)
val encrypted = cipher.doFinal(cleartext.toByteArray())
return String(encodeBase64(encrypted))
}
/**
* Función de tipo String que recibe una llave (key), un vector de inicialización (iv)
* y el texto que se desea descifrar
*
* @param key la llave en tipo String a utilizar
* @param iv el vector de inicialización a utilizar
* @param encrypted el texto cifrado en modo String
* @return el texto desencriptado en modo String
* @throws Exception puede devolver excepciones de los siguientes tipos: NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException
*/
@Throws(Exception::class)
fun decrypt(key: ByteArray, iv: ByteArray, encrypted: String): String {
val skeySpec = SecretKeySpec(key, alg)
val ivParameterSpec = IvParameterSpec(iv)
val cipher = Cipher.getInstance(cI)
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec)
val enc = decodeBase64(encrypted)//encrypted.getBytes();
//Notas
// Usando encrypted.getBytes() se genera cadena de 32 bytes, decir,
// como estamos usando 16 bytes de Llave y 16 Bytes de Vector de inicializacion
// cadena a 32 bytes envia error: javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
// Aunque este error indica que esta mal la llave para desencriptar.
//
//Usando decodeBase64(encrypted); se genera cadena de 24 bytes
//Lo cual parece estar mal para este tipo de desencripcion porque envia el error javax.crypto.IllegalBlockSizeException: error:1e00007b:Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_LENGTH
val decrypted = cipher.doFinal(enc)
return String(decrypted)
}
// decode data from base 64
private fun decodeBase64(dataToDecode: String): ByteArray {
return Base64.decode(dataToDecode, Base64.DEFAULT)
}
//enconde data in base 64
private fun encodeBase64(dataToEncode: ByteArray): ByteArray {
return Base64.encode(dataToEncode, Base64.DEFAULT)
}
fun getKeyAES(strKeySrc: String): ByteArray {
return hexStringToByteArray(strKeySrc.take(64).take(32))
}
fun getIvAES(strKeySrc: String): ByteArray {
return hexStringToByteArray(strKeySrc.take(64).takeLast(32))
}
fun getKeyHmac(strKeySrc: String): ByteArray {
return hexStringToByteArray(strKeySrc.substring(64, 128))
}
fun hexStringToByteArray(s: String): ByteArray {
val len = s.length
val data = ByteArray(len / 2)
var i = 0
while (i < len) {
data[i / 2] = ((Character.digit(s[i], 16) shl 4) + Character.digit(s[i + 1], 16)).toByte()
i += 2
}
return data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment