Last active
July 21, 2017 12:26
-
-
Save Magrath/12845343ea547a4fa8715aafa14dfe6b to your computer and use it in GitHub Desktop.
Retrieving, decrypting from and then re-encrypting to S3 using KMS client side decryption
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
package main | |
import ( | |
"bytes" | |
"fmt" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/client" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/kms" | |
"github.com/aws/aws-sdk-go/service/s3" | |
"github.com/aws/aws-sdk-go/service/s3/s3crypto" | |
"io/ioutil" | |
"log" | |
) | |
const bucket = "bucket" | |
const kmsKeyID = "1234" | |
func main() { | |
sess, err := session.NewSession(&aws.Config{Region: aws.String("us-east-1")}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
b := decrypt(sess, "testKey1") | |
fmt.Printf("%s", b) | |
encrypt(sess, "testKey2", b) | |
} | |
func decrypt(sess client.ConfigProvider, key string) []byte { | |
decryptionClient := s3crypto.NewDecryptionClient(sess) | |
req, out := decryptionClient.GetObjectRequest(&s3.GetObjectInput{ | |
Key: aws.String(key), | |
Bucket: aws.String(bucket), | |
}) | |
err := req.Send() | |
if err != nil { | |
log.Fatal(err) | |
} | |
b, err := ioutil.ReadAll(out.Body) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return b | |
} | |
func encrypt(sess client.ConfigProvider, key string, body []byte) { | |
handler := s3crypto.NewKMSKeyGenerator(kms.New(sess), kmsKeyID) | |
encryptionClient := s3crypto.NewEncryptionClient(sess, s3crypto.AESGCMContentCipherBuilder(handler)) | |
req, _ := encryptionClient.PutObjectRequest(&s3.PutObjectInput{ | |
Key: aws.String(key), | |
Bucket: aws.String(bucket), | |
Body: bytes.NewReader(body), | |
}) | |
err := req.Send() | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment