nsICryptoHash 编辑

netwerk/base/public/nsICryptoHash.idlScriptable This interface can be used to compute a cryptographic hash function of some data. You can, for example, calculate the SHA256 hash of a file to determine if it contains the data you think it does. The hash algorithms supported are MD2, MD5, SHA-1, SHA-256, SHA-384, and SHA-512. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0)

Method overview

ACString finish(in PRBool aASCII);
void init(in unsigned long aAlgorithm);
void initWithString(in ACString aAlgorithm);
void update([const, array, size_is(aLen)] in octet aData, in unsigned long aLen);
void updateFromStream(in nsIInputStream aStream, in unsigned long aLen);

Constants

Hash algorithms

These constants are used by the init() method to indicate which hashing function to use. The values map directly onto the values defined in mozilla/security/nss/lib/cryptohi/hasht.h.

ConstantValueDescription
MD21Message Digest Algorithm 2
MD52Message-Digest algorithm 5
SHA13Secure Hash Algorithm 1
SHA2564Secure Hash Algorithm 256
SHA3845Secure Hash Algorithm 384
SHA5126Secure Hash Algorithm 512

Methods

finish()

Completes the hash object and produces the actual hash data.

Note: This method may be called any time after " .. manch("init") .. " is called. This call resets the object.
ACString finish(
  in PRBool aASCII
);
Parameters
aASCII
If true then the returned value is a base-64 encoded string. If false, then the returned value is binary data.
Return value

This method returns a hash of the data that was read by this object. This can be either binary data or a base-64 encoded string.

Exceptions thrown
NS_ERROR_NOT_INITIALIZED
Indicates that init() or initWithString() has not been called.

init()

Initialize the hashing object. This method may be called multiple times with different algorithm types.

Note: This method or " .. manch("initWithString") .. " must be called before any other method on this interface is called.
void init(
  in unsigned long aAlgorithm
);
Parameters
aAlgorithm
The hash algorithm to use. Must be one of the Hash Algorithms.
Exceptions thrown
NS_ERROR_INVALID_ARG
Indicates that an unsupported algorithm type was passed

initWithString()

Initialize the hashing object. This method may be called multiple times with different algorithm types.

Note: This method or " .. manch("init") .. " must be called before any other method on this interface is called.
void initWithString(
  in ACString aAlgorithm
);
Parameters
aAlgorithm
The hash algorithm type to be used as a string, such as "SHA256".
Exceptions thrown
NS_ERROR_INVALID_ARG
Indicates that an unsupported algorithm type was passed

update()

Adds an array of data to be hashed to the object. See Computing the Hash of a String for an example of using this method.

void update(
  [const, array, size_is(aLen)] in octet aData,
  in unsigned long aLen
);
Parameters
aData
A buffer to calculate the hash over.
aLen
The length of the buffer aData.
Exceptions thrown
NS_ERROR_NOT_INITIALIZED
Indicates that init() or initWithString() has not been called.

updateFromStream()

Calculates and updates a new hash based on a given data stream (nsIInputStream). See Computing the Hash of a File for an example of using this method.

void updateFromStream(
  in nsIInputStream aStream,
  in unsigned long aLen
);
Parameters
aStream
An input stream to read from.
aLen
How much to read from the given aStream. Passing PR_UINT32_MAX indicates that all data available will be used to update the hash.
Exceptions thrown
NS_ERROR_NOT_AVAILABLE
Indicates that the requested amount of data to be calculated into the hash is not available.
NS_ERROR_NOT_INITIALIZED
Indicates that init() or initWithString() has not been called.

Example

Computing the Hash of a File

You can easily compute the hash of a file using nsICryptoHash. You will need to create an instance of nsICryptoHash, open an input stream from a file, and then update the hash with the file. The following example shows how to compute the SHA256 hash of a file:

// hardcoded here for convenience
var path = "c:\\windows\\notepad.exe";
var f = Components.classes["@mozilla.org/file/local;1"]
                  .createInstance(Components.interfaces.nsILocalFile);
f.initWithPath(path);
var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                        .createInstance(Components.interfaces.nsIFileInputStream);
// open for reading
istream.init(f, 0x01, 0444, 0);
var ch = Components.classes["@mozilla.org/security/hash;1"]
                   .createInstance(Components.interfaces.nsICryptoHash);
// we want to use the SHA256 algorithm
ch.init(ch.SHA256);
// this tells updateFromStream to read the entire file
const PR_UINT32_MAX = 0xffffffff;
ch.updateFromStream(istream, PR_UINT32_MAX);
// pass false here to get binary data back
var hash = ch.finish(false);

// return the two-digit hexadecimal code for a byte
function toHexString(charCode)
{
  return ("0" + charCode.toString(16)).slice(-2);
}

// convert the binary hash data to a hex string.
var s = Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join("");
// s now contains your hash in hex

This gives 5eb63bbbe01eeed093cb22bb8f5acdc3 for the hash value. This example, while simple, shows most of the functionality of the interface.

The first thing to note is that when you call the init() method you must specify the hash algorithm to use. All of the available algorithms are specified as constants on the interface.

Also note that when you call the updateFromStream() method, the second parameter is the number of bytes to read. Passing PR_UINT32_MAX here indicates that you want the entire file read.

Finally, note that calling the finish() method produces the hash value. The single parameter to this method is false in this example to return binary data. Passing true returns the hash as a base 64 encoded string. In this example we take the binary data and produce a hexadecimal string of the result, as is commonly output by hashing programs.

Computing the Hash of a String

Another common operation is computing the hash value of a string. Since hash functions are computed over bytes, you will first need to convert the string to a series of bytes using nsIScriptableUnicodeConverter and a Unicode encoding that you specify.

Note: Different encodings will produce different hash values! You should always use the same encoding if you intend to compare results.

The example below shows how to convert a string to bytes in the UTF-8 encoding, and then compute the SHA256 hash of it. The result is computed as a hex string as in the previous example.

In this example, we use the update() method to pass an array of bytes to be hashed. As in the previous example, we convert the binary result to a hex string.

var str = "hello world";
var converter =
  Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
    createInstance(Components.interfaces.nsIScriptableUnicodeConverter);

// we use UTF-8 here, you can choose other encodings.
converter.charset = "UTF-8";
// result is an out parameter,
// result.value will contain the array length
var result = {};
// data is an array of bytes
var data = converter.convertToByteArray(str, result);
var ch = Components.classes["@mozilla.org/security/hash;1"]
                   .createInstance(Components.interfaces.nsICryptoHash);
ch.init(ch.SHA256);
ch.update(data, data.length);
var hash = ch.finish(false);

// return the two-digit hexadecimal code for a byte
function toHexString(charCode)
{
  return ("0" + charCode.toString(16)).slice(-2);
}

// convert the binary hash data to a hex string.
var s = Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join("");
// s now contains your hash in hex: should be
// 5eb63bbbe01eeed093cb22bb8f5acdc3

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:104 次

字数:13704

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文