我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用Crypto.Random.new()。
def get_encryption(): return ''' import base64 from Crypto import Random from Crypto.Cipher import AES abbrev = '{2}' {0} = base64.b64decode('{1}') def encrypt(raw): iv = Random.new().read( AES.block_size ) cipher = AES.new({0}, AES.MODE_CFB, iv ) return (base64.b64encode( iv + cipher.encrypt( raw ) ) ) def decrypt(enc): enc = base64.b64decode(enc) iv = enc[:16] cipher = AES.new({0}, AES.MODE_CFB, iv ) return cipher.decrypt( enc[16:] ) '''.format(st_obf[0],aes_encoded,aes_abbrev) ################################################################################ # st_protocol.py stitch_gen variables # ################################################################################
def AESEnc(sour, key): from Crypto.Cipher import AES from Crypto import Random sour = sour.encode('utf8') key = key.encode('utf8') bs = AES.block_size pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs) iv = Random.new().read(bs) cipher = AES.new(key, AES.MODE_ECB, iv) resData1 = cipher.encrypt(pad(sour)) resData2 = resData1.encode('hex') resData3 = resData2.upper() print resData3 return resData3
def testEncrypt1(self): # Verify encryption using all test vectors for test in self._testData: # Build the key comps = [ long(rws(test[0][x]),16) for x in ('n','e') ] key = RSA.construct(comps) # 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, test[4]) ct = cipher.encrypt(t2b(test[1])) self.assertEqual(ct, t2b(test[2]))
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)
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]))
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]))
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)
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]))
def getRandomInteger(N, randfunc=None): """getRandomInteger(N:int, randfunc:callable):long Return a random number with at most N bits. 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. """ if randfunc is None: _import_Random() randfunc = Random.new().read S = randfunc(N>>3) odd_bits = N % 8 if odd_bits != 0: char = ord(randfunc(1)) >> (8-odd_bits) S = bchr(char) + S value = bytes_to_long(S) return value
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
def __init__(self): self.iv = Random.new().read(AES.block_size) self.key = Random.new().read(AES.block_size) self.cipher = AES.new(key=self.key, mode=AES.MODE_CBC, IV=self.iv) texts = [] self.plaintexts = [] # Reads all the lines from the data, as binary strings, then decodes # them from base64 and applies Pkcs7 padding. with open('data/7.txt', 'rb') as dataFile: texts = dataFile.readlines() for text in texts: strText = base64.b64decode(text) self.plaintexts.append(Pkcs7(strText))
def RandomEncrypt(plaintext): """Returns a tuple with the encrypted text and the mode used.""" # Random key. key = Random.new().read(AES.block_size) # Random padding both before and after the plaintext. The # size of the second padding cannot be random since the result # needs to have a number of bytes multiple of 16. paddingSize = random.randint(5, 10) prepend = Random.new().read(paddingSize) append = Random.new().read(AES.block_size - paddingSize) # Pick encryption mode at random. mode = None if random.randint(0, 1) == 0: mode = AES.MODE_ECB else: mode = AES.MODE_CBC # Perform the encryption. aes = aes_lib.AESCipher(key, mode=mode) text = prepend + plaintext + append return (aes.aes_encrypt(text), mode)
def __init__(self, key=None, mode=AES.MODE_ECB, iv=None): """Initialize a AES cipher with the given mode, and key (as a byte string) Parameters: key: the key, as a byte string (e.g. b'YELLOW SUBMARINE'). If None, a random one will be generated. mode: AES mode. Default: AES.MODE_ECB. iv: IV. If None, a random one will be generated internally. """ if iv is None: self._iv = self.GenerateRandomBytes(AES.block_size) else: self._iv = iv if key is None: self._key = self.GenerateRandomBytes(AES.block_size) else: self._key = key self.mode = mode self._cipher = AES.new(key=self._key, mode=self.mode, IV=self._iv)
def MerkleDamgard(message, state, stateLen): """Applies an arbitrary Merkle-Damgard construction to the message. The default state length and initial state are those used all over this program. """ newState = state # The state length we use is shorter than what AES wants for the keys. newState = padPKCS7(newState) for i in range(GetNumBlocks(message)): cipher = AES.new(newState, AES.MODE_ECB) newState = cipher.encrypt(GetBlock(message, i)) # This would be a really bad idea to do in practice, if we are # actually using AES or an algorithm that requires keys of # a certain size. It's needed here because the hash and # the key needs to be the same for the challenge to work, and # the hash we return has 2 bytes. newState = padPKCS7(newState[:stateLen]) return newState[:stateLen] # Generates the initial 2**k states of the tree at random. We make # all of them different with each other.
def CBCMacWithStates(message, iv): """Computes the CBC-MAC of a message given the IV. Returns a tuple with the hash and a list of tuples; the first element is the block index and the second is the intermediate state associated with that block, as a byte string. It is expected that this returns the same hash as CBC-MAC above given the same inputs. """ M_states = [] paddedMessage = padPKCS7(message) intermediateMessage = b'' currentState = iv for bIndex in range(GetNumBlocks(paddedMessage)): intermediateMessage = GetBlock(paddedMessage, bIndex) cipher = AES.new(b'YELLOW SUBMARINE', AES.MODE_CBC, currentState) currentState = cipher.encrypt(intermediateMessage) currentState = currentState[-AES.block_size:] M_states.append( ( bIndex, currentState ) ) return currentState, M_states
def encrypt(self, plaintext): """CBC encryption.""" cipher = AES.new(key=self._key, mode=AES.MODE_ECB) # The full URL is not necessary for this setup, so I am just encrypting # the plaintext as it is. I don't even need to support padding. prev_ct = self._iv block_index = 0 ciphertext = b'' # The loop simulates encryption through AES in CBC mode. while block_index < len(plaintext): block = plaintext[block_index : block_index + AES.block_size] final_block = strxor(block, prev_ct) cipher_block = cipher.encrypt(final_block) prev_ct = cipher_block ciphertext += cipher_block block_index += AES.block_size return ciphertext
def EditCTR(ciphertext, offset, newText, ctrObj): numBlocks = block_utils.GetNumBlocks(ciphertext) # Sanity checking. if offset < 0 or offset > numBlocks - 1: raise ValueError("Invalid offset.") if len(newText) != AES.block_size: raise ValueError("New plaintext must be 1 block in size") # Encrypt the new block of text using the value of the # counter for the 'offset' block of the ciphertext. The idea # is that newBlock will replace the block at position 'offset' # in the ciphertext, although here we do not perform the # actual substitution. newBlock = ctrObj.OneBlockCrypt(newText, offset) return newBlock # This function is only here to recover the text as explained # in the challenge. Of course here we need to know the key :)
def get_key(encoded_key): IV = None CIPHER = None if encoded_key is False: try: MYFILE = Tools.__path__[0]+os.sep+"admin"+os.sep+'secret.key' with open(MYFILE, 'r') as myfileHandle: encoded_key = myfileHandle.read() except IOError: print_error("Could not find the secret.key file in Tools/Admin!") try: IV = Random.new().read(AES.block_size) CIPHER = AES.new(base64.b64decode(encoded_key), AES.MODE_CFB, IV) except Exception as e: print_exception("Some problem occured: {0}".format(e)) return IV, CIPHER
def decrypt_file_aes(self, in_file, out_file, password, key_length=32): bs = AES.block_size salt = in_file.read(bs)[len('Salted__'):] key, iv = self.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]) if padding_length < 1 or padding_length > bs: raise ValueError('bad decrypt pad (%d)' % padding_length) # all the pad-bytes must be the same if chunk[-padding_length:] != (padding_length * chr(padding_length)): # this is similar to the bad decrypt:evp_enc.c from openssl program raise ValueError('bad decrypt') chunk = chunk[:-padding_length] finished = True out_file.write(chunk)
def lmots_sig_to_pub(sig, S, lmots_type, message): signature = LmotsSignature.deserialize(sig) if (signature.type != lmots_type): raise ValueError(err_unknown_typecode) n, p, w, ls = lmots_params[lmots_type] hashQ = H(S + signature.C + message + D_MESG) V = hashQ + checksum(hashQ, w, ls) hash = SHA256.new() hash.update(S) for i, y in enumerate(signature.y): tmp = y for j in xrange(coef(V, i, w), 2**w - 1): tmp = H(S + tmp + u16str(i) + u8str(j) + D_ITER) hash.update(tmp) hash.update(D_PBLC) return hash.digest() # *************************************************************** # | # LMS N-time signatures functions | # | # ***************************************************************
def test_encrypter(self): """ test_encrypter :return: """ key = '0123456701234567' iv = Random.new().read(AES.block_size) s = '?? 10:00 AM' # ECB encrypter = tools.Encrypter(key) self.assertEqual(encrypter.decrypt(encrypter.encrypt(s)), s) # CBC encrypter = tools.Encrypter(key, AES.MODE_CBC, iv) self.assertEqual(encrypter.decrypt(encrypter.encrypt(s)), s) # CFB encrypter = tools.Encrypter(key, AES.MODE_CFB, iv) self.assertEqual(encrypter.decrypt(encrypter.encrypt(s)), s)
def generate_rsa_private_key(): """Generate a new RSA private key.""" rand = Random.new().read return RSA.generate(4096, rand)
def encrypt(raw, aes_key=secret): iv = Random.new().read( AES.block_size ) cipher = AES.new(aes_key, AES.MODE_CFB, iv ) return (base64.b64encode( iv + cipher.encrypt( raw ) ) )
def decrypt(enc, aes_key=secret): enc = base64.b64decode(enc) iv = enc[:16] cipher = AES.new(aes_key, AES.MODE_CFB, iv ) return cipher.decrypt( enc[16:] )
def encrypt(raw): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(KEY, AES.MODE_CBC, iv) return base64.b64encode( iv + cipher.encrypt(raw) )
def decrypt(enc): enc = base64.b64decode(enc) iv = enc[:16] cipher = AES.new(KEY, AES.MODE_CBC, iv ) return unpad(cipher.decrypt(enc[16:]))
def createKey(): random_generator = Random.new().read return RSA.generate(1024, random_generator)
def encrypt(self, raw): iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return iv + cipher.encrypt(self._pad(raw))
def decrypt(self, enc): iv = enc[:AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) return self._unpad(cipher.decrypt(enc[AES.block_size:]))