/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JIM.
 *
 * The Initial Developer of the Original Code is
 * Pawel Chmielowski <prefiks@o2.pl>
 *
 * Portions created by the Initial Developer are Copyright (C) 2003
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 * Pawel Chmielowski <prefiks@o2.pl>
 *
 * ***** END LICENSE BLOCK ***** */

/**
 * crypto.SHA1
 *
 *
 */
ML.load("crypto/utils.js");

function sha1_ft(t, b, c, d) {
  if(t < 20)
      return (b & c) | ((~b) & d);
  if(t < 40) 
      return b ^ c ^ d;
  if(t < 60) 
      return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

function sha1_bin(data, length) {
    var W = new Array(80);
    var A, B, C, D, E;
    var A2, B2, C2, D2, E2;
    var i, t, tmp;
    var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];

    data[length >> 5] |= 0x80 << (24 - length % 32);
    data[((length + 64 >> 9) << 4) + 15] = length;

    A = 0x67452301;
    B = 0xefcdab89;
    C = 0x98badcfe;
    D = 0x10325476;
    E = 0xc3d2e1f0;

    for (i = 0; i < data.length; i+=16) {
        A2 = A;
        B2 = B;
        C2 = C;
        D2 = D;
        E2 = E;
        for (t = 0; t < 80; t++) {
            W[t] = t < 16 ? data[t+i] : bitroll(W[t-3] ^ W[t-8] ^ W[t- 14] ^ W[t-16], 1);
            tmp = madd(madd(bitroll(A, 5), sha1_ft(t, B, C, D)),
                    madd(madd(E, W[t]), K[Math.floor(t/20)]));

            E = D;
            D = C;
            C = bitroll(B, 30);
            B = A;
            A = tmp;
        }
        A = madd(A, A2);
        B = madd(B, B2);
        C = madd(C, C2);
        D = madd(D, D2);
        E = madd(E, E2);
    }
    return new Array(A, B, C, D, E);
}

function sha1(data, isWideChar) {
    return bin2hex(swapWords(sha1_bin(string2bin(data, true, isWideChar), data.length*(isWideChar ? 16 : 8))));
}

