From bebb561a9138021dca33e1b069267622880eafd4 Mon Sep 17 00:00:00 2001 From: hogelog Date: Fri, 16 Jan 2009 22:36:38 +0000 Subject: * add hash.js: md2|md5|sha1|sha256|sha384|sha512 hash of file git-svn-id: http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk@28532 d0d07461-0603-4401-acd4-de1884942a52 --- hash.js | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 hash.js (limited to 'hash.js') diff --git a/hash.js b/hash.js new file mode 100644 index 0000000..1f3422f --- /dev/null +++ b/hash.js @@ -0,0 +1,88 @@ +// PLUGIN_INFO//{{{ +var PLUGIN_INFO = + + {NAME} + hash of file + hogelog + 0.1 + 2.0pre + 2.0pre + http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/hash.js + +; +//}}} + +(function() { + const PR_UINT_MAX = 0xffffffff; + const Cc = Components.classes; + const Ci = Components.interfaces; + const Algos = [ + ["md2", "MD2 Algorithm"], + ["md5", "MD5 Algorithm"], + ["sha1", "SHA1 Algorithm"], + ["sha256", "SHA256 Algorithm"], + ["sha384", "SHA385 Algorithm"], + ["sha512", "SHA512 Algorithm"], + ]; + + function getStream(path) + { + let file = io.getFile(path); + let stream = Cc["@mozilla.org/network/file-input-stream;1"] + .createInstance(Ci.nsIFileInputStream); + stream.init(file, 0x01, 0444, 0); + return stream; + } + + // return the two-digit hexadecimal code for a byte + function toHexString(charCode) + { + return ("0" + charCode.toString(16)).slice(-2); + } + + + commands.addUserCommand(["hash"], "hash of file", + function(args){ + if (args.length!=2) { + + liberator.echo("usage \":hash md2|md5|sha1|sha256|sha384|sha512 file-path\""); + return false; + } + let [algo, path] = args; + let stream = getStream(path); + + let crypt = Cc["@mozilla.org/security/hash;1"] + .createInstance(Ci.nsICryptoHash); + crypt.initWithString(algo); + + // read the entire stream + crypt.updateFromStream(stream, PR_UINT_MAX); + + // get base-64 string + let hash = crypt.finish(false); + + // convert the binary hash data to a hex string. + let str = [toHexString(hash.charCodeAt(i)) for(i in hash)].join(""); + util.copyToClipboard(str, true); + }, + { + bang: true, + completer: function (context){ + let args = context.value.split(/\s/); + if (args.length<=2) { + context.title = "hash algorithm"; + context.completions = Algos; + } else if (args.length==3) { + completion.url(context, "f"); + } + }, + }); + +})(); +// vim: fdm=marker sw=4 ts=4 et: -- cgit v1.2.3