Mercurial > projects > dcrypt
view dcrypt/crypto/prngs/PRNGFromHash.d @ 16:703901987976
Removed default of SHA256 for PRNGFromHash.
author | Thomas Dixon <reikon@reikon.us> |
---|---|
date | Wed, 19 Nov 2008 19:44:44 -0500 |
parents | 5ce3012f1def |
children | 8b5eaf3c2979 |
line wrap: on
line source
/** * This file is part of the dcrypt project. * * Copyright: Copyright (C) dcrypt contributors 2008. All rights reserved. * License: MIT * Authors: Thomas Dixon */ module dcrypt.crypto.prngs.PRNGFromHash; import dcrypt.crypto.PRNG; import dcrypt.crypto.Hash; /** Creates a PRNG from a hash function. */ class PRNGFromHash : PRNG { private { const uint COUNTER_SIZE = 32; Hash hash; ubyte[] counter, seed, state; uint index; } char[] name() { if (hash is null) throw new NotInitializedError(name()~": PRNG not initialized"); return hash.name~"PRNG"; } this(Hash hash) { if (hash is null) throw new InvalidParameterError( name()~": Invalid parameter passed to constructor."); this.hash = hash; this.hash.reset(); counter = new ubyte[COUNTER_SIZE]; seed = new ubyte[this.hash.digestSize]; state = new ubyte[this.hash.digestSize]; index = this.hash.digestSize; // to force updating of the state } void addEntropy(ubyte[] input) { if (!_initialized) { hash.update(input); seed = hash.digest(); _initialized = true; } else throw new NotSupportedError(name()~": state is immutable once initialized"); } uint read(ubyte[] output) { if (!_initialized) throw new NotInitializedError(name()~": PRNG not initialized"); for (uint i = 0; i < output.length; i++) { if (index == state.length) { hash.update(seed); hash.update(counter); state = hash.digest(); // Increment the counter for (uint j = COUNTER_SIZE-1; j >= 0; j--) if (++counter[j]) break; index = 0; } output[i] = state[index++]; } return output.length; } }