Search code examples
javascriptsignature

javascript how to Constructing a Signature?


i have this pseudo code and i would like to convert it into working code:

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;  
} 

any idea? thanks


Solution

  • Some ideas:

    • Don't calculate BinaryBaseString, given that you never use it
    • Don't refer to UTF8 for no reason at all -- strings in JavaScript are Unicode, which is only distantly connected to UTF.
    • Don't put implementation details in your pseudocode -- especially ones you don't actually need (like assuming the secret key should be in "bytes", whatever that means, when in fact, the standard library takes and returns strings).
    • Don't write comments that just restate what the code is doing.

    Which leaves us with:

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