2013-11-10 55 views
3

我已經花了近6小時實現郵件簽名算法。它不會在所有的工作:OpenSSL的HMAC-SHA1摘要不匹配加密的

這是PHP代碼,並生成摘要:

$payload = "thisisanapple"; 
$signature = hash_hmac("sha1", $payload, "thisisarandomkey"); 
$data = base64_encode($signature); 
// YzExZWRmZDliMjQzNTZjNzhlNmE3ZTdmMDE3ODJjNmMxMmM4ZTllMQ== 

這是JS Node.js的服務器做同樣的事情上運行:

var hmac = crypto.createHmac('sha1', "thisisarandomkey"); 
hmac.update("thisisanapple"); 
var signature = hmac.digest('base64'); 
// wR7f2bJDVseOan5/AXgsbBLI6eE= 

我不知道這裏有什麼問題..我有嘗試SHA256,但他們仍然是不同的。我還使用了由OpenSSL生成的私鑰,無論是明文還是base64,仍然是相同的結果(不同的密鑰)。

回答

2

hash_hmac有四個參數,最後一個指定輸出,默認hash_hmac返回十六進制字符串,而不是原始數據。所以base64_encode在PHP代碼片段中編碼十六進制字符串。

這人會工作得很好:如果您希望複製在JS的PHP行爲

$payload = "thisisanapple"; 
$signature = hash_hmac("sha1", $payload, "thisisarandomkey", true); 
$data = base64_encode($signature); 
// wR7f2bJDVseOan5/AXgsbBLI6eE= 
+1

你知道什麼是JS代碼相匹配原始問題中的PHP行爲? – karellm

0

,這裏是代碼:

hmac = crypto.createHmac('sha1', 'thisisarandomkey') 
signature = hmac.update('thisisanapple') 
data = new Buffer(hmac.digest('hex')).toString('base64')