How to use the createHmac function from crypto
Find comprehensive JavaScript crypto.createHmac code examples handpicked from public code repositorys.
crypto.createHmac is a built-in Node.js module that allows you to create a Hash-based Message Authentication Code (HMAC) using a given algorithm and secret key.
GitHub: awesome-archive/enquirer
35 36 37 38 39 40 41 42 43 44
buffer[7 - i] = counter & 0xff; counter = counter >> 8; } // Step 1: Generate an HMAC-SHA-1 value const hmac = crypto.createHmac(this.hmacAlgorithm, Buffer.from(decodedSecret)); hmac.update(buffer); const hmacResult = hmac.digest(); // Step 2: Generate a 4-byte string (Dynamic Truncation)
GitHub: qiniu/nodejs-sdk
91 92 93 94 95 96 97 98 99 100
// Hmac-sha1 Crypt exports.hmacSha1 = function (encodedFlags, secretKey) { /* *return value already encoded with base64 * */ var hmac = crypto.createHmac('sha1', secretKey); hmac.update(encodedFlags); return hmac.digest('base64'); };
How does crypto.createHmac work?
crypto.createHmac is a built-in Node.js module that allows you to create a Hash-based Message Authentication Code (HMAC) using a given algorithm and secret key. An HMAC is a type of message authentication code that involves a cryptographic hash function and a secret key. HMACs are used to verify the integrity and authenticity of a message, and are commonly used in network security protocols such as SSL/TLS, IPsec, and SSH. To create an HMAC using crypto.createHmac, you start by creating a new instance of the Hmac class by calling crypto.createHmac(algorithm, key), where algorithm is the name of the hash function to use (e.g. 'sha256') and key is the secret key to use for the HMAC. You can then add data to the HMAC by calling the update method with a string or buffer representing the data to be hashed. Once you have added all the data to the HMAC, you can obtain the resulting HMAC by calling the digest method with an optional encoding parameter. For example, here's how you might use crypto.createHmac to create an HMAC using the SHA-256 hash function and a secret key: javascript Copy code {{{{{{{ const crypto = require('crypto'); const secretKey = 'mysecretkey'; const data = 'hello world'; const hmac = crypto.createHmac('sha256', secretKey); hmac.update(data); const signature = hmac.digest('hex'); console.log(signature); In this example, we define a secret key and some data to be hashed. We then create a new Hmac instance using the SHA-256 hash function and our secret key, and add our data to the HMAC using the update method. Finally, we obtain the resulting HMAC by calling the digest method with the 'hex' encoding parameter, which returns a hexadecimal string representing the HMAC. The resulting HMAC can then be used to verify the integrity and authenticity of the message by comparing it to a known or expected HMAC.
GitHub: Kode/Krom
22 23 24 25 26 27 28 29 30 31
```cjs const crypto = require('crypto'); const secret = 'abcdefg'; const hash = crypto.createHmac('sha256', secret) .update('I love cupcakes') .digest('hex'); console.log(hash); // Prints:
+ 15 other calls in file
141 142 143 144 145 146 147 148 149 150
```js // 以nodejs为例 const crypto = require('crypto') const secret = 'your-secret-string' // 自己的密钥不要直接使用示例值,且注意不要泄露 const hmac = crypto.createHmac('sha256', secret); // 自有服务 器生成签名,并以GET方式发送请求 const params = { accessToken: 'xxx', // 客户端传到自己服务器的参数
+ 3 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10
const crypto = require("crypto"); const message = "hello world"; const secretKey = "mysecretkey"; const hmac = crypto.createHmac("sha256", secretKey); hmac.update(message); const hash = hmac.digest("hex"); console.log(hash);
In this example, we create a new Hmac instance using the SHA-256 hash function and our secret key. We then add our message to the HMAC using the update method, and obtain the resulting hash by calling the digest method with the 'hex' encoding parameter, which returns a hexadecimal string representing the hash. The resulting hash can then be used to verify the integrity and authenticity of the message by comparing it to a known or expected hash.
GitHub: hokaccha/node-jwt-simple
175 176 177 178 179 180 181 182 183 184
} function sign(input, key, method, type) { var base64str; if(type === "hmac") { base64str = crypto.createHmac(method, key).update(input).digest('base64'); } else if(type == "sign") { base64str = crypto.createSign(method).update(input).sign(key, 'base64'); }
+ 7 other calls in file
GitHub: cshum/imagor
215 216 217 218 219 220 221 222 223 224
```javascript const crypto = require('crypto'); function sign(path, secret) { const hash = crypto.createHmac('sha1', secret) .update(path) .digest('base64') .replace(/\+/g, '-').replace(/\//g, '_') return hash + '/' + path
+ 3 other calls in file
GitHub: panva/paseto
90 91 92 93 94 95 96 97 98 99
if (!payload) throw new PasetoDecryptionFailed('decryption failed') return payload } const hmac = (data, key) => crypto.createHmac('sha384', key).update(data).digest() const ctr = async (op, data, key, iv) => subtle[op]( { name: 'AES-CTR', counter: iv, length: 16 },
GitHub: baddate/trilium
31 32 33 34 35 36 37 38 39
function fromBase64(encodedText) { return Buffer.from(encodedText, 'base64'); } function hmac(secret, value) { const hmac = crypto.createHmac('sha256', Buffer.from(secret.toString(), 'ASCII')); hmac.update(value.toString()); return hmac.digest('base64'); }
+ 13 other calls in file
GitHub: lpinca/shopify-token
145 146 147 148 149 150 151 152 153 154
Buffer.byteLength(query.hmac) !== 64 ) { return false; } const digest = crypto.createHmac('sha256', this.sharedSecret) .update(pairs.join('&')) .digest(); return timingSafeEqual(digest, Buffer.from(query.hmac, 'hex'));
GitHub: joeferner/redis-commander
18 19 20 21 22 23 24 25 26 27
function comparePasswords(a, b) { // make shure booth buffers have same length and make time comparision attacks to // guess pw length harder by calculation fixed length hmacs first let key = crypto.pseudoRandomBytes(32); let bufA = crypto.createHmac('sha256', key).update(a).digest(); let bufB = crypto.createHmac('sha256', key).update(b).digest(); let ret = true; if (crypto.timingSafeEqual) {
+ 3 other calls in file
33 34 35 36 37 38 39 40 41
return result === 0; } function validateSignature(body, channelSecret, signature) { return safeCompare( createHmac('SHA256', channelSecret).update(body).digest(), s2b(signature, 'base64') ); }
207 208 209 210 211 212 213 214 215 216
createSignedHmacBody(hmacKey, url, payload = null, { nonce = null, kid = null } = {}) { const result = this.prepareSignedBody('HS256', url, payload, { nonce, kid }); /* Signature */ const signer = createHmac('SHA256', Buffer.from(hmacKey, 'base64')).update(`${result.protected}.${result.payload}`, 'utf8'); result.signature = signer.digest().toString('base64url'); return result; }
+ 3 other calls in file
106 107 108 109 110 111 112 113 114 115
var that = this; this._api.command_chain.push({ 'control': /^j?dev\/sys\/keyexchange\//, 'callback': function(loxone_message) { var key = new Buffer(that._decipher(loxone_message.value), 'hex').toString('utf8'); var hmac = crypto.createHmac('sha1', key); var hmac_hash = hmac.update(that._username+':'+that._password).digest('hex'); that._hmac_hash = hmac_hash; var enc_data = that._cipher(that._hmac_hash+'/'+that._username, 'base64'); that._register_authenticateenc_response();
+ 3 other calls in file
38 39 40 41 42 43 44 45 46
var crypto = require('crypto'); var key = 'the shared secret key here'; var message = 'the message to hash here'; var hash = crypto.createHmac('sha256', key).update(message); // to lowercase hexits hash.digest('hex');
GitHub: r2c-CSE/bad-js-app
37 38 39 40 41 42 43 44 45 46
from: (req: Request) => ResponseWithUser | undefined updateFrom: (req: Request, user: ResponseWithUser) => any } exports.hash = (data: string) => crypto.createHash('md5').update(data).digest('hex') exports.hmac = (data: string) => crypto.createHmac('sha256', 'pa4qacea4VK9t9nGv7yZtwmj').update(data).digest('hex') exports.cutOffPoisonNullByte = (str: string) => { const nullByte = '%00' if (utils.contains(str, nullByte)) {
+ 19 other calls in file
GitHub: ulivz/utility
73 74 75 76 77 78 79 80 81
* @param {String} [encoding='base64'] * @return {String} digest string. */ exports.hmac = function hmac(algorithm, key, data, encoding) { encoding = encoding || 'base64'; var hmac = crypto.createHmac(algorithm, key); hmac.update(data, Buffer.isBuffer(data) ? 'binary' : 'utf8'); return hmac.digest(encoding); };
GitHub: Countly/countly-server
151 152 153 154 155 156 157 158 159 160
* @param {boolean} addSalt - should salt be added * @returns {string} hashed string **/ function sha512Hash(str, addSalt) { var salt = (addSalt) ? new Date().getTime() : ""; return crypto.createHmac('sha512', salt + "").update(str + "").digest('hex'); } /** * Verify member for Argon2 Hash
+ 3 other calls in file
GitHub: alibaba/f2etest
113 114 115 116 117 118 119 120 121 122
}; function getBucInfo(username, callback){ var now = new Date(); var Timestamp = now.toISOString(); var hmac = crypto.createHmac('sha256', '_C6_&jQj_42d(E&@KS80n(&vd_KEYY2hQ@W0v&(x'); var nonce = now.getTime()+Math.floor(Math.random()*10000);; var Signature = hmac.update('POST\n'+Timestamp+'\n'+nonce+'\n/rpc/enhancedUserQuery/getUserByLoginName.json\nloginName='+username).digest('base64'); request({
6 7 8 9 10 11 12 13 14 15
if (!payload) { return next('Request body empty') } const sig = req.get(sigHeaderName) || '' const hmac = crypto.createHmac('sha1', secret) const digest = Buffer.from('sha1=' + hmac.update(payload).digest('hex'), 'utf8') const checksum = Buffer.from(sig, 'utf8') if (checksum.length !== digest.length || !crypto.timingSafeEqual(digest, checksum)) { return next(`Request body digest (${digest}) did not match ${sigHeaderName} (${checksum})`)
crypto.createHash is the most popular function in crypto (882 examples)