Skip to content

Instantly share code, notes, and snippets.

Created July 17, 2017 12:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
KMS Encryption in Scala
import java.nio.ByteBuffer
import com.amazonaws.regions.Regions
import{DecryptRequest, EncryptRequest}
object Encrypty extends App {
val kms: AWSKMS = AWSKMSClientBuilder.standard.withRegion(Regions.EU_WEST_2).build()
val keyArn = "arn:aws:kms:eu-west-???"
def encrypt(valueToEncrypt: Option[String]): String = {
println(s"Value to encrypt: ${valueToEncrypt.getOrElse("")}")
val encryptionMessage = valueToEncrypt
.map(bb => buildEncRequest(bb))
.map(req => kms.encrypt(req))
val decryptedMessage: Option[ByteBuffer] = for {
encryptResult <- encryptionMessage
resultText = encryptResult.getCiphertextBlob
_ = println(s"Encrypted value: ${new String(resultText.array, "UTF-8")})")
decryptRequest = buildDecRequest(resultText)
decryptResult = kms.decrypt(decryptRequest)
decryptText = decryptResult.getPlaintext
} yield decryptText
val results = ByteBuffer) => new String(s.array, "UTF-8"))
.map(str => s"Encryption cycle complete! Decrypted value: $str")
.getOrElse("Encryption failed: nothing to encrypt")
def buildEncRequest(byteBuffer: ByteBuffer): EncryptRequest = new EncryptRequest().withKeyId(keyArn).withPlaintext(byteBuffer)
def buildDecRequest(byteBuffer: ByteBuffer): DecryptRequest = new DecryptRequest().withCiphertextBlob(byteBuffer)
Copy link

Build.sbt contents:

version := "1.0"

scalaVersion := "2.12.1"

val awsSdkVersion = "1.11.163"
mainClass := Some("Encrypty")

libraryDependencies += "com.amazonaws" % "aws-java-sdk-kms" % awsSdkVersion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment