update windows build to Python 3.7
This commit is contained in:
parent
73105fa71e
commit
ddc59ab92d
5761 changed files with 750298 additions and 213405 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,189 +1,189 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# SelfTest/Random/Fortuna/test_FortunaAccumulator.py: Self-test for the FortunaAccumulator module
|
||||
#
|
||||
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""Self-tests for Crypto.Random.Fortuna.FortunaAccumulator"""
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
import sys
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
from Crypto.Util.py3compat import *
|
||||
|
||||
import unittest
|
||||
from binascii import b2a_hex
|
||||
|
||||
class FortunaAccumulatorTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
global FortunaAccumulator
|
||||
from Crypto.Random.Fortuna import FortunaAccumulator
|
||||
|
||||
def test_FortunaPool(self):
|
||||
"""FortunaAccumulator.FortunaPool"""
|
||||
pool = FortunaAccumulator.FortunaPool()
|
||||
self.assertEqual(0, pool.length)
|
||||
self.assertEqual("5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456", pool.hexdigest())
|
||||
|
||||
pool.append(b('abc'))
|
||||
|
||||
self.assertEqual(3, pool.length)
|
||||
self.assertEqual("4f8b42c22dd3729b519ba6f68d2da7cc5b2d606d05daed5ad5128cc03e6c6358", pool.hexdigest())
|
||||
|
||||
pool.append(b("dbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"))
|
||||
|
||||
self.assertEqual(56, pool.length)
|
||||
self.assertEqual(b('0cffe17f68954dac3a84fb1458bd5ec99209449749b2b308b7cb55812f9563af'), b2a_hex(pool.digest()))
|
||||
|
||||
pool.reset()
|
||||
|
||||
self.assertEqual(0, pool.length)
|
||||
|
||||
pool.append(b('a') * 10**6)
|
||||
|
||||
self.assertEqual(10**6, pool.length)
|
||||
self.assertEqual(b('80d1189477563e1b5206b2749f1afe4807e5705e8bd77887a60187a712156688'), b2a_hex(pool.digest()))
|
||||
|
||||
def test_which_pools(self):
|
||||
"""FortunaAccumulator.which_pools"""
|
||||
|
||||
# which_pools(0) should fail
|
||||
self.assertRaises(AssertionError, FortunaAccumulator.which_pools, 0)
|
||||
|
||||
self.assertEqual(FortunaAccumulator.which_pools(1), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2), [0, 1])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(3), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(4), [0, 1, 2])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(5), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(6), [0, 1])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(7), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(8), [0, 1, 2, 3])
|
||||
for i in range(1, 32):
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**i-1), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**i), list(range(i+1)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**i+1), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**31), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**32), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**33), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**34), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**35), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**36), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**64), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**128), list(range(32)))
|
||||
|
||||
def test_accumulator(self):
|
||||
"""FortunaAccumulator.FortunaAccumulator"""
|
||||
fa = FortunaAccumulator.FortunaAccumulator()
|
||||
|
||||
# This should fail, because we haven't seeded the PRNG yet
|
||||
self.assertRaises(AssertionError, fa.random_data, 1)
|
||||
|
||||
# Spread some test data across the pools (source number 42)
|
||||
# This would be horribly insecure in a real system.
|
||||
for p in range(32):
|
||||
fa.add_random_event(42, p, b("X") * 32)
|
||||
self.assertEqual(32+2, fa.pools[p].length)
|
||||
|
||||
# This should still fail, because we haven't seeded the PRNG with 64 bytes yet
|
||||
self.assertRaises(AssertionError, fa.random_data, 1)
|
||||
|
||||
# Add more data
|
||||
for p in range(32):
|
||||
fa.add_random_event(42, p, b("X") * 32)
|
||||
self.assertEqual((32+2)*2, fa.pools[p].length)
|
||||
|
||||
# The underlying RandomGenerator should get seeded with Pool 0
|
||||
# s = SHAd256(chr(42) + chr(32) + "X"*32 + chr(42) + chr(32) + "X"*32)
|
||||
# = SHA256(h'edd546f057b389155a31c32e3975e736c1dec030ddebb137014ecbfb32ed8c6f')
|
||||
# = h'aef42a5dcbddab67e8efa118e1b47fde5d697f89beb971b99e6e8e5e89fbf064'
|
||||
# The counter and the key before reseeding is:
|
||||
# C_0 = 0
|
||||
# K_0 = "\x00" * 32
|
||||
# The counter after reseeding is 1, and the new key after reseeding is
|
||||
# C_1 = 1
|
||||
# K_1 = SHAd256(K_0 || s)
|
||||
# = SHA256(h'0eae3e401389fab86640327ac919ecfcb067359d95469e18995ca889abc119a6')
|
||||
# = h'aafe9d0409fbaaafeb0a1f2ef2014a20953349d3c1c6e6e3b962953bea6184dd'
|
||||
# The first block of random data, therefore, is
|
||||
# r_1 = AES-256(K_1, 1)
|
||||
# = AES-256(K_1, h'01000000000000000000000000000000')
|
||||
# = h'b7b86bd9a27d96d7bb4add1b6b10d157'
|
||||
# The second block of random data is
|
||||
# r_2 = AES-256(K_1, 2)
|
||||
# = AES-256(K_1, h'02000000000000000000000000000000')
|
||||
# = h'2350b1c61253db2f8da233be726dc15f'
|
||||
# The third and fourth blocks of random data (which become the new key) are
|
||||
# r_3 = AES-256(K_1, 3)
|
||||
# = AES-256(K_1, h'03000000000000000000000000000000')
|
||||
# = h'f23ad749f33066ff53d307914fbf5b21'
|
||||
# r_4 = AES-256(K_1, 4)
|
||||
# = AES-256(K_1, h'04000000000000000000000000000000')
|
||||
# = h'da9667c7e86ba247655c9490e9d94a7c'
|
||||
# K_2 = r_3 || r_4
|
||||
# = h'f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c'
|
||||
# The final counter value is 5.
|
||||
self.assertEqual("aef42a5dcbddab67e8efa118e1b47fde5d697f89beb971b99e6e8e5e89fbf064",
|
||||
fa.pools[0].hexdigest())
|
||||
self.assertEqual(None, fa.generator.key)
|
||||
self.assertEqual(0, fa.generator.counter.next_value())
|
||||
|
||||
result = fa.random_data(32)
|
||||
|
||||
self.assertEqual(b("b7b86bd9a27d96d7bb4add1b6b10d157" "2350b1c61253db2f8da233be726dc15f"), b2a_hex(result))
|
||||
self.assertEqual(b("f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c"), b2a_hex(fa.generator.key))
|
||||
self.assertEqual(5, fa.generator.counter.next_value())
|
||||
|
||||
def test_accumulator_pool_length(self):
|
||||
"""FortunaAccumulator.FortunaAccumulator minimum pool length"""
|
||||
fa = FortunaAccumulator.FortunaAccumulator()
|
||||
|
||||
# This test case is hard-coded to assume that FortunaAccumulator.min_pool_size is 64.
|
||||
self.assertEqual(fa.min_pool_size, 64)
|
||||
|
||||
# The PRNG should not allow us to get random data from it yet
|
||||
self.assertRaises(AssertionError, fa.random_data, 1)
|
||||
|
||||
# Add 60 bytes, 4 at a time (2 header + 2 payload) to each of the 32 pools
|
||||
for i in range(15):
|
||||
for p in range(32):
|
||||
# Add the bytes to the pool
|
||||
fa.add_random_event(2, p, b("XX"))
|
||||
|
||||
# The PRNG should not allow us to get random data from it yet
|
||||
self.assertRaises(AssertionError, fa.random_data, 1)
|
||||
|
||||
# Add 4 more bytes to pool 0
|
||||
fa.add_random_event(2, 0, b("XX"))
|
||||
|
||||
# We should now be able to get data from the accumulator
|
||||
fa.random_data(1)
|
||||
|
||||
def get_tests(config={}):
|
||||
from Crypto.SelfTest.st_common import list_test_cases
|
||||
return list_test_cases(FortunaAccumulatorTests)
|
||||
|
||||
if __name__ == '__main__':
|
||||
suite = lambda: unittest.TestSuite(get_tests())
|
||||
unittest.main(defaultTest='suite')
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# SelfTest/Random/Fortuna/test_FortunaAccumulator.py: Self-test for the FortunaAccumulator module
|
||||
#
|
||||
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""Self-tests for Crypto.Random.Fortuna.FortunaAccumulator"""
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
import sys
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
from Crypto.Util.py3compat import *
|
||||
|
||||
import unittest
|
||||
from binascii import b2a_hex
|
||||
|
||||
class FortunaAccumulatorTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
global FortunaAccumulator
|
||||
from Crypto.Random.Fortuna import FortunaAccumulator
|
||||
|
||||
def test_FortunaPool(self):
|
||||
"""FortunaAccumulator.FortunaPool"""
|
||||
pool = FortunaAccumulator.FortunaPool()
|
||||
self.assertEqual(0, pool.length)
|
||||
self.assertEqual("5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456", pool.hexdigest())
|
||||
|
||||
pool.append(b('abc'))
|
||||
|
||||
self.assertEqual(3, pool.length)
|
||||
self.assertEqual("4f8b42c22dd3729b519ba6f68d2da7cc5b2d606d05daed5ad5128cc03e6c6358", pool.hexdigest())
|
||||
|
||||
pool.append(b("dbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"))
|
||||
|
||||
self.assertEqual(56, pool.length)
|
||||
self.assertEqual(b('0cffe17f68954dac3a84fb1458bd5ec99209449749b2b308b7cb55812f9563af'), b2a_hex(pool.digest()))
|
||||
|
||||
pool.reset()
|
||||
|
||||
self.assertEqual(0, pool.length)
|
||||
|
||||
pool.append(b('a') * 10**6)
|
||||
|
||||
self.assertEqual(10**6, pool.length)
|
||||
self.assertEqual(b('80d1189477563e1b5206b2749f1afe4807e5705e8bd77887a60187a712156688'), b2a_hex(pool.digest()))
|
||||
|
||||
def test_which_pools(self):
|
||||
"""FortunaAccumulator.which_pools"""
|
||||
|
||||
# which_pools(0) should fail
|
||||
self.assertRaises(AssertionError, FortunaAccumulator.which_pools, 0)
|
||||
|
||||
self.assertEqual(FortunaAccumulator.which_pools(1), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2), [0, 1])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(3), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(4), [0, 1, 2])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(5), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(6), [0, 1])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(7), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(8), [0, 1, 2, 3])
|
||||
for i in range(1, 32):
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**i-1), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**i), list(range(i+1)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**i+1), [0])
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**31), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**32), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**33), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**34), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**35), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**36), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**64), list(range(32)))
|
||||
self.assertEqual(FortunaAccumulator.which_pools(2**128), list(range(32)))
|
||||
|
||||
def test_accumulator(self):
|
||||
"""FortunaAccumulator.FortunaAccumulator"""
|
||||
fa = FortunaAccumulator.FortunaAccumulator()
|
||||
|
||||
# This should fail, because we haven't seeded the PRNG yet
|
||||
self.assertRaises(AssertionError, fa.random_data, 1)
|
||||
|
||||
# Spread some test data across the pools (source number 42)
|
||||
# This would be horribly insecure in a real system.
|
||||
for p in range(32):
|
||||
fa.add_random_event(42, p, b("X") * 32)
|
||||
self.assertEqual(32+2, fa.pools[p].length)
|
||||
|
||||
# This should still fail, because we haven't seeded the PRNG with 64 bytes yet
|
||||
self.assertRaises(AssertionError, fa.random_data, 1)
|
||||
|
||||
# Add more data
|
||||
for p in range(32):
|
||||
fa.add_random_event(42, p, b("X") * 32)
|
||||
self.assertEqual((32+2)*2, fa.pools[p].length)
|
||||
|
||||
# The underlying RandomGenerator should get seeded with Pool 0
|
||||
# s = SHAd256(chr(42) + chr(32) + "X"*32 + chr(42) + chr(32) + "X"*32)
|
||||
# = SHA256(h'edd546f057b389155a31c32e3975e736c1dec030ddebb137014ecbfb32ed8c6f')
|
||||
# = h'aef42a5dcbddab67e8efa118e1b47fde5d697f89beb971b99e6e8e5e89fbf064'
|
||||
# The counter and the key before reseeding is:
|
||||
# C_0 = 0
|
||||
# K_0 = "\x00" * 32
|
||||
# The counter after reseeding is 1, and the new key after reseeding is
|
||||
# C_1 = 1
|
||||
# K_1 = SHAd256(K_0 || s)
|
||||
# = SHA256(h'0eae3e401389fab86640327ac919ecfcb067359d95469e18995ca889abc119a6')
|
||||
# = h'aafe9d0409fbaaafeb0a1f2ef2014a20953349d3c1c6e6e3b962953bea6184dd'
|
||||
# The first block of random data, therefore, is
|
||||
# r_1 = AES-256(K_1, 1)
|
||||
# = AES-256(K_1, h'01000000000000000000000000000000')
|
||||
# = h'b7b86bd9a27d96d7bb4add1b6b10d157'
|
||||
# The second block of random data is
|
||||
# r_2 = AES-256(K_1, 2)
|
||||
# = AES-256(K_1, h'02000000000000000000000000000000')
|
||||
# = h'2350b1c61253db2f8da233be726dc15f'
|
||||
# The third and fourth blocks of random data (which become the new key) are
|
||||
# r_3 = AES-256(K_1, 3)
|
||||
# = AES-256(K_1, h'03000000000000000000000000000000')
|
||||
# = h'f23ad749f33066ff53d307914fbf5b21'
|
||||
# r_4 = AES-256(K_1, 4)
|
||||
# = AES-256(K_1, h'04000000000000000000000000000000')
|
||||
# = h'da9667c7e86ba247655c9490e9d94a7c'
|
||||
# K_2 = r_3 || r_4
|
||||
# = h'f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c'
|
||||
# The final counter value is 5.
|
||||
self.assertEqual("aef42a5dcbddab67e8efa118e1b47fde5d697f89beb971b99e6e8e5e89fbf064",
|
||||
fa.pools[0].hexdigest())
|
||||
self.assertEqual(None, fa.generator.key)
|
||||
self.assertEqual(0, fa.generator.counter.next_value())
|
||||
|
||||
result = fa.random_data(32)
|
||||
|
||||
self.assertEqual(b("b7b86bd9a27d96d7bb4add1b6b10d157" "2350b1c61253db2f8da233be726dc15f"), b2a_hex(result))
|
||||
self.assertEqual(b("f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c"), b2a_hex(fa.generator.key))
|
||||
self.assertEqual(5, fa.generator.counter.next_value())
|
||||
|
||||
def test_accumulator_pool_length(self):
|
||||
"""FortunaAccumulator.FortunaAccumulator minimum pool length"""
|
||||
fa = FortunaAccumulator.FortunaAccumulator()
|
||||
|
||||
# This test case is hard-coded to assume that FortunaAccumulator.min_pool_size is 64.
|
||||
self.assertEqual(fa.min_pool_size, 64)
|
||||
|
||||
# The PRNG should not allow us to get random data from it yet
|
||||
self.assertRaises(AssertionError, fa.random_data, 1)
|
||||
|
||||
# Add 60 bytes, 4 at a time (2 header + 2 payload) to each of the 32 pools
|
||||
for i in range(15):
|
||||
for p in range(32):
|
||||
# Add the bytes to the pool
|
||||
fa.add_random_event(2, p, b("XX"))
|
||||
|
||||
# The PRNG should not allow us to get random data from it yet
|
||||
self.assertRaises(AssertionError, fa.random_data, 1)
|
||||
|
||||
# Add 4 more bytes to pool 0
|
||||
fa.add_random_event(2, 0, b("XX"))
|
||||
|
||||
# We should now be able to get data from the accumulator
|
||||
fa.random_data(1)
|
||||
|
||||
def get_tests(config={}):
|
||||
from Crypto.SelfTest.st_common import list_test_cases
|
||||
return list_test_cases(FortunaAccumulatorTests)
|
||||
|
||||
if __name__ == '__main__':
|
||||
suite = lambda: unittest.TestSuite(get_tests())
|
||||
unittest.main(defaultTest='suite')
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,171 +1,171 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Self-tests for the user-friendly Crypto.Random interface
|
||||
#
|
||||
# Written in 2013 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""Self-test suite for generic Crypto.Random stuff """
|
||||
|
||||
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
import binascii
|
||||
import pprint
|
||||
import unittest
|
||||
import os
|
||||
import time
|
||||
import sys
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
from Crypto.Util.py3compat import *
|
||||
|
||||
try:
|
||||
import multiprocessing
|
||||
except ImportError:
|
||||
multiprocessing = None
|
||||
|
||||
import Crypto.Random._UserFriendlyRNG
|
||||
import Crypto.Random.random
|
||||
|
||||
class RNGForkTest(unittest.TestCase):
|
||||
|
||||
def _get_reseed_count(self):
|
||||
"""
|
||||
Get `FortunaAccumulator.reseed_count`, the global count of the
|
||||
number of times that the PRNG has been reseeded.
|
||||
"""
|
||||
rng_singleton = Crypto.Random._UserFriendlyRNG._get_singleton()
|
||||
rng_singleton._lock.acquire()
|
||||
try:
|
||||
return rng_singleton._fa.reseed_count
|
||||
finally:
|
||||
rng_singleton._lock.release()
|
||||
|
||||
def runTest(self):
|
||||
# Regression test for CVE-2013-1445. We had a bug where, under the
|
||||
# right conditions, two processes might see the same random sequence.
|
||||
|
||||
if sys.platform.startswith('win'): # windows can't fork
|
||||
assert not hasattr(os, 'fork') # ... right?
|
||||
return
|
||||
|
||||
# Wait 150 ms so that we don't trigger the rate-limit prematurely.
|
||||
time.sleep(0.15)
|
||||
|
||||
reseed_count_before = self._get_reseed_count()
|
||||
|
||||
# One or both of these calls together should trigger a reseed right here.
|
||||
Crypto.Random._UserFriendlyRNG._get_singleton().reinit()
|
||||
Crypto.Random.get_random_bytes(1)
|
||||
|
||||
reseed_count_after = self._get_reseed_count()
|
||||
self.assertNotEqual(reseed_count_before, reseed_count_after) # sanity check: test should reseed parent before forking
|
||||
|
||||
rfiles = []
|
||||
for i in range(10):
|
||||
rfd, wfd = os.pipe()
|
||||
if os.fork() == 0:
|
||||
# child
|
||||
os.close(rfd)
|
||||
f = os.fdopen(wfd, "wb")
|
||||
|
||||
Crypto.Random.atfork()
|
||||
|
||||
data = Crypto.Random.get_random_bytes(16)
|
||||
|
||||
f.write(data)
|
||||
f.close()
|
||||
os._exit(0)
|
||||
# parent
|
||||
os.close(wfd)
|
||||
rfiles.append(os.fdopen(rfd, "rb"))
|
||||
|
||||
results = []
|
||||
results_dict = {}
|
||||
for f in rfiles:
|
||||
data = binascii.hexlify(f.read())
|
||||
results.append(data)
|
||||
results_dict[data] = 1
|
||||
f.close()
|
||||
|
||||
if len(results) != len(list(results_dict.keys())):
|
||||
raise AssertionError("RNG output duplicated across fork():\n%s" %
|
||||
(pprint.pformat(results)))
|
||||
|
||||
|
||||
# For RNGMultiprocessingForkTest
|
||||
def _task_main(q):
|
||||
a = Crypto.Random.get_random_bytes(16)
|
||||
time.sleep(0.1) # wait 100 ms
|
||||
b = Crypto.Random.get_random_bytes(16)
|
||||
q.put(binascii.b2a_hex(a))
|
||||
q.put(binascii.b2a_hex(b))
|
||||
q.put(None) # Wait for acknowledgment
|
||||
|
||||
|
||||
class RNGMultiprocessingForkTest(unittest.TestCase):
|
||||
|
||||
def runTest(self):
|
||||
# Another regression test for CVE-2013-1445. This is basically the
|
||||
# same as RNGForkTest, but less compatible with old versions of Python,
|
||||
# and a little easier to read.
|
||||
|
||||
n_procs = 5
|
||||
manager = multiprocessing.Manager()
|
||||
queues = [manager.Queue(1) for i in range(n_procs)]
|
||||
|
||||
# Reseed the pool
|
||||
time.sleep(0.15)
|
||||
Crypto.Random._UserFriendlyRNG._get_singleton().reinit()
|
||||
Crypto.Random.get_random_bytes(1)
|
||||
|
||||
# Start the child processes
|
||||
pool = multiprocessing.Pool(processes=n_procs, initializer=Crypto.Random.atfork)
|
||||
map_result = pool.map_async(_task_main, queues)
|
||||
|
||||
# Get the results, ensuring that no pool processes are reused.
|
||||
aa = [queues[i].get(30) for i in range(n_procs)]
|
||||
bb = [queues[i].get(30) for i in range(n_procs)]
|
||||
res = list(zip(aa, bb))
|
||||
|
||||
# Shut down the pool
|
||||
map_result.get(30)
|
||||
pool.close()
|
||||
pool.join()
|
||||
|
||||
# Check that the results are unique
|
||||
if len(set(aa)) != len(aa) or len(set(res)) != len(res):
|
||||
raise AssertionError("RNG output duplicated across fork():\n%s" %
|
||||
(pprint.pformat(res),))
|
||||
|
||||
|
||||
def get_tests(config={}):
|
||||
tests = []
|
||||
tests += [RNGForkTest()]
|
||||
if multiprocessing is not None:
|
||||
tests += [RNGMultiprocessingForkTest()]
|
||||
return tests
|
||||
|
||||
if __name__ == '__main__':
|
||||
suite = lambda: unittest.TestSuite(get_tests())
|
||||
unittest.main(defaultTest='suite')
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
# -*- coding: utf-8 -*-
|
||||
# Self-tests for the user-friendly Crypto.Random interface
|
||||
#
|
||||
# Written in 2013 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""Self-test suite for generic Crypto.Random stuff """
|
||||
|
||||
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
import binascii
|
||||
import pprint
|
||||
import unittest
|
||||
import os
|
||||
import time
|
||||
import sys
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
from Crypto.Util.py3compat import *
|
||||
|
||||
try:
|
||||
import multiprocessing
|
||||
except ImportError:
|
||||
multiprocessing = None
|
||||
|
||||
import Crypto.Random._UserFriendlyRNG
|
||||
import Crypto.Random.random
|
||||
|
||||
class RNGForkTest(unittest.TestCase):
|
||||
|
||||
def _get_reseed_count(self):
|
||||
"""
|
||||
Get `FortunaAccumulator.reseed_count`, the global count of the
|
||||
number of times that the PRNG has been reseeded.
|
||||
"""
|
||||
rng_singleton = Crypto.Random._UserFriendlyRNG._get_singleton()
|
||||
rng_singleton._lock.acquire()
|
||||
try:
|
||||
return rng_singleton._fa.reseed_count
|
||||
finally:
|
||||
rng_singleton._lock.release()
|
||||
|
||||
def runTest(self):
|
||||
# Regression test for CVE-2013-1445. We had a bug where, under the
|
||||
# right conditions, two processes might see the same random sequence.
|
||||
|
||||
if sys.platform.startswith('win'): # windows can't fork
|
||||
assert not hasattr(os, 'fork') # ... right?
|
||||
return
|
||||
|
||||
# Wait 150 ms so that we don't trigger the rate-limit prematurely.
|
||||
time.sleep(0.15)
|
||||
|
||||
reseed_count_before = self._get_reseed_count()
|
||||
|
||||
# One or both of these calls together should trigger a reseed right here.
|
||||
Crypto.Random._UserFriendlyRNG._get_singleton().reinit()
|
||||
Crypto.Random.get_random_bytes(1)
|
||||
|
||||
reseed_count_after = self._get_reseed_count()
|
||||
self.assertNotEqual(reseed_count_before, reseed_count_after) # sanity check: test should reseed parent before forking
|
||||
|
||||
rfiles = []
|
||||
for i in range(10):
|
||||
rfd, wfd = os.pipe()
|
||||
if os.fork() == 0:
|
||||
# child
|
||||
os.close(rfd)
|
||||
f = os.fdopen(wfd, "wb")
|
||||
|
||||
Crypto.Random.atfork()
|
||||
|
||||
data = Crypto.Random.get_random_bytes(16)
|
||||
|
||||
f.write(data)
|
||||
f.close()
|
||||
os._exit(0)
|
||||
# parent
|
||||
os.close(wfd)
|
||||
rfiles.append(os.fdopen(rfd, "rb"))
|
||||
|
||||
results = []
|
||||
results_dict = {}
|
||||
for f in rfiles:
|
||||
data = binascii.hexlify(f.read())
|
||||
results.append(data)
|
||||
results_dict[data] = 1
|
||||
f.close()
|
||||
|
||||
if len(results) != len(list(results_dict.keys())):
|
||||
raise AssertionError("RNG output duplicated across fork():\n%s" %
|
||||
(pprint.pformat(results)))
|
||||
|
||||
|
||||
# For RNGMultiprocessingForkTest
|
||||
def _task_main(q):
|
||||
a = Crypto.Random.get_random_bytes(16)
|
||||
time.sleep(0.1) # wait 100 ms
|
||||
b = Crypto.Random.get_random_bytes(16)
|
||||
q.put(binascii.b2a_hex(a))
|
||||
q.put(binascii.b2a_hex(b))
|
||||
q.put(None) # Wait for acknowledgment
|
||||
|
||||
|
||||
class RNGMultiprocessingForkTest(unittest.TestCase):
|
||||
|
||||
def runTest(self):
|
||||
# Another regression test for CVE-2013-1445. This is basically the
|
||||
# same as RNGForkTest, but less compatible with old versions of Python,
|
||||
# and a little easier to read.
|
||||
|
||||
n_procs = 5
|
||||
manager = multiprocessing.Manager()
|
||||
queues = [manager.Queue(1) for i in range(n_procs)]
|
||||
|
||||
# Reseed the pool
|
||||
time.sleep(0.15)
|
||||
Crypto.Random._UserFriendlyRNG._get_singleton().reinit()
|
||||
Crypto.Random.get_random_bytes(1)
|
||||
|
||||
# Start the child processes
|
||||
pool = multiprocessing.Pool(processes=n_procs, initializer=Crypto.Random.atfork)
|
||||
map_result = pool.map_async(_task_main, queues)
|
||||
|
||||
# Get the results, ensuring that no pool processes are reused.
|
||||
aa = [queues[i].get(30) for i in range(n_procs)]
|
||||
bb = [queues[i].get(30) for i in range(n_procs)]
|
||||
res = list(zip(aa, bb))
|
||||
|
||||
# Shut down the pool
|
||||
map_result.get(30)
|
||||
pool.close()
|
||||
pool.join()
|
||||
|
||||
# Check that the results are unique
|
||||
if len(set(aa)) != len(aa) or len(set(res)) != len(res):
|
||||
raise AssertionError("RNG output duplicated across fork():\n%s" %
|
||||
(pprint.pformat(res),))
|
||||
|
||||
|
||||
def get_tests(config={}):
|
||||
tests = []
|
||||
tests += [RNGForkTest()]
|
||||
if multiprocessing is not None:
|
||||
tests += [RNGMultiprocessingForkTest()]
|
||||
return tests
|
||||
|
||||
if __name__ == '__main__':
|
||||
suite = lambda: unittest.TestSuite(get_tests())
|
||||
unittest.main(defaultTest='suite')
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
|
|
|
|||
|
|
@ -1,171 +1,171 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# SelfTest/Util/test_generic.py: Self-test for the Crypto.Random.new() function
|
||||
#
|
||||
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""Self-test suite for Crypto.Random.new()"""
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
import unittest
|
||||
import sys
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
from Crypto.Util.py3compat import *
|
||||
|
||||
class SimpleTest(unittest.TestCase):
|
||||
def runTest(self):
|
||||
"""Crypto.Random.new()"""
|
||||
# Import the Random module and try to use it
|
||||
from Crypto import Random
|
||||
randobj = Random.new()
|
||||
x = randobj.read(16)
|
||||
y = randobj.read(16)
|
||||
self.assertNotEqual(x, y)
|
||||
z = Random.get_random_bytes(16)
|
||||
self.assertNotEqual(x, z)
|
||||
self.assertNotEqual(y, z)
|
||||
# Test the Random.random module, which
|
||||
# implements a subset of Python's random API
|
||||
# Not implemented:
|
||||
# seed(), getstate(), setstate(), jumpahead()
|
||||
# random(), uniform(), triangular(), betavariate()
|
||||
# expovariate(), gammavariate(), gauss(),
|
||||
# longnormvariate(), normalvariate(),
|
||||
# vonmisesvariate(), paretovariate()
|
||||
# weibullvariate()
|
||||
# WichmannHill(), whseed(), SystemRandom()
|
||||
from Crypto.Random import random
|
||||
x = random.getrandbits(16*8)
|
||||
y = random.getrandbits(16*8)
|
||||
self.assertNotEqual(x, y)
|
||||
# Test randrange
|
||||
if x>y:
|
||||
start = y
|
||||
stop = x
|
||||
else:
|
||||
start = x
|
||||
stop = y
|
||||
for step in range(1,10):
|
||||
x = random.randrange(start,stop,step)
|
||||
y = random.randrange(start,stop,step)
|
||||
self.assertNotEqual(x, y)
|
||||
self.assertEqual(start <= x < stop, True)
|
||||
self.assertEqual(start <= y < stop, True)
|
||||
self.assertEqual((x - start) % step, 0)
|
||||
self.assertEqual((y - start) % step, 0)
|
||||
for i in range(10):
|
||||
self.assertEqual(random.randrange(1,2), 1)
|
||||
self.assertRaises(ValueError, random.randrange, start, start)
|
||||
self.assertRaises(ValueError, random.randrange, stop, start, step)
|
||||
self.assertRaises(TypeError, random.randrange, start, stop, step, step)
|
||||
self.assertRaises(TypeError, random.randrange, start, stop, "1")
|
||||
self.assertRaises(TypeError, random.randrange, "1", stop, step)
|
||||
self.assertRaises(TypeError, random.randrange, 1, "2", step)
|
||||
self.assertRaises(ValueError, random.randrange, start, stop, 0)
|
||||
# Test randint
|
||||
x = random.randint(start,stop)
|
||||
y = random.randint(start,stop)
|
||||
self.assertNotEqual(x, y)
|
||||
self.assertEqual(start <= x <= stop, True)
|
||||
self.assertEqual(start <= y <= stop, True)
|
||||
for i in range(10):
|
||||
self.assertEqual(random.randint(1,1), 1)
|
||||
self.assertRaises(ValueError, random.randint, stop, start)
|
||||
self.assertRaises(TypeError, random.randint, start, stop, step)
|
||||
self.assertRaises(TypeError, random.randint, "1", stop)
|
||||
self.assertRaises(TypeError, random.randint, 1, "2")
|
||||
# Test choice
|
||||
seq = list(range(10000))
|
||||
x = random.choice(seq)
|
||||
y = random.choice(seq)
|
||||
self.assertNotEqual(x, y)
|
||||
self.assertEqual(x in seq, True)
|
||||
self.assertEqual(y in seq, True)
|
||||
for i in range(10):
|
||||
self.assertEqual(random.choice((1,2,3)) in (1,2,3), True)
|
||||
self.assertEqual(random.choice([1,2,3]) in [1,2,3], True)
|
||||
if sys.version_info[0] is 3:
|
||||
self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True)
|
||||
self.assertEqual(1, random.choice([1]))
|
||||
self.assertRaises(IndexError, random.choice, [])
|
||||
self.assertRaises(TypeError, random.choice, 1)
|
||||
# Test shuffle. Lacks random parameter to specify function.
|
||||
# Make copies of seq
|
||||
seq = list(range(500))
|
||||
x = list(seq)
|
||||
y = list(seq)
|
||||
random.shuffle(x)
|
||||
random.shuffle(y)
|
||||
self.assertNotEqual(x, y)
|
||||
self.assertEqual(len(seq), len(x))
|
||||
self.assertEqual(len(seq), len(y))
|
||||
for i in range(len(seq)):
|
||||
self.assertEqual(x[i] in seq, True)
|
||||
self.assertEqual(y[i] in seq, True)
|
||||
self.assertEqual(seq[i] in x, True)
|
||||
self.assertEqual(seq[i] in y, True)
|
||||
z = [1]
|
||||
random.shuffle(z)
|
||||
self.assertEqual(z, [1])
|
||||
if sys.version_info[0] == 3:
|
||||
z = bytearray(b('12'))
|
||||
random.shuffle(z)
|
||||
self.assertEqual(b('1') in z, True)
|
||||
self.assertRaises(TypeError, random.shuffle, b('12'))
|
||||
self.assertRaises(TypeError, random.shuffle, 1)
|
||||
self.assertRaises(TypeError, random.shuffle, "1")
|
||||
self.assertRaises(TypeError, random.shuffle, (1,2))
|
||||
# 2to3 wraps a list() around it, alas - but I want to shoot
|
||||
# myself in the foot here! :D
|
||||
# if sys.version_info[0] == 3:
|
||||
# self.assertRaises(TypeError, random.shuffle, range(3))
|
||||
# Test sample
|
||||
x = random.sample(seq, 20)
|
||||
y = random.sample(seq, 20)
|
||||
self.assertNotEqual(x, y)
|
||||
for i in range(20):
|
||||
self.assertEqual(x[i] in seq, True)
|
||||
self.assertEqual(y[i] in seq, True)
|
||||
z = random.sample([1], 1)
|
||||
self.assertEqual(z, [1])
|
||||
z = random.sample((1,2,3), 1)
|
||||
self.assertEqual(z[0] in (1,2,3), True)
|
||||
z = random.sample("123", 1)
|
||||
self.assertEqual(z[0] in "123", True)
|
||||
z = random.sample(list(range(3)), 1)
|
||||
self.assertEqual(z[0] in range(3), True)
|
||||
if sys.version_info[0] == 3:
|
||||
z = random.sample(b("123"), 1)
|
||||
self.assertEqual(z[0] in b("123"), True)
|
||||
z = random.sample(bytearray(b("123")), 1)
|
||||
self.assertEqual(z[0] in bytearray(b("123")), True)
|
||||
self.assertRaises(TypeError, random.sample, 1)
|
||||
|
||||
def get_tests(config={}):
|
||||
return [SimpleTest()]
|
||||
|
||||
if __name__ == '__main__':
|
||||
suite = lambda: unittest.TestSuite(get_tests())
|
||||
unittest.main(defaultTest='suite')
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# SelfTest/Util/test_generic.py: Self-test for the Crypto.Random.new() function
|
||||
#
|
||||
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
||||
#
|
||||
# ===================================================================
|
||||
# The contents of this file are dedicated to the public domain. To
|
||||
# the extent that dedication to the public domain is not available,
|
||||
# everyone is granted a worldwide, perpetual, royalty-free,
|
||||
# non-exclusive license to exercise all rights associated with the
|
||||
# contents of this file for any purpose whatsoever.
|
||||
# No rights are reserved.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
# ===================================================================
|
||||
|
||||
"""Self-test suite for Crypto.Random.new()"""
|
||||
|
||||
__revision__ = "$Id$"
|
||||
|
||||
import unittest
|
||||
import sys
|
||||
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
|
||||
from Crypto.Util.py21compat import *
|
||||
from Crypto.Util.py3compat import *
|
||||
|
||||
class SimpleTest(unittest.TestCase):
|
||||
def runTest(self):
|
||||
"""Crypto.Random.new()"""
|
||||
# Import the Random module and try to use it
|
||||
from Crypto import Random
|
||||
randobj = Random.new()
|
||||
x = randobj.read(16)
|
||||
y = randobj.read(16)
|
||||
self.assertNotEqual(x, y)
|
||||
z = Random.get_random_bytes(16)
|
||||
self.assertNotEqual(x, z)
|
||||
self.assertNotEqual(y, z)
|
||||
# Test the Random.random module, which
|
||||
# implements a subset of Python's random API
|
||||
# Not implemented:
|
||||
# seed(), getstate(), setstate(), jumpahead()
|
||||
# random(), uniform(), triangular(), betavariate()
|
||||
# expovariate(), gammavariate(), gauss(),
|
||||
# longnormvariate(), normalvariate(),
|
||||
# vonmisesvariate(), paretovariate()
|
||||
# weibullvariate()
|
||||
# WichmannHill(), whseed(), SystemRandom()
|
||||
from Crypto.Random import random
|
||||
x = random.getrandbits(16*8)
|
||||
y = random.getrandbits(16*8)
|
||||
self.assertNotEqual(x, y)
|
||||
# Test randrange
|
||||
if x>y:
|
||||
start = y
|
||||
stop = x
|
||||
else:
|
||||
start = x
|
||||
stop = y
|
||||
for step in range(1,10):
|
||||
x = random.randrange(start,stop,step)
|
||||
y = random.randrange(start,stop,step)
|
||||
self.assertNotEqual(x, y)
|
||||
self.assertEqual(start <= x < stop, True)
|
||||
self.assertEqual(start <= y < stop, True)
|
||||
self.assertEqual((x - start) % step, 0)
|
||||
self.assertEqual((y - start) % step, 0)
|
||||
for i in range(10):
|
||||
self.assertEqual(random.randrange(1,2), 1)
|
||||
self.assertRaises(ValueError, random.randrange, start, start)
|
||||
self.assertRaises(ValueError, random.randrange, stop, start, step)
|
||||
self.assertRaises(TypeError, random.randrange, start, stop, step, step)
|
||||
self.assertRaises(TypeError, random.randrange, start, stop, "1")
|
||||
self.assertRaises(TypeError, random.randrange, "1", stop, step)
|
||||
self.assertRaises(TypeError, random.randrange, 1, "2", step)
|
||||
self.assertRaises(ValueError, random.randrange, start, stop, 0)
|
||||
# Test randint
|
||||
x = random.randint(start,stop)
|
||||
y = random.randint(start,stop)
|
||||
self.assertNotEqual(x, y)
|
||||
self.assertEqual(start <= x <= stop, True)
|
||||
self.assertEqual(start <= y <= stop, True)
|
||||
for i in range(10):
|
||||
self.assertEqual(random.randint(1,1), 1)
|
||||
self.assertRaises(ValueError, random.randint, stop, start)
|
||||
self.assertRaises(TypeError, random.randint, start, stop, step)
|
||||
self.assertRaises(TypeError, random.randint, "1", stop)
|
||||
self.assertRaises(TypeError, random.randint, 1, "2")
|
||||
# Test choice
|
||||
seq = list(range(10000))
|
||||
x = random.choice(seq)
|
||||
y = random.choice(seq)
|
||||
self.assertNotEqual(x, y)
|
||||
self.assertEqual(x in seq, True)
|
||||
self.assertEqual(y in seq, True)
|
||||
for i in range(10):
|
||||
self.assertEqual(random.choice((1,2,3)) in (1,2,3), True)
|
||||
self.assertEqual(random.choice([1,2,3]) in [1,2,3], True)
|
||||
if sys.version_info[0] is 3:
|
||||
self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True)
|
||||
self.assertEqual(1, random.choice([1]))
|
||||
self.assertRaises(IndexError, random.choice, [])
|
||||
self.assertRaises(TypeError, random.choice, 1)
|
||||
# Test shuffle. Lacks random parameter to specify function.
|
||||
# Make copies of seq
|
||||
seq = list(range(500))
|
||||
x = list(seq)
|
||||
y = list(seq)
|
||||
random.shuffle(x)
|
||||
random.shuffle(y)
|
||||
self.assertNotEqual(x, y)
|
||||
self.assertEqual(len(seq), len(x))
|
||||
self.assertEqual(len(seq), len(y))
|
||||
for i in range(len(seq)):
|
||||
self.assertEqual(x[i] in seq, True)
|
||||
self.assertEqual(y[i] in seq, True)
|
||||
self.assertEqual(seq[i] in x, True)
|
||||
self.assertEqual(seq[i] in y, True)
|
||||
z = [1]
|
||||
random.shuffle(z)
|
||||
self.assertEqual(z, [1])
|
||||
if sys.version_info[0] == 3:
|
||||
z = bytearray(b('12'))
|
||||
random.shuffle(z)
|
||||
self.assertEqual(b('1') in z, True)
|
||||
self.assertRaises(TypeError, random.shuffle, b('12'))
|
||||
self.assertRaises(TypeError, random.shuffle, 1)
|
||||
self.assertRaises(TypeError, random.shuffle, "1")
|
||||
self.assertRaises(TypeError, random.shuffle, (1,2))
|
||||
# 2to3 wraps a list() around it, alas - but I want to shoot
|
||||
# myself in the foot here! :D
|
||||
# if sys.version_info[0] == 3:
|
||||
# self.assertRaises(TypeError, random.shuffle, range(3))
|
||||
# Test sample
|
||||
x = random.sample(seq, 20)
|
||||
y = random.sample(seq, 20)
|
||||
self.assertNotEqual(x, y)
|
||||
for i in range(20):
|
||||
self.assertEqual(x[i] in seq, True)
|
||||
self.assertEqual(y[i] in seq, True)
|
||||
z = random.sample([1], 1)
|
||||
self.assertEqual(z, [1])
|
||||
z = random.sample((1,2,3), 1)
|
||||
self.assertEqual(z[0] in (1,2,3), True)
|
||||
z = random.sample("123", 1)
|
||||
self.assertEqual(z[0] in "123", True)
|
||||
z = random.sample(list(range(3)), 1)
|
||||
self.assertEqual(z[0] in range(3), True)
|
||||
if sys.version_info[0] == 3:
|
||||
z = random.sample(b("123"), 1)
|
||||
self.assertEqual(z[0] in b("123"), True)
|
||||
z = random.sample(bytearray(b("123")), 1)
|
||||
self.assertEqual(z[0] in bytearray(b("123")), True)
|
||||
self.assertRaises(TypeError, random.sample, 1)
|
||||
|
||||
def get_tests(config={}):
|
||||
return [SimpleTest()]
|
||||
|
||||
if __name__ == '__main__':
|
||||
suite = lambda: unittest.TestSuite(get_tests())
|
||||
unittest.main(defaultTest='suite')
|
||||
|
||||
# vim:set ts=4 sw=4 sts=4 expandtab:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue