Created
July 21, 2022 10:30
-
-
Save neogeogre/8ea2d8bab234ddc8fe3affcdd7c0b4c7 to your computer and use it in GitHub Desktop.
simplest way to have cipher encryption in Kotlin
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
import java.util.* | |
import javax.crypto.Cipher.* | |
import javax.crypto.spec.IvParameterSpec | |
import javax.crypto.spec.SecretKeySpec | |
fun main() { | |
val str = "Hello World !" | |
val encryptionKey = "1mfNnQ8CSdxHOhwO" | |
println(str) | |
val encoded = encrypt(str, encryptionKey) | |
println(encoded) | |
val decoded = decrypt(encoded, encryptionKey) | |
println(decoded) | |
} | |
const val ALGO = "AES" | |
const val TRANSFORMATION = "AES/CBC/PKCS5Padding" | |
fun encrypt(input: String, encryptionKey: String): String { | |
val secretKeySpec = SecretKeySpec(encryptionKey.toByteArray(), ALGO) | |
val ivParameterSpec = IvParameterSpec(encryptionKey.toByteArray()) | |
val cipher = getInstance(TRANSFORMATION)!! | |
cipher.init(ENCRYPT_MODE, secretKeySpec, ivParameterSpec) | |
return Base64.getEncoder().encodeToString(cipher.doFinal(input.toByteArray())) | |
} | |
fun decrypt(input: String, encryptionKey: String): String { | |
val secretKeySpec = SecretKeySpec(encryptionKey.toByteArray(), ALGO) | |
val ivParameterSpec = IvParameterSpec(encryptionKey.toByteArray()) | |
val cipher = getInstance(TRANSFORMATION)!! | |
cipher.init(DECRYPT_MODE, secretKeySpec, ivParameterSpec) | |
val decodedValue = Base64.getDecoder().decode(input)!! | |
return String(cipher.doFinal(decodedValue)!!) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment