本文整理汇总了Python中Crypto.Random.new方法的典型用法代码示例。如果您正苦于以下问题:Python Random.new方法的具体用法?Python Random.new怎么用?Python Random.new使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Crypto.Random
的用法示例。
在下文中一共展示了Random.new方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: encrypt
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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)
示例2: __init__
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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
示例3: testSign1
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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]))
示例4: testVerify1
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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)
示例5: testSign1
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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]))
示例6: testVerify1
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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)
示例7: testEncryptDecrypt1
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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)
示例8: testEncrypt1
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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]))
示例9: decrypt
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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)
示例10: encrypt_credential
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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')
示例11: decrypt_credential
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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
示例12: decrypt
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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.
示例13: calc_encryption_sha_and_length
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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
示例14: decrypt_private_key
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
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')
示例15: test_get_aes
# 需要导入模块: from Crypto import Random [as 别名]
# 或者: from Crypto.Random import new [as 别名]
def test_get_aes(self):
IV = CryptoRandom.new().read(AES.block_size)
self.assertIsInstance(self.enc2.get_aes(IV), Cipher._mode_cbc.CbcMode)