/*
 * BEGIN FLOCK GPL
 *
 * Copyright Flock Inc. 2005-2009
 * http://flock.com
 *
 * This file may be used under the terms of the
 * GNU General Public License Version 2 or later (the "GPL"),
 * http://www.gnu.org/licenses/gpl.html
 *
 * 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.
 *
 * END FLOCK GPL
 */

/**
 * Convenience wrappers for JavaScript code to use nsICryptoHash
 * functionality. They return the standard hex representation of
 * the hashes.
 *
 * Import this module through
 *
 * Components.utils.import("resource:///modules/FlockCryptoHash.jsm");
 *
 * Common usage:
 *
 * var md5 = FlockCryptoHash.md5("thing to hash");
 * var md5 = FlockCryptoHash.md5Stream(someInputStream);
 *
 * There are also SHA1 variants, and generic functions (hash and hashStream)
 * which take an nsICryptoHash algorithm constant as their second parameter.
 */

const CC = Components.classes;
const CI = Components.interfaces;
const CR = Components.results;

var EXPORTED_SYMBOLS = ["FlockCryptoHash"];

var FlockCryptoHash = {
  hashStream: function FlockCryptoHash_hashStream(aStream, aAlgorithm) {
    var hasher = CC["@mozilla.org/security/hash;1"]
                 .createInstance(CI.nsICryptoHash);
    hasher.init(aAlgorithm);

    hasher.updateFromStream(aStream, aStream.available());
    var hash = hasher.finish(false);

    var ret = "";
    for (var i = 0; i < hash.length; ++i) {
        var hexChar = hash.charCodeAt(i).toString(16);
        if (hexChar.length == 1) {
            ret += "0";
        }
        ret += hexChar;
    }

    return ret;
  },
  hash: function FlockCryptoHash_hash(aString, aAlgorithm) {
    var stream = CC["@mozilla.org/io/string-input-stream;1"]
                 .createInstance(CI.nsIStringInputStream);
    stream.setData(aString, aString.length);
    return this.hashStream(stream, aAlgorithm);
  },

  md5Stream: function FlockCryptoHash_md5Stream(aStream) {
    return this.hashStream(aStream, CI.nsICryptoHash.MD5);
  },
  md5: function FlockCryptoHash_md5(aString) {
    return this.hash(aString, CI.nsICryptoHash.MD5);
  },

  hexSHA1FromStream: function FlockCryptoHash_hexSHA1FromStream(aStream) {
    return this.hashStream(aStream, CI.nsICryptoHash.SHA1);
  },
  sha1: function FlockCryptoHash_sha1(aString) {
    return this.hash(aString, CI.nsICryptoHash.SHA1);
  }
};
