亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 javascript 中為數據傳輸生成 HMAC-SHA-256 登錄?

如何在 javascript 中為數據傳輸生成 HMAC-SHA-256 登錄?

慕沐林林 2023-02-17 17:59:18
我有一個 Angular 項目,我必須在其中實現數據傳輸支付。但我無法生成付款標志。我正在按照此鏈接上給出的過程(在此處輸入鏈接描述)生成符號。但我無法實現它。我正在使用角度庫 crypto-js 生成 HMAC-SHA-256 簽名字符串。這是我的javascript代碼。const merchantId = 'xxxxxxx';const refNo = '1234567890';const amount = 0;const currency = 'CHF';const theme = 'DT2015';const paymentmethod = 'VIS';const stringSs = merchantId+amount+currency+refNo;const base = 16;// My Hmac Keyconst s = 'fa3d0ea1772cf21e53158283e4f123ebf1eb1ccfb15619e2fc91ee6860a2e5e48409e902b610ce5dc6f7f77fab8affb60d69b2a7aa9acf56723d868d36ab3f32';// Step 1: Code to generate hex to byte of hmac keyconst a = s.replace(/../g, '$&_').slice (0, -1).split ('_').map ((x) => parseInt (x, base));//  Step 3: Sign the string with HMAC-SHA-256 together with your HMAC keyconst signedString = HmacSHA256(a, stringSs);// Step 4: Translate the signature from byte to hex formatconst signString = enc.Hex.stringify(signedString);您能幫我解決這個問題,以建議我做錯了什么或可以通過什么方式實現。
查看完整描述

2 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

你可以用加密來做到這一點(不需要安裝額外的庫)


// Typescript

import * as crypto from 'crypto';


function signKey (clientKey: string, msg: string) {

    const key = new Buffer(clientKey, 'hex');

    return crypto.createHmac('sha256', key).update(msg).digest('hex');

}

// Javascript

const crypto = require('crypto')


function signKey (clientKey, msg) {

    const key = new Buffer(clientKey, 'hex');

    return crypto.createHmac('sha256', key).update(msg).digest('hex');

}

signKey(s, stringSs)


查看完整回答
反對 回復 2023-02-17
?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

要按要求回答 crypto-js 的問題(請參閱https://github.com/brix/crypto-js),以下內容可以解決問題:


// Javascript; example from datatrans documentation using a random key

stringSs ='3000017692850CHF91827364';

key='1ca12d7c0629194a9f9d0dbbc957709dd3aed385925b077e726813f0b452de6a38256abd1116138d21754cfb33964b6b1aaa375b74d3580fcda916898f553c92';

expectedSign='d7dee9ae1e542bc02bcb063a3dd3673871b2e43ccb4c230f26e8b85d14e25901';


signedString = CryptoJS.HmacSHA256(stringSs, CryptoJS.enc.Hex.parse(key));

resultSign = CryptoJS.enc.Hex.stringify(signedString);


// now resultSign == expectedSign is true :-)


忍者神龜的方法幾乎是正確的,除了第 1 步,十六進制到字節。改用 Crypto-JS 的內置函數,一切都按預期工作。


查看完整回答
反對 回復 2023-02-17
  • 2 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號