Created
September 20, 2018 09:13
-
-
Save manujrastogi/5d737e756624778349f39bbc755830ec to your computer and use it in GitHub Desktop.
A sample in nodejs for google cloud Asymmetric Signature creation and verification using crypto , googleapis. Algorithm - 3072 bit RSA key PSS Padding - SHA256 Digest
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
var google = require('googleapis'); | |
function buildAndAuthorizeService (callback) { | |
// Acquires credentials | |
google.google.auth.getApplicationDefault((err, authClient) => { | |
if (err) { | |
callback(err); | |
return; | |
} | |
if (authClient.createScopedRequired && authClient.createScopedRequired()) { | |
authClient = authClient.createScoped([ | |
'https://www.googleapis.com/auth/cloud-platform' | |
]); | |
} | |
// Instantiates an authorized client | |
const cloudkms = new google.cloudkms_v1.Cloudkms({ | |
version: 'v1', | |
auth: authClient | |
}); | |
callback(null, cloudkms); | |
}); | |
} | |
/* | |
Digest Data | |
*/ | |
var data_to_hash = 'your data here'; | |
var hash = crypto.createHash('sha256'); | |
var digest_data = hash.update(data_to_hash, 'utf8').digest('base64'); | |
// returns digest of the data | |
var parent = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}/cryptoKeyVersions/{}' | |
var digest_JSON = { digest: { sha256: digest_data }} | |
/* | |
Asymmetric Sign | |
*/ | |
buildAndAuthorizeService((err, cloudkms) => { | |
// get signature for data | |
cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.asymmetricSign({ | |
name:parent, | |
resource:digest_JSON | |
}) | |
.then(result => {console.log(result['data']['signature']); | |
}) | |
.catch(err => {console.log(err); | |
}); | |
}); | |
/* | |
Asymmetric Get Public Key | |
*/ | |
buildAndAuthorizeService((err, cloudkms) => { | |
cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.getPublicKey({ | |
name:parent | |
}) | |
.then(result => {console.log(result['data']['pem']); | |
}) | |
.catch(err => {console.log(err); | |
}); | |
}); | |
/* | |
Asymmetric Verification | |
*/ | |
var crypto = require('crypto'); | |
var verfiy = crypto.createVerify('SHA256'); | |
verify.update(data_to_hash); | |
verify.verify({key : pem, padding : crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: 32 }, signature, 'base64'); | |
// returns true or flase | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment