2011-07-07 22 views
0

我有這個僞代碼,我想將它轉換成工作代碼:javascript如何構建簽名?

string constructSignature(string timestamp, string UID, string secretKey) { 
    baseString = timestamp + "_" + UID;         // Construct a "base string" for signing 
    binaryBaseString = ConvertUTF8ToBytes(baseString); // Convert the base string into a binary array 
    binaryKey = ConvertFromBase64ToBytes(secretKey);  // Convert secretKey from BASE64 to a binary array 
    binarySignature = hmacsha1(binaryKey, baseString);  // Use the HMAC-SHA1 algorithm to calculate the signature 
    signature = ConvertToBase64(binarySignature);    // Convert the signature to a BASE64 
    return signature; 
} 

什麼想法? 感謝

+0

我真的不知道你所說的「簽名」是什麼意思?標識特定機器的散列? –

回答

1

一些想法:

  • 不計算BinaryBaseString,因爲你永遠不使用它
  • 沒有提及UTF8沒有任何理由可言 - 在JavaScript字符串都是Unicode,這僅遠程連接到UTF。
  • 不要把實現細節在你的僞代碼 - 尤其是你實際上並不需要的人(如假設密鑰應該是「字節」,這意味着什麼,而事實上,在standard library需要和返回的字符串) 。
  • 不要寫,只是重申了代碼做註釋。

這給我們留下了:

var constructSignature = function(timestamp, UID, secretKey) { 
    return Crypto.HMAC(Crypto.SHA1, timestamp + "_" + UID, secretKey, 
        { asString: true }); 
};