Python Crypto.Random.new() Examples

The following are 30 code examples of Crypto.Random.new(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Crypto.Random , or try the search function .
Example #1
Source File: crypto.py    From Python-Scripts with GNU General Public License v3.0 6 votes vote down vote up
def decrypt(key, filename):
	chunksize = 64 * 1024
	outputFile = filename.split('.hacklab')[0]


	with open(filename, 'rb') as infile:
		filesize = int(infile.read(16))
		IV = infile.read(16)
		decryptor = AES.new(key, AES.MODE_CBC, IV)

		with open(outputFile, 'wb') as outfile:

			while True:
				chunk = infile.read(chunksize)

				if len(chunk) == 0:
					break

				chunk = str(decryptor.decrypt(chunk))
				chunk = chunk.replace("0000hack1lab0000", "")
				outfile.write(chunk)
			outfile.truncate(filesize) 
Example #2
Source File: Encryption.py    From vault with MIT License 6 votes vote down vote up
def encrypt(self, secret):
        """
            Encrypt a secret
        """

        # generate IV
        IV = CryptoRandom.new().read(AES.block_size)

        # Retrieve AES instance
        aes = self.get_aes(IV)

        # calculate needed padding
        padding = AES.block_size - len(secret) % AES.block_size

        # Python 2.x: secret += chr(padding) * padding
        secret += bytes([padding]) * padding

        # store the IV at the beginning and encrypt
        data = IV + aes.encrypt(secret)

        # Reset salted key
        self.set_salt()

        # Return base 64 encoded bytes
        return base64.b64encode(data) 
Example #3
Source File: test_pkcs1_15.py    From earthengine with MIT License 6 votes vote down vote up
def testVerify1(self):
                for i in range(len(self._testData)):
                        row = self._testData[i]
                        # Build the key
                        if isStr(row[0]):
                                key = RSA.importKey(row[0]).publickey()
                        else:
                                comps = [ long(rws(row[0][x]),16) for x in ('n','e') ]
                                key = RSA.construct(comps)
                        h = row[3].new()
                        # Data to sign can either be in hex form or not
                        try:
                            h.update(t2b(row[1]))
                        except:
                            h.update(b(row[1]))
                        # The real test
                        verifier = PKCS.new(key)
                        self.failIf(verifier.can_sign())
                        result = verifier.verify(h, t2b(row[2]))
                        self.failUnless(result) 
Example #4
Source File: test_pkcs1_15.py    From earthengine with MIT License 6 votes vote down vote up
def testSign1(self):
                for i in range(len(self._testData)):
                        row = self._testData[i]
                        # Build the key
                        if isStr(row[0]):
                                key = RSA.importKey(row[0])
                        else:
                                comps = [ long(rws(row[0][x]),16) for x in ('n','e','d') ]
                                key = RSA.construct(comps)
                        h = row[3].new()
                        # Data to sign can either be in hex form or not
                        try:
                            h.update(t2b(row[1]))
                        except:
                            h.update(b(row[1]))
                        # The real test
                        signer = PKCS.new(key)
                        self.failUnless(signer.can_sign())
                        s = signer.sign(h)
                        self.assertEqual(s, t2b(row[2])) 
Example #5
Source File: AllOrNothing.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, ciphermodule, mode=None, IV=None):
        """AllOrNothing(ciphermodule, mode=None, IV=None)

        ciphermodule is a module implementing the cipher algorithm to
        use.  It must provide the PEP272 interface.

        Note that the encryption key is randomly generated
        automatically when needed.  Optional arguments mode and IV are
        passed directly through to the ciphermodule.new() method; they
        are the feedback mode and initialization vector to use.  All
        three arguments must be the same for the object used to create
        the digest, and to undigest'ify the message blocks.
        """

        self.__ciphermodule = ciphermodule
        self.__mode = mode
        self.__IV = IV
        self.__key_size = ciphermodule.key_size
        if not isInt(self.__key_size) or self.__key_size==0:
            self.__key_size = 16 
