crypto#createHmac TypeScript Examples
The following examples show how to use
crypto#createHmac.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From eufy-security-client with MIT License | 7 votes |
eufyKDF = (key: Buffer): Buffer => {
const hash_length = 32;
const digest_length = 48;
const staticBuffer = Buffer.from("ECIES");
const steps = Math.ceil(digest_length / hash_length);
const buffer = Buffer.alloc(hash_length * steps);
let tmpBuffer = staticBuffer;
for (let step = 0; step < steps; ++step) {
tmpBuffer = createHmac("sha256", key).update(tmpBuffer).digest();
const digest = createHmac("sha256", key).update(Buffer.concat([tmpBuffer, staticBuffer])).digest();
digest.copy(buffer, hash_length * step);
}
return buffer.slice(0, digest_length);
}
Example #2
Source File: utils.ts From eufy-security-client with MIT License | 7 votes |
getAdvancedLockKey = (key: string, publicKey: string): string => {
const ecdh: ECDH = createECDH("prime256v1");
ecdh.generateKeys();
const secret = ecdh.computeSecret(Buffer.concat([Buffer.from("04", "hex"), Buffer.from(publicKey, "hex")]));
const randomValue = randomBytes(16);
const derivedKey = eufyKDF(secret);
const encryptedData = encryptAdvancedLockData(key, derivedKey.slice(0, 16), randomValue);
const hmac = createHmac("sha256", derivedKey.slice(16));
hmac.update(randomValue);
hmac.update(encryptedData);
const hmacDigest = hmac.digest();
return Buffer.concat([Buffer.from(ecdh.getPublicKey("hex", "compressed"), "hex"), randomValue, encryptedData, hmacDigest]).toString("hex");
}
Example #3
Source File: hd-wallet.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 6 votes |
// @ts-ignore
CKDPriv({ key, chainCode }, index): Keys {
const indexBuffer = Buffer.allocUnsafe(4);
indexBuffer.writeUInt32BE(index, 0);
const data = Buffer.concat([Buffer.alloc(1, 0), key, indexBuffer]);
const I = createHmac('sha512', chainCode)
.update(data)
.digest();
const IL = I.slice(0, 32);
const IR = I.slice(32);
return {
key: IL,
chainCode: IR,
};
}
Example #4
Source File: _helpers.ts From telegram-standup-bot with MIT License | 6 votes |
signatureMath = ({ hash, ...data }) => {
if (!hash) {
return false;
}
const checkString = Object.keys(data)
.sort()
.map((k) => `${k}=${data[k]}`)
.join('\n');
const hmac = createHmac('sha256', secret).update(checkString).digest('hex');
return hmac === hash;
}
Example #5
Source File: keyDerivation.ts From hoprnet with GNU General Public License v3.0 | 6 votes |
/**
* Derives the initial commitment seed on a newly opened channel.
* @param privateKey Node private key.
* @param channelInfo Additional information identifying the channel.
*/
export function deriveCommitmentSeed(privateKey: Uint8Array, channelInfo: Uint8Array): Uint8Array {
if (privateKey.length != SECRET_LENGTH) {
throw Error(`Invalid arguments`)
}
const key = expand(HASH_ALGORITHM, HASH_LENGTH, Buffer.from(privateKey), SECRET_LENGTH, HASH_KEY_COMMITMENT_SEED)
return new Uint8Array(createHmac(HASH_ALGORITHM, key).update(channelInfo).digest().buffer)
}
Example #6
Source File: mac.ts From hoprnet with GNU General Public License v3.0 | 6 votes |
/**
* Computes the authentication tag to make the integrity of
* the packet header verifiable
* @param secret shared secret with the creator of the packet
* @param header the packet header
* @returns the authentication tag
*/
export function createMAC(secret: Uint8Array, header: Uint8Array): Uint8Array {
if (secret.length != SECRET_LENGTH) {
throw Error(`Invalid arguments`)
}
const key = expand(HASH_ALGORITHM, HASH_LENGTH, Buffer.from(secret), SECRET_LENGTH, HASH_KEY_HMAC)
return createHmac(HASH_ALGORITHM, key).update(header).digest()
}
Example #7
Source File: resolver.ts From one-platform with MIT License | 6 votes |
export default function resolver(
req: Request,
res: Response,
next: NextFunction
): void {
const { uid, role, rhatUUID } = res.locals.user;
/* Adding additional roles */
role.push('user:' + uid, 'user:' + rhatUUID, 'op-users');
const token = createHmac('sha1', COUCHDB_SECRET as string)
.update(uid) // lgtm[js/weak-cryptographic-algorithm]
.digest('hex');
const proxy = createProxyMiddleware({
target: COUCHDB_HOST,
secure: useSecureSSL,
changeOrigin: true,
headers: {
'X-Auth-CouchDB-UserName': uid,
'X-Auth-CouchDB-Roles': role.join(','),
'X-Auth-CouchDB-Token': token,
},
pathRewrite: {
['^/api/couchdb']: '',
},
});
proxy(req, res, next);
}
Example #8
Source File: gitea.ts From metroline with GNU General Public License v3.0 | 6 votes |
// https://docs.gitea.io/en-us/webhooks/#example
// eslint-disable-next-line class-methods-use-this
async verifyWebhookSecret(req: Request, secret: string): Promise<boolean> {
const signature = req.header(GITEA_WEBHOOK_SIGNATURE_HEADER);
const { rawBody } = req as any;
if (!signature || !rawBody || !Buffer.isBuffer(rawBody)) {
return false;
}
const hmac = createHmac('sha256', secret)
.update(rawBody)
.digest()
.toString('hex');
return hmac === signature;
}
Example #9
Source File: github.ts From metroline with GNU General Public License v3.0 | 6 votes |
// https://developer.github.com/webhooks/event-payloads/#delivery-headers
// eslint-disable-next-line class-methods-use-this
async verifyWebhookSecret(req: Request, secret: string): Promise<boolean> {
const signature = req.header(GITHUB_WEBHOOK_SIGNATURE_HEADER);
const { rawBody } = req as any;
if (!signature || !rawBody || !Buffer.isBuffer(rawBody)) {
return false;
}
const hmac = createHmac('sha1', secret)
.update(rawBody)
.digest()
.toString('hex');
return hmac === signature.replace('sha1=', '');
}
Example #10
Source File: prp.ts From hoprnet with GNU General Public License v3.0 | 5 votes |
function hash(data: Uint8Array, k: Uint8Array, iv: Uint8Array): void {
const hash = createHmac(HASH_ALGORITHM, Buffer.concat([k, iv], INTERMEDIATE_KEY_LENGTH + INTERMEDIATE_IV_LENGTH))
hash.update(data.subarray(HASH_LENGTH))
u8aXOR(true, data.subarray(0, HASH_LENGTH), hash.digest())
}
Example #11
Source File: node-support.ts From ftx-api with MIT License | 5 votes |
export async function signMessage(message: string, secret: string): Promise<string> {
if (typeof createHmac === 'function') {
return createHmac('sha256', secret)
.update(message)
.digest('hex');
}
return browserMethods.signMessage(message, secret);
}
Example #12
Source File: node-support.ts From bybit-api with MIT License | 5 votes |
export async function signMessage(
message: string,
secret: string
): Promise<string> {
return createHmac('sha256', secret).update(message).digest('hex');
}
Example #13
Source File: authUtils.ts From homebridge-lg-thinq-ac with Apache License 2.0 | 5 votes |
function generateOAuth2Signature(message: string, secretKey: string) {
return createHmac('sha1', secretKey)
.update(message)
.digest()
.toString('base64')
}
Example #14
Source File: requestSigner.ts From MDDL with MIT License | 5 votes |
hmacSha256 = (data: string, secret: string) => {
return createHmac('sha256', secret).update(data).digest('hex')
}
Example #15
Source File: node-crypto.ts From mtcute with GNU Lesser General Public License v3.0 | 5 votes |
hmacSha256(data: Buffer, key: Buffer): MaybeAsync<Buffer> {
return createHmac('sha256', key).update(data).digest()
}
Example #16
Source File: helpers.ts From livepeer-com with MIT License | 5 votes |
export function sign(data: string, secret: string) {
const hmac = createHmac("sha256", secret);
hmac.update(Buffer.from(data));
return hmac.digest("hex");
}
Example #17
Source File: Tools.ts From core with GNU Affero General Public License v3.0 | 5 votes |
export function HMAC(value: string, secret=process.env.CAMO_SECRET):string|null {
try {
return createHmac('sha1', secret).update(value, 'utf8').digest('hex')
}
catch {
return null
}
}
Example #18
Source File: helpers.ts From blockfrost-js with Apache License 2.0 | 5 votes |
verifyWebhookSignature = (
webhookPayload: unknown,
signatureHeader: string,
secret: string,
timestampToleranceSeconds = 600,
) => {
let timestamp;
let signature;
if (Array.isArray(signatureHeader)) {
throw new SignatureVerificationError(
'Unexpected: An array was passed as a header',
);
}
const decodedWebhookPayload = Buffer.isBuffer(webhookPayload)
? webhookPayload.toString('utf8')
: webhookPayload;
const decodedSignatureHeader = Buffer.isBuffer(signatureHeader)
? signatureHeader.toString('utf8')
: signatureHeader;
// Parse signature header (example: t=1648550558,v1=162381a59040c97d9b323cdfec02facdfce0968490ec1732f5d938334c1eed4e)
const tokens = decodedSignatureHeader.split(',');
for (const token of tokens) {
const [key, value] = token.split('=');
switch (key) {
case 't':
timestamp = Number(value);
break;
case 'v1':
signature = value;
break;
default:
console.warn(
`Cannot parse part of the signature header, key "${key}" is not supported by this version of Blockfrost SDK.`,
);
}
}
if (!timestamp || !signature) {
throw new SignatureVerificationError('Invalid signature header format', {
signatureHeader: decodedSignatureHeader,
webhookPayload: decodedWebhookPayload,
});
}
// Recreate signature by concatenating timestamp with stringified payload,
// then compute HMAC using sha256 and provided secret (auth token)
const signaturePayload = `${timestamp}.${decodedWebhookPayload}`;
const hmac = createHmac('sha256', secret)
.update(signaturePayload)
.digest('hex');
if (hmac !== signature) {
return false;
}
// computed hmac should match signature parsed from a signature header
const currentTimestamp = Math.floor(new Date().getTime() / 1000);
if (currentTimestamp - timestamp > timestampToleranceSeconds) {
if (isDebugEnabled()) {
console.debug(
`Invalid signature. Signature timestamp ${timestamp} is out of range!`,
);
}
return false;
} else {
// Successfully validate the signature only if it is within tolerance
return true;
}
}
Example #19
Source File: crypto.ts From FIDO2Client with MIT License | 5 votes |
static hmac(key: Buffer, message: Buffer): Buffer {
switch (Fido2Spec) {
case Fido2SpecVersion.FIDO_2_1:
return createHmac('sha256', key).update(message).digest();
default:
throw new CommonFido2SpecNotImplemented();
}
}
Example #20
Source File: hd-wallet.service.ts From xBull-Wallet with GNU Affero General Public License v3.0 | 5 votes |
getMasterKeyFromSeed(seed: Hex): Keys {
const hmac = createHmac('sha512', this.ED25519_CURVE);
const hmacResult = hmac.update(Buffer.from(seed, 'hex')).digest();
return {
key: hmacResult.slice(0, 32),
chainCode: hmacResult.slice(32),
};
}