diff --git a/extmod/modtrezorcrypto/rand.c b/extmod/modtrezorcrypto/rand.c index 385244b4..665f311e 100644 --- a/extmod/modtrezorcrypto/rand.c +++ b/extmod/modtrezorcrypto/rand.c @@ -56,6 +56,9 @@ void random_buffer(uint8_t *buf, size_t len) void random_permute(void *buf, size_t size, size_t count) { + if (count < 1 || size < 1) { + return; + } uint8_t *d = (uint8_t *)buf; uint8_t t[size]; for (size_t i = count - 1; i >= 1; i--) { diff --git a/src/tests/test_crypto_random.py b/src/tests/test_crypto_random.py new file mode 100644 index 00000000..c8f89899 --- /dev/null +++ b/src/tests/test_crypto_random.py @@ -0,0 +1,48 @@ +import sys +sys.path.append('..') +sys.path.append('../lib') +import unittest +from ubinascii import hexlify + +from trezor.crypto import random + +class TestCryptoRandom(unittest.TestCase): + + def test_uniform(self): + c = {} + for i in range(15): + c[i] = 0 + for _ in range(15000): + r = random.uniform(15) + c[r] += 1 + for i in range(15): + self.assertTrue(c[r] > 900) + self.assertTrue(c[r] < 1100) + + def test_bytes_length(self): + for l in range(1024 + 1): + lst = random.bytes(l) + self.assertEqual(len(lst), l) + + def test_bytes_uniform(self): + for _ in range(100): + b = random.bytes(8000) + c = {} + for h in '0123456789abcdef': + c[h] = 0 + for h in hexlify(b): + c[chr(h)] += 1 + for h in '0123456789abcdef': + self.assertTrue(c[h] > 900) + self.assertTrue(c[h] < 1100) + + + def test_shuffle(self): + for l in range(256 + 1): + lst = list(range(l)) + random.shuffle(lst) + self.assertEqual(len(lst), l) + self.assertEqual(sorted(lst), list(range(l))) + +if __name__ == '__main__': + unittest.main() diff --git a/src/tests/test_crypto_sha512.py b/src/tests/test_crypto_sha512.py index 58348e4d..94ca2dfe 100644 --- a/src/tests/test_crypto_sha512.py +++ b/src/tests/test_crypto_sha512.py @@ -2,7 +2,6 @@ import sys sys.path.append('..') sys.path.append('../lib') import unittest -import trezor.utils from ubinascii import unhexlify from trezor.crypto import hashlib