當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript crypto.createHmac函數代碼示例

本文整理匯總了TypeScript中crypto.createHmac函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript createHmac函數的具體用法?TypeScript createHmac怎麽用?TypeScript createHmac使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了createHmac函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: reject

            worker.request = new Promise<PhantomResult>((resolve, reject) => {
                const hmac = crypto.createHmac("sha256", worker.key)
                    .update([worker.counter, 'POST', '/', `localhost:${worker.port}`, 'application/json', payload].join('\n'))
                    .digest('hex');

                http.request({
                    port:    worker.port,
                    method:  'POST',
                    auth:    worker.counter + ':' + hmac,
                    headers: {
                        'Content-Type':   'application/json',
                        'Content-Length': payload.length,
                    },
                }, (response) => {
                    let result = '';

                    response.on('error', (error) => {
                        reject(error);
                    });

                    response.on('data', (data) => {
                        result += data;
                    });

                    response.on('end', () => {
                        resolve([response, result]);
                    });
                })
                .on('error', (error) => {
                    reject(error);
                })
                .end(payload);
            });
開發者ID:LeviticusMB,項目名稱:ghostly,代碼行數:33,代碼來源:ghostly.ts

示例2: Error

  return Promise.resolve().then(() => {
    // must be bip39 mnemonic
    if (!bip39.validateMnemonic(phrase)) {
      throw new Error('Not a valid bip39 nmemonic')
    }

    // normalize plaintext to fixed length byte string
    const plaintextNormalized = Buffer.from(
      bip39.mnemonicToEntropy(phrase), 'hex'
    )

    // AES-128-CBC with SHA256 HMAC
    const salt = crypto.randomBytes(16)
    const keysAndIV = crypto.pbkdf2Sync(password, salt, 100000, 48, 'sha512')
    const encKey = keysAndIV.slice(0, 16)
    const macKey = keysAndIV.slice(16, 32)
    const iv = keysAndIV.slice(32, 48)

    const cipher = crypto.createCipheriv('aes-128-cbc', encKey, iv)
    let cipherText = cipher.update(plaintextNormalized).toString('hex')
    cipherText += cipher.final().toString('hex')

    const hmacPayload = Buffer.concat([salt, Buffer.from(cipherText, 'hex')])

    const hmac = crypto.createHmac('sha256', macKey)
    hmac.write(hmacPayload)
    const hmacDigest = hmac.digest()

    const payload = Buffer.concat([salt, hmacDigest, Buffer.from(cipherText, 'hex')])
    return payload
  })
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:31,代碼來源:wallet.ts

示例3: function

 prototype.request = function(method, uriParts, opts, callback) {
     var self = this;
     opts = opts || {};
     method = method.toUpperCase();
     if (!callback && (opts instanceof Function)) {
         callback = opts;
         opts = {};
     }
     var relativeURI = self.makeRelativeURI(uriParts);
     _.assign(opts, {
         'method': method,
         'uri': self.makeAbsoluteURI(relativeURI),
     });
     if (opts.body && (typeof opts.body !== 'string')) {
         opts.body = JSON.stringify(opts.body);
     }
     opts.agent = keepaliveAgent;
     var timestamp = Date.now() / 1000;
     var what = timestamp + method + relativeURI + (opts.body || '');
     var key = new Buffer(self.b64secret, 'base64');
     var hmac = crypto.createHmac('sha256', key);
     var signature = hmac.update(what).digest('base64');
     self.addHeaders(opts, {
         'CB-ACCESS-KEY': self.key,
         'CB-ACCESS-SIGN': signature,
         'CB-ACCESS-TIMESTAMP': timestamp,
         'CB-ACCESS-PASSPHRASE': self.passphrase,
     });
     request(opts, self.makeRequestCallback(callback));
 };
開發者ID:Camille92,項目名稱:tribeca,代碼行數:30,代碼來源:coinbase-api.ts

示例4: TypeError

