CryptoJS HMAC-SHA1 Encryption

CryptoJS HMAC-SHA1 Encryption

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha1.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64.js"></script>
<p id="hash1"></p>
<p id="hash2"></p>
<p id="hash3"></p>
<p id="try">Check console for error</p>

JavaScript

function toBase64EncodedHmacSha1(data, key, rawOutput) {
  // if boolean, cast to string
  if (typeof(key) === 'boolean') {
    key = key ? '1' : '0';
  }

  // optional
  if (typeof(rawOutput) === 'undefined') {
    rawOutput = false;
  }

  // check type
  if (typeof(rawOutput) !== 'boolean') {
    throw new Error('Raw output is boolean value: true/false');
  }

  var hash = CryptoJS.HmacSHA1(data, key);

  if (rawOutput) {
    // output: raw binary
    return CryptoJS.enc.Base64.stringify(hash);
  }

  var hex = CryptoJS.enc.Hex.stringify(hash);
  var wordArray = CryptoJS.enc.Utf8.parse(hex);

  // output: lowercase hexits
  return CryptoJS.enc.Base64.stringify(wordArray);
}

// echo base64_encode(hash_hmac("sha1", "what is this", true));
// echo base64_encode(hash_hmac("sha1", "what is this", true, false));
$('#hash1').text(toBase64EncodedHmacSha1('what is this', true));
$('#hash2').text(toBase64EncodedHmacSha1('what is this', true, false));

// echo base64_encode(hash_hmac("sha1", "what is this", true, true));
$('#hash3').text(toBase64EncodedHmacSha1('what is this', true, true));

$('#try').text(toBase64EncodedHmacSha1('what is this', true, 'This will throw error'));