Patch #934711: Expose platform-specific entropy.
diff --git a/Lib/os.py b/Lib/os.py
index 5b79981..86b3566 100644
--- a/Lib/os.py
+++ b/Lib/os.py
@@ -656,3 +656,24 @@
_make_statvfs_result)
except NameError: # statvfs_result may not exist
pass
+
+if not _exists("urandom"):
+ _urandomfd = None
+ def urandom(n):
+ """urandom(n) -> str
+
+ Return a string of n random bytes suitable for cryptographic use.
+
+ """
+ global _urandomfd
+ if not _urandomfd:
+ try:
+ _urandomfd = open("/dev/urandom", O_RDONLY)
+ except:
+ _urandomfd = NotImplementedError
+ if _urandomfd is NotImplementedError:
+ raise NotImplementedError("/dev/urandom (or equivalent) not found")
+ bytes = ""
+ while len(bytes) < n:
+ bytes += read(_urandomfd, n - len(bytes))
+ return bytes
diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py
index 22cd112..a9668aa 100644
--- a/Lib/test/test_os.py
+++ b/Lib/test/test_os.py
@@ -343,6 +343,16 @@
self.assertEqual(f.read(), '')
f.close()
+class URandomTests (unittest.TestCase):
+ def test_urandom(self):
+ try:
+ self.assertEqual(len(os.urandom(1)), 1)
+ self.assertEqual(len(os.urandom(10)), 10)
+ self.assertEqual(len(os.urandom(100)), 100)
+ self.assertEqual(len(os.urandom(1000)), 1000)
+ except NotImplementedError:
+ pass
+
def test_main():
test_support.run_unittest(
TemporaryFileTests,
@@ -351,6 +361,7 @@
WalkTests,
MakedirTests,
DevNullTests,
+ URandomTests
)
if __name__ == "__main__":