Example #6
Source File: test_pkcs1_15.py    From earthengine with MIT License 6 votes vote down vote up
def testEncrypt1(self):
                for test in self._testData:
                        # Build the key
                        key = RSA.importKey(test[0])
                        # RNG that takes its random numbers from a pool given
                        # at initialization
                        class randGen:
                            def __init__(self, data):
                                self.data = data
                                self.idx = 0
                            def __call__(self, N):
                                r = self.data[self.idx:N]
                                self.idx += N
                                return r
                        # The real test
                        key._randfunc = randGen(t2b(test[3]))
                        cipher = PKCS.new(key)
                        ct = cipher.encrypt(b(test[1]))
                        self.assertEqual(ct, t2b(test[2])) 
Example #7
Source File: test_pkcs1_pss.py    From earthengine with MIT License 6 votes vote down vote up
def testVerify1(self):
               for i in range(len(self._testData)):
                        # Build the key
                        comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e') ]
                        key = MyKey(RSA.construct(comps))
                        # Hash function
                        h = self._testData[i][4].new()
                        # Data to sign
                        h.update(t2b(self._testData[i][1]))
                        # Salt
                        test_salt = t2b(self._testData[i][3])
                        # The real test
                        key._randfunc = lambda N: test_salt
                        verifier = PKCS.new(key)
                        self.failIf(verifier.can_sign())
                        result = verifier.verify(h, t2b(self._testData[i][2]))
                        self.failUnless(result) 
Example #8
Source File: test_pkcs1_pss.py    From earthengine with MIT License 6 votes vote down vote up
def testSign1(self):
                for i in range(len(self._testData)):
                        # Build the key
                        comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e','d') ]
                        key = MyKey(RSA.construct(comps))
                        # Hash function
                        h = self._testData[i][4].new()
                        # Data to sign
                        h.update(t2b(self._testData[i][1]))
                        # Salt
                        test_salt = t2b(self._testData[i][3])
                        key._randfunc = lambda N: test_salt
                        # The real test
                        signer = PKCS.new(key)
                        self.failUnless(signer.can_sign())
                        s = signer.sign(h)
                        self.assertEqual(s, t2b(self._testData[i][2])) 
Example #9
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 6 votes vote down vote up
def testEncryptDecrypt1(self):
                # Helper function to monitor what's requested from RNG
                global asked
                def localRng(N):
                    global asked
                    asked += N
                    return self.rng(N)
                # Verify that OAEP is friendly to all hashes
                for hashmod in (MD2,MD5,SHA1,SHA256,RIPEMD):
                    # Verify that encrypt() asks for as many random bytes
                    # as the hash output size
                    asked = 0
                    pt = self.rng(40)
                    self.key1024._randfunc = localRng
                    cipher = PKCS.new(self.key1024, hashmod)
                    ct = cipher.encrypt(pt)
                    self.assertEqual(cipher.decrypt(ct), pt)
                    self.failUnless(asked > hashmod.digest_size) 
Example #10
Source File: credentials.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
def encrypt_credential(raw):
    """
    Encodes data

    :param data: Data to be encoded
    :type data: str
    :returns:  string -- Encoded data
    """
    # pylint: disable=invalid-name,import-error
    import base64
    try:  # The crypto package depends on the library installed (see Wiki)
        from Crypto import Random
        from Crypto.Cipher import AES
        from Crypto.Util import Padding
    except ImportError:
        from Cryptodome import Random
        from Cryptodome.Cipher import AES
        from Cryptodome.Util import Padding
    raw = bytes(Padding.pad(data_to_pad=raw.encode('utf-8'), block_size=__BLOCK_SIZE__))
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(get_crypt_key(), AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') 
Example #11
Source File: credentials.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
def decrypt_credential(enc, secret=None):
    """
    Decodes data

    :param data: Data to be decoded
    :type data: str
    :returns:  string -- Decoded data
    """
    # pylint: disable=invalid-name,import-error
    import base64
    try:  # The crypto package depends on the library installed (see Wiki)
        from Crypto.Cipher import AES
        from Crypto.Util import Padding
    except ImportError:
        from Cryptodome.Cipher import AES
        from Cryptodome.Util import Padding
    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(secret or get_crypt_key(), AES.MODE_CBC, iv)
    decoded = Padding.unpad(
        padded_data=cipher.decrypt(enc[AES.block_size:]),
        block_size=__BLOCK_SIZE__)
    return decoded 
Example #12
Source File: backblazeb2.py    From backblaze-b2 with MIT License 6 votes vote down vote up
def calc_encryption_sha_and_length(in_file, password, salt, key_length, key,
                                   iv):
    bs = AES.block_size
    size = 0
    cipher = AES.new(key, AES.MODE_CBC, iv)
    sha = hashlib.sha1()
    sha.update('Salted__' + salt)
    size += len('Salted__' + salt)
    finished = False
    while not finished:
        chunk = in_file.read(1024 * bs)
        if len(chunk) == 0 or len(chunk) % bs != 0:
            padding_length = (bs - len(chunk) % bs) or bs
            chunk += padding_length * chr(padding_length)
            finished = True
        chunk = cipher.encrypt(chunk)
        sha.update(chunk)
        size += len(chunk)
    return sha.hexdigest(), size 
Example #13
Source File: backblazeb2.py    From backblaze-b2 with MIT License 6 votes vote down vote up
def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)


# A stupid way to calculate size of encrypted file and sha1
# B2 requires a header with the sha1 but urllib2 must have the header before streaming
# the data. This means we must read the file once to calculate the sha1, then read it again
# for streaming the data on upload. 
Example #14
Source File: AllOrNothing.py    From earthengine with MIT License 6 votes vote down vote up
def __init__(self, ciphermodule, mode=None, IV=None):
        """AllOrNothing(ciphermodule, mode=None, IV=None)

        ciphermodule is a module implementing the cipher algorithm to
        use.  It must provide the PEP272 interface.

        Note that the encryption key is randomly generated
        automatically when needed.  Optional arguments mode and IV are
        passed directly through to the ciphermodule.new() method; they
        are the feedback mode and initialization vector to use.  All
        three arguments must be the same for the object used to create
        the digest, and to undigest'ify the message blocks.
        """

        self.__ciphermodule = ciphermodule
        self.__mode = mode
        self.__IV = IV
        self.__key_size = ciphermodule.key_size
        if not isInt(self.__key_size) or self.__key_size==0:
            self.__key_size = 16 
Example #15
Source File: wallet.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def encrypt_private_key(private_key: str, password: str) -> bytes:
        '''
        Encrypt private key with the password.

        Args:
            private_key (str): private key
            password (str): password to encrypt private key with

        Returns:
            bytes: encrpyted private key
        '''
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(sha256(bytes(password.encode('utf-8'))).digest(), AES.MODE_CFB, iv)
        encrypted_private_key = base64.b64encode(iv + cipher.encrypt(bytes(private_key.encode('utf-8'))))
        return encrypted_private_key 
Example #16
Source File: test_pkcs1_15.py    From earthengine with MIT License 5 votes vote down vote up
def testEncryptVerify1(self):
                # Encrypt/Verify messages of length [0..RSAlen-11]
                # and therefore padding [8..117]
                for pt_len in xrange(0,128-11+1):
                    pt = self.rng(pt_len)
                    cipher = PKCS.new(self.key1024)
                    ct = cipher.encrypt(pt)
                    pt2 = cipher.decrypt(ct, "---")
                    self.assertEqual(pt,pt2) 
Example #17
Source File: random.py    From earthengine with MIT License 5 votes vote down vote up
def getrandbits(self, k):
        """Return a python long integer with k random bits."""
        if self._randfunc is None:
            self._randfunc = Random.new().read
        mask = (1L << k) - 1
        return mask & bytes_to_long(self._randfunc(ceil_div(k, 8))) 
Example #18
Source File: gdog.py    From gdog with GNU General Public License v3.0 5 votes vote down vote up
def Encrypt(self, plainText):
        raw = self._pad(plainText)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw)) 
Example #19
Source File: AllOrNothing.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _inventkey(self, key_size):
        # Return key_size random bytes
        from Crypto import Random
        return Random.new().read(key_size) 
Example #20
Source File: Chaffing.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _randnum(self, size):
        from Crypto import Random
        return Random.new().read(size) 
Example #21
Source File: wallet.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def decrypt_private_key(encrypted_private_key: bytes, password: str) -> str:
        '''
        Decrypt private key with the password.

        Args:
            encrypted_private_key (bytes): encrypted private key
            password (str): password to decrypt private key with

        Returns:
            str: decrypted private key
        '''
        encrypted_private_key = base64.b64decode(encrypted_private_key)
        iv = encrypted_private_key[:AES.block_size]
        cipher = AES.new(sha256(bytes(password.encode('utf-8'))).digest(), AES.MODE_CFB, iv)
        private_key = cipher.decrypt(encrypted_private_key[AES.block_size:])
        return str(private_key, 'ascii') 
Example #22
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def testEncrypt2(self):
                # Verify that encryption fails if plaintext is too long
                pt = '\x00'*(128-2*20-2+1)
                cipher = PKCS.new(self.key1024)
                self.assertRaises(ValueError, cipher.encrypt, pt) 
Example #23
Source File: test_pkcs1_15.py    From earthengine with MIT License 5 votes vote down vote up
def testVerify1(self):
                for test in self._testData:
                        # Build the key
                        key = RSA.importKey(test[0])
                        # The real test
                        cipher = PKCS.new(key)
                        pt = cipher.decrypt(t2b(test[2]), "---")
                        self.assertEqual(pt, b(test[1])) 
Example #24
Source File: test_pkcs1_15.py    From earthengine with MIT License 5 votes vote down vote up
def testEncrypt2(self):
                # Verify that encryption fail if plaintext is too long
                pt = '\x00'*(128-11+1)
                cipher = PKCS.new(self.key1024)
                self.assertRaises(ValueError, cipher.encrypt, pt) 
Example #25
Source File: test_pkcs1_15.py    From earthengine with MIT License 5 votes vote down vote up
def setUp(self):
                self.rng = Random.new().read
                self.key1024 = RSA.generate(1024, self.rng)

        # List of tuples with test data for PKCS#1 v1.5.
        # Each tuple is made up by:
        #       Item #0: dictionary with RSA key component, or key to import
        #       Item #1: plaintext
        #       Item #2: ciphertext
        #       Item #3: random data 
Example #26
Source File: test_pkcs1_15.py    From earthengine with MIT License 5 votes vote down vote up
def rws(t):
    """Remove white spaces, tabs, and new lines from a string"""
    for c in ['\n', '\t', ' ']:
        t = t.replace(c,'')
    return t 
Example #27
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def testEncryptDecrypt2(self):
                # Verify that OAEP supports labels
                pt = self.rng(35)
                xlabel = self.rng(22)
                cipher = PKCS.new(self.key1024, label=xlabel)
                ct = cipher.encrypt(pt)
                self.assertEqual(cipher.decrypt(ct), pt) 
Example #28
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def testDecrypt2(self):
                # Simplest possible negative tests
                for ct_size in (127,128,129):
                    cipher = PKCS.new(self.key1024)
                    self.assertRaises(ValueError, cipher.decrypt, bchr(0x00)*ct_size) 
Example #29
Source File: test_pkcs1_oaep.py    From earthengine with MIT License 5 votes vote down vote up
def testDecrypt1(self):
                # Verify decryption using all test vectors
                for test in self._testData:
                        # Build the key
                        comps = [ long(rws(test[0][x]),16) for x in ('n','e','d') ]
                        key = RSA.construct(comps)
                        # The real test
                        cipher = PKCS.new(key, test[4])
                        pt = cipher.decrypt(t2b(test[2]))
                        self.assertEqual(pt, t2b(test[1])) 
Example #30
Source File: number.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def getRandomRange(a, b, randfunc=None):
    """getRandomRange(a:int, b:int, randfunc:callable):long
    Return a random number n so that a <= n < b.

    If randfunc is omitted, then Random.new().read is used.

    This function is for internal use only and may be renamed or removed in
    the future.
    """
    range_ = b - a - 1
    bits = size(range_)
    value = getRandomInteger(bits, randfunc)
    while value > range_:
        value = getRandomInteger(bits, randfunc)
    return a + value