export function unsignSync<T extends UnknownRecord>(
  signature: string,
  secret: string,
  options?: SignaturOptions
): T {
  const { separator = '.' } = options || {} as SignaturOptions;

  if ('string' !== typeof(signature) || !signature.length) {
    throw new TypeError(`Expected 'signature' to be defined, but received '${signature}'`);
  }

  if ('string' !== typeof(secret) || !secret.length) {
    throw new TypeError(`Expected 'secret' to be defined, but received '${secret}'`);
  }

  const [hash, enc] = signature.split(separator, 2);
  const decoded = Buffer.from(
    (hash + '==='.slice((hash.length + 3) % 4))
      .replace(/\-/gi, '+')
      .replace(/_/gi, '/'), 'base64')
    .toString('utf8');
  const signedDecoded = urlSafeBase64(
    createHmac('sha256', secret).update(decoded).digest('base64'));

  if (enc !== signedDecoded) {
    throw new SignaturError('invalid_signature', 'Signature not match');
  }

  return (JSON.parse(decoded) as DecodedData<T>).data;
}
開發者ID:motss,項目名稱:signatur,代碼行數:30,代碼來源:index.ts

示例5: makeNewUser

	private makeNewUser(email: string, password: string) {
		const solt = crypto.randomBytes(16).toString('hex');
		const hashPassword = crypto
			.createHmac("sha256", solt)
			.update(password)
			.digest('hex');

		const newUser = {
			UTC: new Date(),
			email: email,
			solt: solt,
			password: hashPassword,
		};

		this.sendMailToNewUser(email);

		return new Promise((resolve) => {
			this.db.collection("users").insert(newUser, (err) => {
				if (err) {
					resolve(false);
					return;
				}

				resolve(true);
				return;
			});
		});

	}
開發者ID:spear4life,項目名稱:Socotra,代碼行數:29,代碼來源:auth.mod.ts

示例6: computeHmac

function computeHmac(iv: Buffer, ciphertext: Buffer, opts: Options) {
  const hmac = createHmac(opts.signatureAlgorithm as string, opts.signatureKey as Buffer);
  hmac.update(iv);
  hmac.update(ciphertext);

  return forceBuffer(hmac.digest());
}
開發者ID:syaiful6,項目名稱:jonggrang,代碼行數:7,代碼來源:encrypt.ts

示例7: checkPassword

  /**
   * @returns {bool}
   */
  checkPassword (password: string) {
    const hashed = crypto
        .createHmac('sha1', this.salt + config.app.secret)
        .update(password)
        .digest('hex');

    return hashed === this.password;
  }
開發者ID:euoia,項目名稱:node-mud,代碼行數:11,代碼來源:player.ts

示例8: return

const signBlob = (exports.signBlob = (key: string, blob: string) => {
  return (
    "sha1=" +
    crypto
      .createHmac("sha1", key)
      .update(blob)
      .digest("hex")
  );
});
開發者ID:ft-interactive,項目名稱:ft-ig-github-project-manager,代碼行數:9,代碼來源:e2e.spec.ts

示例9: function

userSchema.methods.hashPassword = function(password: string): string {
	if (!password) {
		return '';
	}
	if (!this.password_salt) {
		return '';
	}
	return createHmac('sha1', this.password_salt).update(password).digest('hex');
};
開發者ID:freezy,項目名稱:node-vpdb,代碼行數:9,代碼來源:user.schema.ts

示例10: webhookAuth

export function webhookAuth(req, res, next) {
  const createdHmac = createHmac("SHA256", getEnv(SHOPIFY_SHARED_SECRET)).update(new Buffer(req.rawBody, 'utf8')).digest('base64');
  const hmacHeader = req.get('HTTP_X_SHOPIFY_HMAC_SHA256');

  if (createdHmac !== hmacHeader) {
    console.warn('HTTP_X_SHOPIFY_HMAC_SHA256 header does not match calculated HMAC');
    return res.sendStatus(401);
  }

  next()
}
開發者ID:chmurson,項目名稱:shopify,代碼行數:11,代碼來源:webhookAuth.ts


注:本文中的crypto.createHmac函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。