2011-07-07 23 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 }); 
};