Created
August 9, 2020 13:31
-
-
Save eendroroy/6bc3e1e1a706c87307b26ec5ccfddd72 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* @author indrajit | |
*/ | |
class AesCryptoUtil(secret: String) { | |
private val secretKey: SecretKeySpec | |
init { | |
var key: ByteArray = secret.toByteArray(StandardCharsets.UTF_8) | |
val sha = MessageDigest.getInstance("SHA-1") | |
key = sha.digest(key) | |
key = key.copyOf(16) | |
secretKey = SecretKeySpec(key, "AES") | |
} | |
fun encrypt(strToEncrypt: String): String { | |
val cipher = Cipher.getInstance(AES_TRANSFORMATION) | |
cipher.init(Cipher.ENCRYPT_MODE, secretKey) | |
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.toByteArray(StandardCharsets.UTF_8))) | |
} | |
fun decrypt(strToDecrypt: String): String { | |
val cipher = Cipher.getInstance(AES_TRANSFORMATION) | |
cipher.init(Cipher.DECRYPT_MODE, secretKey) | |
return String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))) | |
} | |
companion object { | |
private const val AES_TRANSFORMATION = "AES/ECB/PKCS5Padding" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment