Created
July 17, 2017 12:30
-
-
Save RawToast/2b4c862f0c06211c18e18fa3d815192c to your computer and use it in GitHub Desktop.
KMS Encryption in Scala
This file contains hidden or 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 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Build.sbt contents: