Skip to content

Instantly share code, notes, and snippets.

@jdelibas
Last active June 7, 2017 09:24
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 jdelibas/872438dfba550b47c0b31dde82bbbe63 to your computer and use it in GitHub Desktop.
Save jdelibas/872438dfba550b47c0b31dde82bbbe63 to your computer and use it in GitHub Desktop.
AWS KMS and S3 secret storage

AWS KMS and S3 secret storage

Usage

const Secrets = require('./Secrets')
const secrets = new Secrets({
  accessKeyId: 'some aws access key id',
  secretAccessKey: 'some aws secret access key'
})

const bucket = 'some-s3-bucket'
const filename = 'some.secrets'
const keyid = 'some kms key id'

async function demo () {
  try {
    // Load secrets from s3 and decrypt them
    // returns object
    let decrypted = await this.aws.getSecrets({
      bucket,
      filename
    })
    console.log(decrypted)
    
    // Edit the object
    decrypted['newkey'] = 'new data'
    
    // Save the new object (encrypt and store in s3)
    return await this.aws.saveSecrets({
      bucket,
      filename,
      keyid,
      data: decrypted
    })
  } catch (e) {
    throw (e)
  }
}

demo()
  .then(res => console.log(res))
  .catch(err => console.log(err))
/* global TextDecoder */
const AWSSDK = require('aws-sdk')
AWSSDK.config.setPromisesDependency(Promise)
export default class Secrets{
constructor (config) {
AWSSDK.config = config
this.s3 = new AWSSDK.S3()
this.kms = new AWSSDK.KMS()
}
async getSecrets ({ bucket, filename }) {
try {
const s3Params = {
Bucket: bucket,
Key: filename
}
const res = await this.s3.getObject(s3Params).promise()
const kmsParams = {
CiphertextBlob: res.Body
}
const decrypted = await this.kms.decrypt(kmsParams).promise()
// decode uint8 array
const decoded = new TextDecoder('utf-8').decode(decrypted.Plaintext)
return JSON.parse(decoded)
} catch (e) {
throw e
}
}
async saveSecrets ({ bucket, filename, keyid, data }) {
try {
const kmsParams = {
KeyId: keyid,
Plaintext: JSON.stringify(data)
}
const encrypted = await this.kms.encrypt(kmsParams).promise()
const s3Params = {
Bucket: bucket,
Key: filename,
Body: encrypted.CiphertextBlob
}
return await this.s3.putObject(s3Params).promise()
} catch (e) {
throw e
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment