def testGetRandBytes(self):
     logging.debug('Running testGetRandBytes method.')
     rand1 = ccrypto.GetRandBytes(16)
     rand2 = ccrypto.GetRandBytes(16)
     self.assertTrue(isinstance(rand1, str))
     self.assertEqual(16, len(rand1))
     self.assertEqual(16, len(rand2))
     self.assertNotEqual(rand1, rand2)
    def testGetRandBytesWhenPlatformOther(self):
        logging.debug('Running testGetRandBytesWhenPlatformOther method.')

        fmock = self.mox.CreateMockAnything()
        self.stubs.Set(ccrypto, '_f_urandom_func', None)
        self.mox.StubOutWithMock(ccrypto.platform, 'uname')
        self.mox.StubOutWithMock(ccrypto.os, 'urandom')
        ccrypto.platform.uname().AndReturn(
            ['OFQv', 'h', 'v', 'x', 'x86', 'x86'])
        ccrypto.os.urandom(16).AndReturn('a' * 16)
        ccrypto.os.urandom(16).AndReturn('b' * 16)

        self.mox.ReplayAll()
        b = ccrypto.GetRandBytes(16, _open=fmock)
        self.assertEqual(len(b), 16)
        b = ccrypto.GetRandBytes(16, _open=fmock)
        self.assertEqual(len(b), 16)
        self.mox.VerifyAll()
    def testGetRandBytesWhenPlatformLinux(self):
        logging.debug('Running testGetRandBytesWhenPlatformLinux method.')

        fmock = self.mox.CreateMockAnything()
        self.stubs.Set(ccrypto, '_f_urandom_func', None)
        self.mox.StubOutWithMock(ccrypto.platform, 'uname')
        self.mox.StubOutWithMock(ccrypto.os, 'urandom')
        ccrypto.platform.uname().AndReturn(
            ['Linux', 'h', 'v', 'x', 'x86', 'x86'])
        fmock('/dev/urandom', 'rb', ccrypto._F_URANDOM_BUFLEN).AndReturn(fmock)
        fmock.read(16).AndReturn('a' * 16)
        fmock.read(16).AndReturn('b' * 16)

        self.mox.ReplayAll()
        b = ccrypto.GetRandBytes(16, _open=fmock)
        self.assertEqual(len(b), 16)
        b = ccrypto.GetRandBytes(16, _open=fmock)
        self.assertEqual(len(b), 16)
        self.mox.VerifyAll()
def _CreateAndStoreMasterKeyFile(filepath):
    """Create and return a 16 byte random key and store it in a file."""
    key = ccrypto.GetRandBytes(16)
    _SecurelyCreateFile(filepath, 0600)
    with open(filepath, 'wt') as f:
        f.write(base64.b64encode(key))