crypto#createHmac JavaScript 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: UserDelegationKeyCredential.js    From action-install-gh-release with Apache License 2.0 6 votes vote down vote up
/**
     * Generates a hash signature for an HTTP request or for a SAS.
     *
     * @param stringToSign -
     */
    computeHMACSHA256(stringToSign) {
        // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`);
        return createHmac("sha256", this.key).update(stringToSign, "utf8").digest("base64");
    }
Example #2
Source File: nexoCrypto.js    From Lynx with MIT License 6 votes vote down vote up
NexoCrypto = /** @class */ (function () {
    function NexoCrypto() {
    }
    NexoCrypto.encrypt = function (messageHeader, saleToPoiMessageJson, securityKey) {
        var derivedKey = NexoDerivedKeyGenerator.deriveKeyMaterial(securityKey.passphrase);
        var saleToPoiMessageByteArray = Buffer.from(saleToPoiMessageJson, "ascii");
        var ivNonce = NexoCrypto.generateRandomIvNonce();
        var encryptedSaleToPoiMessage = NexoCrypto.crypt(saleToPoiMessageByteArray, derivedKey, ivNonce, Modes.ENCRYPT);
        var encryptedSaleToPoiMessageHmac = NexoCrypto.hmac(saleToPoiMessageByteArray, derivedKey);
        var securityTrailer = {
            adyenCryptoVersion: securityKey.adyenCryptoVersion,
            hmac: encryptedSaleToPoiMessageHmac.toString("base64"),
            keyIdentifier: securityKey.keyIdentifier,
            keyVersion: securityKey.keyVersion,
            nonce: ivNonce.toString("base64"),
        };
        return {
            messageHeader: messageHeader,
            nexoBlob: encryptedSaleToPoiMessage.toString("base64"),
            securityTrailer: securityTrailer,
        };
    };
    NexoCrypto.prototype.decrypt = function (saleToPoiSecureMessage, securityKey) {
        NexoCrypto.validateSecurityKey(securityKey);
        var encryptedSaleToPoiMessageByteArray = Buffer.from(saleToPoiSecureMessage.nexoBlob, "base64");
        var derivedKey = NexoDerivedKeyGenerator.deriveKeyMaterial(securityKey.passphrase);
        var ivNonce = Buffer.from(saleToPoiSecureMessage.securityTrailer.nonce, "base64");
        var decryptedSaleToPoiMessageByteArray = NexoCrypto.crypt(encryptedSaleToPoiMessageByteArray, derivedKey, ivNonce, Modes.DECRYPT);
        var receivedHmac = Buffer.from(saleToPoiSecureMessage.securityTrailer.hmac, "base64");
        this.validateHmac(receivedHmac, decryptedSaleToPoiMessageByteArray, derivedKey);
        return decryptedSaleToPoiMessageByteArray.toString("ascii");
    };
    NexoCrypto.validateSecurityKey = function (securityKey) {
        var isValid = securityKey
            && securityKey.passphrase
            && securityKey.keyIdentifier
            && securityKey.keyVersion
            && securityKey.adyenCryptoVersion;
        if (!isValid) {
            throw new InvalidSecurityKeyException("Invalid Security Key");
        }
    };
    NexoCrypto.crypt = function (bytes, dk, ivNonce, mode) {
        var actualIV = Buffer.alloc(NEXO_IV_LENGTH);
        for (var i = 0; i < NEXO_IV_LENGTH; i++) {
            actualIV[i] = dk.iv[i] ^ ivNonce[i];
        }
        var cipher = mode === Modes.ENCRYPT
            ? createCipheriv("aes-256-cbc", dk.cipherKey, actualIV)
            : createDecipheriv("aes-256-cbc", dk.cipherKey, actualIV);
        var encrypted = cipher.update(bytes);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        return encrypted;
    };
    NexoCrypto.hmac = function (bytes, derivedKey) {
        var mac = createHmac("sha256", derivedKey.hmacKey);
        return mac.update(bytes).digest();
    };
    NexoCrypto.generateRandomIvNonce = function () {
        return randomBytes(NEXO_IV_LENGTH);
    };
    NexoCrypto.prototype.validateHmac = function (receivedHmac, decryptedMessage, derivedKey) {
        var hmac = NexoCrypto.hmac(decryptedMessage, derivedKey);
        var isValid = hmac.every(function (item, index) { return item === receivedHmac[index]; });
        if (!isValid) {
            throw new NexoCryptoException("Hmac validation failed");
        }
    };
    return NexoCrypto;
}())
Example #3
Source File: StorageSharedKeyCredential.js    From action-install-gh-release with Apache License 2.0 5 votes vote down vote up
/**
     * Generates a hash signature for an HTTP request or for a SAS.
     *
     * @param stringToSign -
     */
    computeHMACSHA256(stringToSign) {
        return createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64");
    }
Example #4
Source File: hmacValidator.js    From Lynx with MIT License 5 votes vote down vote up
HmacValidator = /** @class */ (function () {
    function HmacValidator() {
    }
    HmacValidator.prototype.calculateHmac = function (data, key) {
        var dataString = typeof data !== "string" ? this.getDataToSign(data) : data;
        var rawKey = Buffer.from(key, "hex");
        return createHmac(HmacValidator.HMAC_SHA256_ALGORITHM, rawKey).update(dataString, "utf8").digest("base64");
    };
    HmacValidator.prototype.validateHMAC = function (notificationRequestItem, key) {
        var expectedSign = this.calculateHmac(notificationRequestItem, key);
        var merchantSign = notificationRequestItem.additionalData[HMAC_SIGNATURE];
        return expectedSign === merchantSign;
    };
    HmacValidator.prototype.isNotificationRequestItem = function (item) {
        return !Object.values(item).every(function (value) { return typeof value === "string"; });
    };
    HmacValidator.prototype.getDataToSign = function (notificationRequestItem) {
        if (this.isNotificationRequestItem(notificationRequestItem)) {
            var signedDataList = [];
            signedDataList.push(notificationRequestItem.pspReference);
            signedDataList.push(notificationRequestItem.originalReference);
            signedDataList.push(notificationRequestItem.merchantAccountCode);
            signedDataList.push(notificationRequestItem.merchantReference);
            signedDataList.push(notificationRequestItem.amount.value);
            signedDataList.push(notificationRequestItem.amount.currency);
            signedDataList.push(notificationRequestItem.eventCode);
            signedDataList.push(notificationRequestItem.success);
            return signedDataList.join(HmacValidator.DATA_SEPARATOR);
        }
        else {
            var keys_1 = [];
            var values_1 = [];
            var replacer_1 = function (str) {
                return str.replace(/\\/g, "\\\\").replace(/:/g, "\\:");
            };
            Object.entries(notificationRequestItem).sort().forEach(function (_a) {
                var key = _a[0], value = _a[1];
                keys_1.push(replacer_1(key));
                values_1.push(replacer_1(value));
            });
            return __spreadArrays(keys_1, values_1).join(HmacValidator.DATA_SEPARATOR);
        }
    };
    HmacValidator.HMAC_SHA256_ALGORITHM = "sha256";
    HmacValidator.DATA_SEPARATOR = ":";
    return HmacValidator;
}())