Skip to content

Instantly share code, notes, and snippets.

@RawToast
Created July 17, 2017 12:30
Embed
What would you like to do?
KMS Encryption in Scala
import java.nio.ByteBuffer
import com.amazonaws.regions.Regions
import com.amazonaws.services.kms.AWSKMS
import com.amazonaws.services.kms.AWSKMSClientBuilder
import com.amazonaws.services.kms.model.{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(_.getBytes("UTF-8"))
.map(ByteBuffer.wrap)
.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 = decryptedMessage.map((s: ByteBuffer) => new String(s.array, "UTF-8"))
.map(str => s"Encryption cycle complete! Decrypted value: $str")
.getOrElse("Encryption failed: nothing to encrypt")
println(results)
results
}
def buildEncRequest(byteBuffer: ByteBuffer): EncryptRequest = new EncryptRequest().withKeyId(keyArn).withPlaintext(byteBuffer)
def buildDecRequest(byteBuffer: ByteBuffer): DecryptRequest = new DecryptRequest().withCiphertextBlob(byteBuffer)
encrypt(args.headOption)
}
@RawToast
Copy link
Author

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