Skip to content

Instantly share code, notes, and snippets.

@jadlr
Created June 26, 2020 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jadlr/68c919f2c645184b4fdec2873920b90e to your computer and use it in GitHub Desktop.
Save jadlr/68c919f2c645184b4fdec2873920b90e to your computer and use it in GitHub Desktop.
Using AES256GCM to encrypt and decrypt a text
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