Skip to content

Instantly share code, notes, and snippets.

@ryu1kn
Created March 29, 2020 09:21
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 ryu1kn/50fffb484fdb9055e2ffcc0bb235c084 to your computer and use it in GitHub Desktop.
Save ryu1kn/50fffb484fdb9055e2ffcc0bb235c084 to your computer and use it in GitHub Desktop.
GCP KMS node.js client (googleapis and @google-cloud/kms) usage
const locationId = "KMS key's region ID"
const projectId = "KMS key's project ID"
const keyRring = "KMS key's key ring"
const keyId = "KMS key's ID"
const encryptedText = 'CiQAfn8U68PD1weop5nXO43I8srZ2pMLaxXci2tcaDnfwLt2YOUSMwDNtppaQLU82bYtoRXx/NCnLnUt05WtHl8Y2QKUNCq6QS9FJdoxCszzjsnpym7SktWn+g==';
async function useGoogleapisModule() {
console.log('Use `googleapis` module to decrypt KMS encrypted secret')
const {google} = require('googleapis')
const auth = new google.auth.GoogleAuth({scopes: ['https://www.googleapis.com/auth/cloudkms']})
const cloudkms = google.cloudkms({version: 'v1', auth: await auth.getClient()})
const result = await cloudkms.projects.locations.keyRings.cryptoKeys.decrypt({
name: `projects/${projectId}/locations/${locationId}/keyRings/${keyRring}/cryptoKeys/${keyId}`,
requestBody: {ciphertext: encryptedText}
})
console.log(decodeBase64(result.data.plaintext))
}
async function useGoogleCloudKmsModule() {
console.log('Use `@google-cloud/kms` module to decrypt KMS encrypted secret')
const kms = require('@google-cloud/kms')
const kmsClient = new kms.KeyManagementServiceClient()
const keyPath = kmsClient.cryptoKeyPath(projectId, locationId, keyRring, keyId)
const [result] = await kmsClient.decrypt({name: keyPath, ciphertext: encryptedText})
console.log(decodeBase64(result.plaintext))
}
function decodeBase64(base64String) {
return Buffer.from(base64String, 'base64').toString('utf8')
}
useGoogleapisModule().catch(e => console.error(e.stack))
useGoogleCloudKmsModule().catch(e => console.error(e.stack))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment