Package viff :: Module prss :: Class PRF
[hide private]
[frames] | no frames]

Class PRF

source code

Models a pseudo random function (a PRF).

The numbers are based on a SHA1 hash of the initial key.

Each PRF is created based on a key (which should be random and secret) and a maximum (which may be public):

>>> f = PRF("some random key", 256)

Calling f return values between zero and the given maximum:

>>> f(1)
>>> f(2)
>>> f(3)
Instance Methods [hide private]
__init__(self, key, max)
Create a PRF keyed with the given key and max.
source code
__call__(self, input)
Return a number based on input.
source code

Inherited from object: __delattr__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __str__

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, key, max)

source code 

Create a PRF keyed with the given key and max.

The key must be a string whereas the max must be a number. Output value will be in the range zero to max, with zero included and max excluded.

To make a PRF what generates numbers less than 1000 do:

>>> f = PRF("key", 1000)

The PRF can be evaluated by calling it on some input:

>>> f("input")

Creating another PRF with the same key gives identical results since f and g are deterministic functions, depending only on the key:

>>> g = PRF("key", 1000)
>>> g("input")

We can test that f and g behave the same on many inputs:

>>> [f(i) for i in range(100)] == [g(i) for i in range(100)]

Both the key and the max is used when the PRF is keyed. This means that

>>> f = PRF("key", 1000)
>>> g = PRF("key", 10000)
>>> [f(i) for i in range(100)] == [g(i) for i in range(100)]
Overrides: object.__init__

__call__(self, input)
(Call operator)

source code 

Return a number based on input.

If the input is not already a string, it is hashed (using the normal Python hash built-in) and the hash value is used instead. The hash value is a 32 bit value, so a string should be given if one wants to evaluate the PRF on more that 2**32 different values.

>>> prf = PRF("key", 1000)
>>> prf(1), prf(2), prf(3)
(501L, 432L, 133L)

Since prf is a function we can of course evaluate the same input to get the same output:

>>> prf(1)

The prf can take arbitrary input:

>>> prf(("input", 123))

Non-string input will be converted with str, which means that the input must have a deterministic __str__ method. This means that hashable instances are probably best.