Mercurial > projects > dcrypt
diff dcrypt/crypto/macs/HMAC.d @ 27:8b5eaf3c2979
Fixed error in hash message padding reported by Glenn Haecker.
author | Thomas Dixon <reikon@reikon.us> |
---|---|
date | Sat, 09 May 2009 23:29:20 -0400 |
parents | 176c933827a8 |
children | ad687db713a4 |
line wrap: on
line diff
--- a/dcrypt/crypto/macs/HMAC.d Sun Mar 01 13:06:48 2009 -0500 +++ b/dcrypt/crypto/macs/HMAC.d Sat May 09 23:29:20 2009 -0400 @@ -13,7 +13,8 @@ import dcrypt.crypto.params.SymmetricKey; import dcrypt.crypto.errors.NotInitializedError; -debug (UnitTest) { +debug (UnitTest) +{ import dcrypt.crypto.hashes.SHA1; } @@ -23,14 +24,17 @@ * Conforms: RFC 2104 * References: http://www.faqs.org/rfcs/rfc2104.html */ -class HMAC : MAC { - private { +class HMAC : MAC +{ + private + { ubyte[] ipad, opad, key; Hash hash; bool initialized; } - this (Hash hash, void[] key=null) { + this (Hash hash, void[] key=null) + { this.hash = hash.copy(); this.hash.reset(); @@ -41,7 +45,8 @@ init(new SymmetricKey(key)); // I'm lazy. } - void init(CipherParameters params) { + void init(CipherParameters params) + { SymmetricKey keyParams = cast(SymmetricKey)params; if (!keyParams) throw new InvalidParameterError( @@ -49,7 +54,8 @@ hash.reset(); - if (keyParams.key.length > blockSize) { + if (keyParams.key.length > blockSize) + { hash.update(keyParams.key); key = hash.digest(); } else @@ -58,7 +64,8 @@ ipad[] = 0x36; opad[] = 0x5c; - foreach (uint i, ubyte j; key) { + foreach (uint i, ubyte j; key) + { ipad[i] ^= j; opad[i] ^= j; } @@ -68,44 +75,54 @@ initialized = true; } - void update(void[] input_) { + void update(void[] input_) + { if (!initialized) - throw new NotInitializedError( - name()~": MAC not initialized."); + throw new NotInitializedError(name()~": MAC not initialized."); + hash.update(input_); } - char[] name() { + char[] name() + { return "HMAC-"~hash.name; } - void reset() { + void reset() + { hash.reset(); hash.update(ipad); } - uint blockSize() { + uint blockSize() + { return hash.blockSize; } - uint macSize() { + uint macSize() + { return hash.digestSize; } - ubyte[] digest() { + ubyte[] digest() + { ubyte[] t = hash.digest(); hash.update(opad); hash.update(t); ubyte[] r = hash.digest(); + reset(); + return r; } - char[] hexDigest() { + char[] hexDigest() + { return ByteConverter.hexEncode(digest()); } - HMAC copy() { + HMAC copy() + { // Ghetto... oh so ghetto :\ HMAC h = new HMAC(hash.copy()); h.hash = hash.copy(); @@ -113,8 +130,10 @@ return h; } - debug (UnitTest) { - unittest { + debug (UnitTest) + { + unittest + { static char[][] test_keys = [ "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4a656665", // Jefe? @@ -145,7 +164,8 @@ ]; HMAC h = new HMAC(new SHA1()); - foreach (uint i, char[] k; test_keys) { + foreach (uint i, char[] k; test_keys) + { h.init(new SymmetricKey(ByteConverter.hexDecode(k))); for (int j = 0; j < test_repeat[i]; j++) h.update(ByteConverter.hexDecode(test_inputs[i]));