Created
December 12, 2021 14:52
-
-
Save abircse/93fb4337465fd38eba954d3c91e9ff82 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
object PasswordEncryptor { | |
private const val SECRET_KEY = "aesEncryptionKey" | |
private const val INIT_VECTOR = "encryptionIntVec" | |
fun encrypt(value: String): String? { | |
try { | |
val iv = IvParameterSpec(INIT_VECTOR.toByteArray(charset("UTF-8"))) | |
val skeySpec = SecretKeySpec(SECRET_KEY.toByteArray(charset("UTF-8")), "AES") | |
val cipher: Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING") | |
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv) | |
val encrypted: ByteArray = cipher.doFinal(value.toByteArray()) | |
return Base64.encodeToString(encrypted, Base64.DEFAULT) | |
} catch (ex: Exception) { | |
ex.printStackTrace() | |
} | |
return null | |
} | |
fun decrypt(value: String?): String? { | |
try { | |
val iv = IvParameterSpec(INIT_VECTOR.toByteArray(charset("UTF-8"))) | |
val skeySpec = SecretKeySpec(SECRET_KEY.toByteArray(charset("UTF-8")), "AES") | |
val cipher: Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING") | |
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv) | |
val original: ByteArray = cipher.doFinal(Base64.decode(value, Base64.DEFAULT)) | |
return String(original) | |
} catch (ex: Exception) { | |
ex.printStackTrace() | |
} | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment