Created
June 26, 2020 13:51
-
-
Save jadlr/68c919f2c645184b4fdec2873920b90e to your computer and use it in GitHub Desktop.
Using AES256GCM to encrypt and decrypt a text
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 cats.effect.{ ExitCode, IO, IOApp } | |
import tsec.cipher.symmetric.{ AAD, AADEncryptor, IvGen } | |
import tsec.cipher.symmetric.jca.{ AES256GCM, SecretKey } | |
import tsec.common._ | |
import tsec.cipher.symmetric._ | |
object CryptoApp extends IOApp { | |
private val aad: AAD = AAD("KnQCxy4rW4KuxMRcvkVvAs9KufF7XR4b".utf8Bytes) | |
private implicit val ctrStrategy: IvGen[IO, AES256GCM] = AES256GCM.defaultIvStrategy[IO] | |
private implicit val cachedInstance: AADEncryptor[IO, AES256GCM, SecretKey] = AES256GCM.genEncryptor[IO] | |
override def run(args: List[String]): IO[ExitCode] = | |
for { | |
secretKey <- AES256GCM.generateKey[IO] | |
encrypted <- AES256GCM.encryptWithAAD[IO](PlainText("I'm a secret".utf8Bytes), secretKey, aad) | |
base64 = encrypted.toConcatenated.toB64String | |
_ <- IO.delay(println(base64)) | |
bytes <- IO.fromOption(base64.b64Bytes)(new Exception("Could not decode base64")) | |
cipherText <- IO.fromEither(AES256GCM.ciphertextFromConcat(bytes)) | |
decrypted <- AES256GCM.decryptWithAAD(cipherText, secretKey, aad) | |
_ <- IO.delay(println(decrypted.toUtf8String)) | |
} yield ExitCode.Success | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment