Python Crypto.Random 模块,get_random_bytes() 实例源码

我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用Crypto.Random.get_random_bytes()

项目:neo-python    作者:CityOfZion    | 项目源码 | 文件源码
def CreateKey(self, private_key=None):
        """
        Create a KeyPair

        Args:
            private_key (iterable_of_ints): (optional) 32 byte private key

        Returns:
            KeyPair: a KeyPair instance
        """
        if private_key is None:
            private_key = bytes(Random.get_random_bytes(32))

        key = KeyPair(priv_key=private_key)
        self._keys[key.PublicKeyHash.ToBytes()] = key
        return key
项目:cottoncandy    作者:gallantlab    | 项目源码 | 文件源码
def generate_AES_key(self, key_size=None):
        """Generates a new AES key

        Parameters
        ----------
        key_size : int
            bits in key

        Returns
        -------
        key : str
            AES key
        """
        if key_size is None:
            key_size = self.AES_key_length
        if key_size not in [16, 24, 32]:
            raise ValueError('Bad AES key size')
        return Random.get_random_bytes(key_size)
项目:cottoncandy    作者:gallantlab    | 项目源码 | 文件源码
def generate_AES_key(bytes = 32):
    """Generates a new AES key

    Parameters
    ----------
    bytes : int
        number of bytes in key

    Returns
    -------
    key : bytes
    """
    try:
        from Crypto import Random
        return Random.get_random_bytes(bytes)
    except ImportError:
        print('PyCrypto not install. Reading from /dev/random instead')
        with open('/dev/random', 'r') as rand:
            return rand.read(bytes)
项目:ransomware    作者:xiaozhouas    | 项目源码 | 文件源码
def encryptFile(in_filename, out_filename=None, chunksize=64*1024):
    if not out_filename:
        out_filename = in_filename + '.enc'

    key = Random.get_random_bytes(32)
    iv = Random.get_random_bytes(16)
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    #filesize = os.path.getsize(in_filename)

    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            #outfile.write(struct.pack('<Q', filesize))
            outfile.write(key)
            outfile.write(iv)
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += b' ' * (16 - len(chunk) % 16)

                outfile.write(encryptor.encrypt(chunk))
            os.remove(in_filename)
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def _encrypt_with_shares(cls, plaintext, key_id, vis_expr):
        '''
        Arguments:
        plaintext - plaintext portion of the cell to be encrypted
        key_id - the keytor object,contains a key_id and handle on the key_objection 
              to obtain the keys.
        vis_expr - visibility expression of the cell to be encrypted

        Returns - the encrypted shares concatenated with the ciphertext
        or the field of the cell being encrypted 
        '''
        #generate a random key for the cell 
        cell_key = Random.get_random_bytes(key_id.cell_key_length)
        #break into shares and then encrypt
        encrypted_shares = SecretVisTreeEncryptor.encrypt_secret_shares(vis_expr,
                                                                 cell_key,
                                                                 key_id,
                                                                 cls.leaf_class)
        #encrypt the plaintext 
        ciphertext = cls._encrypt(plaintext, cell_key)
        return encrypted_shares + "#" + ciphertext
项目:keyrings.alt    作者:jaraco    | 项目源码 | 文件源码
def encrypt(self, password, assoc = None):
        # encrypt password, ignore associated data
        from Crypto.Random import get_random_bytes
        salt = get_random_bytes(self.block_size)
        from Crypto.Cipher import AES
        IV = get_random_bytes(AES.block_size)
        cipher = self._create_cipher(self.keyring_key, salt, IV)
        password_encrypted = cipher.encrypt(self.pw_prefix + password)
        # Serialize the salt, IV, and encrypted password in a secure format
        data = dict(
            salt=salt, IV=IV, password_encrypted=password_encrypted,
        )
        for key in data:
            # spare a few bytes: throw away newline from base64 encoding
            data[key] = encodebytes(data[key]).decode()[:-1]
        return json.dumps(data).encode()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def generate_iv(self):
        """
        Generate a random initialization vector. If pycrypto is not available,
        return a buffer of the correct length filled with only '\x00'.
        """
        if Random:
            return Random.get_random_bytes(self.iv_size)
        else:
            return chr(0) * self.iv_size
项目:watchmen    作者:lycclsltt    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:git_intgrtn_aws_s3    作者:droidlabour    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:MCSManager-fsmodule    作者:Suwings    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:PyKI    作者:pykiki    | 项目源码 | 文件源码
def authBykey(pubkeydir, privkeyString, passph):
    # encrypt with pubkey
    if pubkeydir[-1] != '/':
        pubkeydir = pubkeydir + "/"

    try:
        pkey = open(pubkeydir + "public_key.pem", "rt")
        public_key = RSA.importKey(pkey.read())
        pkey.close()
    except FileNotFoundError as e:
        res = {"error": True, "message": 'ERROR: Public key not found.'}
        return(res)
    except:
        res = {"error": True, "message": 'ERROR: Problem reading public key'}
        return(res)

    randomData = Random.get_random_bytes(32)
    enc_data = public_key.encrypt(b'success', randomData)

    # decrypt with private key
    private_key = RSA.importKey(privkeyString, passph)
    dec_data = private_key.decrypt(enc_data)
    if dec_data == b'success':
        # self.__token = SHA256.new(private_key.exportKey()).digest()
        res = {"error": False, "message": "INFO: Successfully authenticated"}
        return(res)
    else:
        res = {"error": True, "message": 'ERROR: Unable to authenticate'}
        return(res)
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def generate_iv(self):
        """
        Generate a random initialization vector. If pycrypto is not available,
        return a buffer of the correct length filled with only '\x00'.
        """
        if Random:
            return Random.get_random_bytes(self.iv_size)
        else:
            return chr(0) * self.iv_size
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def generate_iv(self):
        """
        Generate a random initialization vector. If pycrypto is not available,
        return a buffer of the correct length filled with only '\x00'.
        """
        if Random:
            return Random.get_random_bytes(self.iv_size)
        else:
            return chr(0) * self.iv_size
项目:PyMal    作者:cysinfo    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:cottoncandy    作者:gallantlab    | 项目源码 | 文件源码
def generate_key(self, key_size=32):
        """Generates a new AES key

        Parameters
        ----------
        key_size : int
            bits in key

        Returns
        -------

        """
        if key_size not in [16, 24, 32]:
            raise RuntimeError('Bad key length')
        self.key = Random.get_random_bytes(key_size)
项目:SublimeRemoteGDB    作者:summerwinter    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:scapy-bpf    作者:guedou    | 项目源码 | 文件源码
def generate_iv(self):
        """
        Generate a random initialization vector. If pycrypto is not available,
        return a buffer of the correct length filled with only '\x00'.
        """
        if Random:
            return Random.get_random_bytes(self.iv_size)
        else:
            return chr(0) * self.iv_size
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def generate_iv(self):
        """
        Generate a random initialization vector. If pycrypto is not available,
        return a buffer of the correct length filled with only '\x00'.
        """
        if Random:
            return Random.get_random_bytes(self.iv_size)
        else:
            return chr(0) * self.iv_size
项目:Encryped-file-system    作者:kittenish    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:scapy-radio    作者:BastilleResearch    | 项目源码 | 文件源码
def generate_iv(self):
        """
        Generate a random initialization vector. If pycrypto is not available,
        return a buffer of the correct length filled with only '\x00'.
        """
        if Random:
            return Random.get_random_bytes(self.iv_size)
        else:
            return chr(0) * self.iv_size
项目:Quiver-alfred    作者:danielecook    | 项目源码 | 文件源码
def encrypt(self, value):
            iv = Random.get_random_bytes(AES.block_size)
            cipher = self.get_cipher(self.key, iv)
            return iv + cipher.encrypt(value)
项目:isf    作者:w3h    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:isf    作者:w3h    | 项目源码 | 文件源码
def generate_iv(self):
        """
        Generate a random initialization vector. If pycrypto is not available,
        return a buffer of the correct length filled with only '\x00'.
        """
        if Random:
            return Random.get_random_bytes(self.iv_size)
        else:
            return chr(0) * self.iv_size
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
def encrypt(self, value):
            iv = Random.get_random_bytes(AES.block_size)
            cipher = self.get_cipher(self.key, iv)
            return iv + cipher.encrypt(value)
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
def encrypt(self, value):
            iv = Random.get_random_bytes(AES.block_size)
            cipher = self.get_cipher(self.key, iv)
            return iv + cipher.encrypt(value)
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def _generate_n_random_shares(n, l):
        '''
        Arguments:
        n - the number of random shares to generate
        l - the upper length of the shares to generate (in bytes)

        Returns: A list of n random numbers of length l, 
        they are generated using a cryptographic PRNG. 
        '''
        return [Random.get_random_bytes(l) for x in xrange(0, n)]
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def test_optimal_path(self):
        '''
        Test the optimal path functionality
        '''
        expressions = [('a&b',['a','b'],'a&b'),
                       ('a&b&c', ['a','b'],''),
                       ('a|b', ['a'], 'a'),
                       ('a|b|c',['a','b'], 'a'),
                       ('(a&b)|c',['a','b'], '(a&b)'),
                       ('(a&b)|c',['c'], 'c'),
                       ('(a|b)&c',['a','c'], '(a)&c'),
                       ('(a|b)&c',['a'], ''),
                       ('(a&b)|(b&c)',['b','c'],'(b&c)'),
                       ('(a|b)&(c|d)',['a','d'],'(a)&(d)'),
                       ('((a&b)|c)&(d|e)',['c','e'],'(c)&(e)')]

        parser = VisParser()
        share_parser = SecretVisParser()
        for (e, t, g) in expressions:
            vis_tree = parser.parse(e)
            share_tree = SecretVisTree(vis_tree.root,
                                       vis_tree.expression, 
                                       secret=Random.get_random_bytes(16))
            share_tree.compute_shares()
            share_tree.set_attributes(vis_tree)
            (match, opt_tree, keys) = share_tree.optimal_decryption_tree(Keytor('VIS_AES_CBC',DummyKeys(terms=t),16),
                                                                     encrypted=False) 
            self.assertEqual(g, opt_tree.__str__(),   
                             "Optimal tree for %s: %s should be %s" % 
                             (e,opt_tree.__str__(),g))
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def test_compute_shares(self):
        '''
        Tests computing the shares
        '''
        expressions = ['a&b',
                       'a&b&c',
                       'a|b',
                       'a|b|c',
                       '(a&b)|c',
                       '(a|b)&c',
                       'a|(b&c)',
                       'a&(b|c)',
                       '(a&b)|(b&c)',
                       '(a|b)&(c|d)',
                       '"test&|"&b',
                       '((a&b)|c)&(d|e)']
        parser = VisParser()
        for e in expressions:
            tree = parser.parse(e)
            secret = Random.get_random_bytes(16)
            secret_tree = SecretVisTree(tree.root, e, secret=secret)
            secret_tree.compute_shares()

            #Test for correct share
            self.assertTrue(secret_tree.verify_shares(), 
                            "Shares %s did not verify for expression %s." %
                             (secret_tree.print_shares(), e))

            #Test for incorrect share
            secret_tree.root.share = 0 
            self.assertFalse(secret_tree.verify_shares(), 
                            "Shares %s did incorrectly verify for expression %s." %
                             (secret_tree.print_shares(), e))
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def test_encrypt_decrypt(self):
        '''
        Tests encrypting and decrypting the shares 
        '''
        DummyPKI = DummyEncryptionPKI()

        expressions = ['a&b',
                       'a&b&c',
                       'a|b',
                       'a|b|c',
                       '(a&b)|c',
                       '(a|b)&c',
                       'a|(b&c)',
                       'a&(b|c)',
                       '(a&b)|(b&c)',
                       '(a|b)&(c|d)']


        for e in expressions:
            secret = Random.get_random_bytes(16)
            encrypted_shares = SecretVisTreeEncryptor.encrypt_secret_shares(e,
                                                                            secret,
                                                                            Keytor('VIS_AES_CBC',DummyPKI,16),
                                                                            Pycrypto_AES_CBC)
            share = SecretVisTreeEncryptor.decrypt_secret_shares(e, 
                                                          encrypted_shares,
                                                          Keytor('VIS_AES_CBC',DummyPKI,16),
                                                          Pycrypto_AES_CBC)
            self.assertEqual(share, secret)
项目:mist.api    作者:mistio    | 项目源码 | 文件源码
def encrypt(plaintext, key=config.SECRET, key_salt='', no_iv=False):
    """Encrypt shit the right way"""

    # sanitize inputs
    key = SHA256.new(key + key_salt).digest()
    if len(key) not in AES.key_size:
        raise Exception()
    if isinstance(plaintext, unicode):
        plaintext = plaintext.encode('utf-8')

    # pad plaintext using PKCS7 padding scheme
    padlen = AES.block_size - len(plaintext) % AES.block_size
    plaintext += chr(padlen) * padlen

    # generate random initialization vector using CSPRNG
    iv = '\0' * AES.block_size if no_iv else get_random_bytes(AES.block_size)

    # encrypt using AES in CFB mode
    ciphertext = AES.new(key, AES.MODE_CFB, iv).encrypt(plaintext)

    # prepend iv to ciphertext
    if not no_iv:
        ciphertext = iv + ciphertext

    # return ciphertext in hex encoding
    return ciphertext.encode('hex')
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def generate_iv(self):
        """
        Generate a random initialization vector. If pycrypto is not available,
        return a buffer of the correct length filled with only '\x00'.
        """
        if Random:
            return Random.get_random_bytes(self.iv_size)
        else:
            return chr(0) * self.iv_size
项目:mass-apk-installer    作者:binary-signal    | 项目源码 | 文件源码
def __init__(self, key_aes):
        if key_aes==None: # if key_aes is empty generate random key 16 byte / 128 bit in length for the AES cipher key
            self.key_aes = Random.get_random_bytes(16)
            self.dump_aes_key(self.key_aes)
        if key_aes != None:
            self.key_aes =self.hash_sha256(key_aes)
            if len(self.hash_sha256(key_aes)) != self.block_size:
                print "Aes key size missmatch !"
                return None

    # the function generates encrypted files with the extension
    # *.enc encrypted files are stored in the specified format
    # below {[file size in bytes][IV][Cipher blocks]}.enc
项目:android-backup-tools    作者:bluec0re    | 项目源码 | 文件源码
def _encrypt(self, dec, password=None):
        """
        Internal encryption function

        Uses either the password argument for the encryption,
        or, if not supplied, the password field of the object

        :param dec: a byte string representing the to be encrypted data
        :rtype: bytes
        """
        if AES is None:
            raise ImportError("PyCrypto required")

        if password is None:
            password = self.password

        if password is None:
            raise ValueError(
                "Password need to be provided to create encrypted archives")

        # generate the different encryption parts (non-secure!)
        master_key = Random.get_random_bytes(32)
        master_salt = Random.get_random_bytes(64)
        user_salt = Random.get_random_bytes(64)
        master_iv = Random.get_random_bytes(16)
        user_iv = Random.get_random_bytes(16)
        rounds = 10000

        # create the PKCS#7 padding
        l = len(dec)
        pad = 16 - (l % 16)
        dec += bytes([pad] * pad)

        # encrypt the data
        cipher = AES.new(master_key, IV=master_iv, mode=AES.MODE_CBC)
        enc = cipher.encrypt(dec)

        # generate the master key checksum
        master_ck = PBKDF2(self.encode_utf8(master_key),
                           master_salt, dkLen=256//8, count=rounds)

        # generate the user key from the given password
        user_key = PBKDF2(password,
                          user_salt, dkLen=256//8, count=rounds)

        # encrypt the master key and iv
        master_dec = b"\x10" + master_iv + b"\x20" + master_key + b"\x20" + master_ck
        l = len(master_dec)
        pad = 16 - (l % 16)
        master_dec += bytes([pad] * pad)
        cipher = AES.new(user_key, IV=user_iv, mode=AES.MODE_CBC)
        master_enc = cipher.encrypt(master_dec)

        # put everything together
        enc = binascii.b2a_hex(user_salt).upper() + b"\n" + \
                binascii.b2a_hex(master_salt).upper() + b"\n" + \
                str(rounds).encode() + b"\n" + \
                binascii.b2a_hex(user_iv).upper() + b"\n" + \
                binascii.b2a_hex(master_enc).upper() + b"\n" + enc

        return enc