Skip to content

Instantly share code, notes, and snippets.

@paigeshin
Created April 10, 2023 10:13
Show Gist options
  • Save paigeshin/dc91ea9c06b09a6bf4399ecde99f2d38 to your computer and use it in GitHub Desktop.
Save paigeshin/dc91ea9c06b09a6bf4399ecde99f2d38 to your computer and use it in GitHub Desktop.
Copy code
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
fun encrypt(plainText: String, key: SecretKey): Pair<ByteArray, ByteArray> {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
val iv = ByteArray(16)
val random = SecureRandom()
random.nextBytes(iv)
cipher.init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(iv))
val encrypted = cipher.doFinal(plainText.toByteArray(Charsets.UTF_8))
return Pair(iv, encrypted)
}
fun decrypt(iv: ByteArray, encrypted: ByteArray, key: SecretKey): String {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
val decrypted = cipher.doFinal(encrypted)
return String(decrypted, Charsets.UTF_8)
}
fun main() {
val keyGenerator = KeyGenerator.getInstance("AES")
keyGenerator.init(256)
val key = keyGenerator.generateKey()
val plainText = "Hello, World!"
val (iv, encrypted) = encrypt(plainText, key)
val decrypted = decrypt(iv, encrypted, key)
println("Original message: $plainText")
println("Encrypted message: ${String(encrypted, Charsets.UTF_8)}")
println("Decrypted message: $decrypted")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment