本文整理汇总了Python中Cryptodome.Random.get_random_bytes方法的典型用法代码示例。如果您正苦于以下问题:Python Random.get_random_bytes方法的具体用法?Python Random.get_random_bytes怎么用?Python Random.get_random_bytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cryptodome.Random
的用法示例。
在下文中一共展示了Random.get_random_bytes方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AES_encrypt_Login
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def AES_encrypt_Login(self, user, psw, returnOrdType=3):
assert (type(user)) == str
assert (type(psw)) == str
logger = self._SetLogger(package=__name__)
# if isinstance(user, str): b_user = user.encode('utf-8') # covert to bytes
# if isinstance(psw, str): b_psw = psw.encode('utf-8') # covert to bytes
# b_user = user.encode('utf-8') # covert to bytes
# b_psw = psw.encode('utf-8') # covert to bytes
logger.info(' encrypting password with user value')
b_key = self._prepareKey(user)
nounce = Random.get_random_bytes(16)
cipher = AES.new(b_key, AES.MODE_CFB, nounce)
# - text to be ciphered
ciphertext = cipher.encrypt(psw.encode('utf-8')) # covert to bytes
# - encrypting della psw
b_cipheredPsw = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
pswLen = len(b_cipheredPsw)
# - cipheredPsw is bytearray '''
h_cipheredPsw = self.bytesToHex(b_cipheredPsw) # hex contenuto in string
logger.info(' h_cipheredPsw %s' % h_cipheredPsw)
# crypting dello user, usiamo la HexPSW come Key
logger.info(' encrypting user value with password in strHex format')
b_key = self._prepareKey(b_cipheredPsw)
nounce = Random.get_random_bytes(16)
cipher = AES.new(b_key, AES.MODE_CFB, nounce)
# - text to be ciphered
ciphertext = cipher.encrypt(user.encode('utf-8')) # convert to bytes
# - encrypting dello user
b_cipheredUser = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
# - cipheredPsw is bytearray '''
h_cipheredUser = self.bytesToHex(b_cipheredUser) # hex contenuto in string
logger.info(' h_cipheredUser %s' % h_cipheredUser)
'''
costruzione del dato di ritorno composto dai dati HEX di PSW + USER con
l'aggiunta della lunghezza della PSW calcolata sul bytes_data.
'''
myData = h_cipheredPsw + h_cipheredUser + '{0:02x}'.format(pswLen)
logger = self._SetLogger(package=__name__, exiting=True)
return myData
示例2: create_entry
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def create_entry(self, group = None, title = "", image = 1, url = "",
username = "", password = "", comment = "",
y = 2999, mon = 12, d = 28, h = 23, min_ = 59,
s = 59):
"""This method creates a new entry.
The group which should hold the entry is needed.
image must be an unsigned int >0, group a v1Group.
It is possible to give an expire date in the following way:
- y is the year between 1 and 9999 inclusive
- mon is the month between 1 and 12
- d is a day in the given month
- h is a hour between 0 and 23
- min_ is a minute between 0 and 59
- s is a second between 0 and 59
The special date 2999-12-28 23:59:59 means that entry expires never.
"""
if (type(title) is not str or
type(image) is not int or image < 0 or
type(url) is not str or
type(username) is not str or
type(password) is not str or
type(comment) is not str or
type(y) is not int or
type(mon) is not int or
type(d) is not int or
type(h) is not int or
type(min_) is not int
or type(s) is not int or
type(group) is not v1Group):
raise KPError("One argument has not a valid type.")
elif group not in self.groups:
raise KPError("Group doesn't exist.")
elif (y > 9999 or y < 1 or mon > 12 or mon < 1 or d > 31 or d < 1 or
h > 23 or h < 0 or min_ > 59 or min_ < 0 or s > 59 or s < 0):
raise KPError("No legal date")
elif (((mon == 1 or mon == 3 or mon == 5 or mon == 7 or mon == 8 or
mon == 10 or mon == 12) and d > 31) or
((mon == 4 or mon == 6 or mon == 9 or mon == 11) and d > 30) or
(mon == 2 and d > 28)):
raise KPError("Given day doesn't exist in given month")
Random.atfork()
uuid = Random.get_random_bytes(16)
entry = v1Entry(group.id_, group, image, title, url, username,
password, comment,
datetime.now().replace(microsecond = 0),
datetime.now().replace(microsecond = 0),
datetime.now().replace(microsecond = 0),
datetime(y, mon, d, h, min_, s),
uuid)
self.entries.append(entry)
group.entries.append(entry)
self._num_entries += 1
return True
示例3: __init__
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def __init__(self, module, params):
from Cryptodome 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)
示例4: __init__
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def __init__(self, filepath=None, password=None, keyfile=None,
read_only=False, new = False):
""" Initialize a new or an existing database.
If a 'filepath' and a 'masterkey' is passed 'load' will try to open
a database. If 'True' is passed to 'read_only' the database will open
read-only. It's also possible to create a new one, just pass 'True' to
new. This will be ignored if a filepath and a masterkey is given this
will be ignored.
"""
if filepath is not None and password is None and keyfile is None:
raise KPError('Missing argument: Password or keyfile '
'needed additionally to open an existing database!')
elif type(read_only) is not bool or type(new) is not bool:
raise KPError('read_only and new must be bool')
elif ((filepath is not None and type(filepath) is not str) or
(type(password) is not str and password is not None) or
(type(keyfile) is not str and keyfile is not None)):
raise KPError('filepath, masterkey and keyfile must be a string')
elif (filepath is None and password is None and keyfile is None and
new is False):
raise KPError('Either an existing database should be opened or '
'a new should be created.')
self.groups = []
self.entries = []
self.root_group = v1Group()
self.read_only = read_only
self.filepath = filepath
self.password = password
self.keyfile = keyfile
# This are attributes that are needed internally. You should not
# change them directly, it could damage the database!
self._group_order = []
self._entry_order = []
self._signature1 = 0x9AA2D903
self._signature2 = 0xB54BFB65
self._enc_flag = 2
self._version = 0x00030002
self._final_randomseed = ''
self._enc_iv = ''
self._num_groups = 1
self._num_entries = 0
self._contents_hash = ''
Random.atfork()
self._transf_randomseed = Random.get_random_bytes(32)
self._key_transf_rounds = 150000
# Due to the design of KeePass, at least one group is needed.
if new is True:
self._group_order = [("id", 1), (1, 4), (2, 9), (7, 4), (8, 2),
(0xFFFF, 0)]
group = v1Group(1, 'Internet', 1, self, parent = self.root_group)
self.root_group.children.append(group)
self.groups.append(group)
示例5: generate_nonce
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def generate_nonce(size):
""" Generate a secure random for cryptographic use.
Args:
size: Number of bytes for the nonce
Returns: Generated random bytes
"""
return Random.get_random_bytes(size)
示例6: _generate_key_and_iv
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def _generate_key_and_iv(encalg, cek="", iv=""):
if cek and iv:
return cek, iv
try:
_key = Random.get_random_bytes(ENCALGLEN1[encalg])
_iv = Random.get_random_bytes(12)
except KeyError:
try:
_key = Random.get_random_bytes(ENCALGLEN2[encalg])
_iv = Random.get_random_bytes(16)
except KeyError:
raise Exception("Unsupported encryption algorithm %s" % encalg)
if cek:
_key = cek
if iv:
_iv = iv
return _key, _iv
示例7: AES_encrypt
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def AES_encrypt(self, clearMsg, returnOrdType=3, returnDataTYPE='bytes'):
# print (type (clearMsg), clearMsg)
if isinstance(clearMsg, str): clearMsg = clearMsg.encode('utf-8') # covert to bytes
# if isinstance(clearMsg, str): clearMsg = bytes(clearMsg, 'utf-8') # covert to bytes
# print (type (clearMsg), clearMsg)
nounce = Random.get_random_bytes(16)
cipher = AES.new(self._key, AES.MODE_CFB, nounce)
ciphertext = cipher.encrypt(clearMsg)
retValue = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
if returnDataTYPE == 'hex': return self.bytesToHex(retValue)
elif returnDataTYPE == 'base64': return self.bytesToBase64(retValue)
else: return bytes(retValue)
示例8: AES_encrypt
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def AES_encrypt(self, clearMsg, returnOrdType=3, returnDataType='bytes'):
if isinstance(clearMsg, str): clearMsg = clearMsg.encode('utf-8') # covert to bytes
nounce = Random.get_random_bytes(16)
cipher = AES.new(self._key, AES.MODE_CFB, nounce)
ciphertext = cipher.encrypt(clearMsg)
retValue = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType)
''' retValue is bytearray '''
if returnDataType == 'hex-str': return self.bytesToHex(retValue) # hex contenuto in string
elif returnDataType == 'base64': return self.bytesToBase64(retValue)
return bytes(retValue)
示例9: PKCS1_OAEP_AES_encrypt
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def PKCS1_OAEP_AES_encrypt(self, data, outFile):
# recipient_key = Crypto.PublicKey.RSA.import_key(open("receiver.pem").read())
recipient_key = self._privateKey
session_key = Random.get_random_bytes(32)
# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
# creazione del file con i dati crypted
print ('file {FILE} has been created with encrypted data.'.format(FILE=outFile))
file_out = open(outFile, "wb")
file_out.write(cipher_rsa.encrypt(session_key))
[ file_out.write(x) for x in (cipher_aes.nonce, tag, ciphertext) ]
return ciphertext
示例10: enc_setup
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def enc_setup(self, msg, auth_data, key=None, **kwargs):
encrypted_key = ""
self.msg = msg
self.auth_data = auth_data
# Generate the input parameters
try:
apu = b64d(kwargs["apu"])
except KeyError:
apu = Random.get_random_bytes(16)
try:
apv = b64d(kwargs["apv"])
except KeyError:
apv = Random.get_random_bytes(16)
# Handle Local Key and Ephemeral Public Key
if not key:
raise Exception("EC Key Required for ECDH-ES JWE Encrpytion Setup")
# Generate an ephemeral key pair if none is given
curve = NISTEllipticCurve.by_name(key.crv)
if "epk" in kwargs:
epk = kwargs["epk"] if isinstance(kwargs["epk"], ECKey) else ECKey(kwargs["epk"])
else:
raise Exception(
"Ephemeral Public Key (EPK) Required for ECDH-ES JWE "
"Encryption Setup")
params = {
"apu": b64e(apu),
"apv": b64e(apv),
"epk": epk.serialize(False)
}
cek = iv = None
if 'cek' in kwargs and kwargs['cek']:
cek = kwargs['cek']
if 'iv' in kwargs and kwargs['iv']:
iv = kwargs['iv']
cek, iv = self._generate_key_and_iv(self.enc, cek=cek, iv=iv)
if self.alg == "ECDH-ES":
try:
dk_len = KEYLEN[self.enc]
except KeyError:
raise Exception(
"Unknown key length for algorithm %s" % self.enc)
cek = ecdh_derive_key(curve, epk.d, (key.x, key.y), apu, apv,
str(self.enc).encode(), dk_len)
elif self.alg in ["ECDH-ES+A128KW", "ECDH-ES+A192KW", "ECDH-ES+A256KW"]:
_pre, _post = self.alg.split("+")
klen = int(_post[1:4])
kek = ecdh_derive_key(curve, epk.d, (key.x, key.y), apu, apv,
str(_post).encode(), klen)
encrypted_key = aes_wrap_key(kek, cek)
else:
raise Exception("Unsupported algorithm %s" % self.alg)
return cek, encrypted_key, iv, params, epk
示例11: runTest
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def runTest(self):
"""Cryptodome.Random.new()"""
# Import the Random module and try to use it
from Cryptodome import Random
randobj = Random.new()
x = randobj.read(16)
y = randobj.read(16)
self.assertNotEqual(x, y)
z = Random.get_random_bytes(16)
self.assertNotEqual(x, z)
self.assertNotEqual(y, z)
# Test the Random.random module, which
# implements a subset of Python's random API
# Not implemented:
# seed(), getstate(), setstate(), jumpahead()
# random(), uniform(), triangular(), betavariate()
# expovariate(), gammavariate(), gauss(),
# longnormvariate(), normalvariate(),
# vonmisesvariate(), paretovariate()
# weibullvariate()
# WichmannHill(), whseed(), SystemRandom()
from Cryptodome.Random import random
x = random.getrandbits(16*8)
y = random.getrandbits(16*8)
self.assertNotEqual(x, y)
# Test randrange
if x>y:
start = y
stop = x
else:
start = x
stop = y
for step in range(1,10):
x = random.randrange(start,stop,step)
y = random.randrange(start,stop,step)
self.assertNotEqual(x, y)
self.assertEqual(start <= x < stop, True)
self.assertEqual(start <= y < stop, True)
self.assertEqual((x - start) % step, 0)
self.assertEqual((y - start) % step, 0)
for i in range(10):
self.assertEqual(random.randrange(1,2), 1)
self.assertRaises(ValueError, random.randrange, start, start)
self.assertRaises(ValueError, random.randrange, stop, start, step)
self.assertRaises(TypeError, random.randrange, start, stop, step, step)
self.assertRaises(TypeError, random.randrange, start, stop, "1")
self.assertRaises(TypeError, random.randrange, "1", stop, step)
self.assertRaises(TypeError, random.randrange, 1, "2", step)
self.assertRaises(ValueError, random.randrange, start, stop, 0)
# Test randint
x = random.randint(start,stop)
y = random.randint(start,stop)
self.assertNotEqual(x, y)
self.assertEqual(start <= x <= stop, True)
self.assertEqual(start <= y <= stop, True)
for i in range(10):
self.assertEqual(random.randint(1,1), 1)
self.assertRaises(ValueError, random.randint, stop, start)
self.assertRaises(TypeError, random.randint, start, stop, step)
self.assertRaises(TypeError, random.randint, "1", stop)
self.assertRaises(TypeError, random.randint, 1, "2")
# Test choice
seq = range(10000)
x = random.choice(seq)
y = random.choice(seq)
self.assertNotEqual(x, y)
self.assertEqual(x in seq, True)
self.assertEqual(y in seq, True)
for i in range(10):
self.assertEqual(random.choice((1,2,3)) in (1,2,3), True)
self.assertEqual(random.choice([1,2,3]) in [1,2,3], True)
if sys.version_info[0] is 3:
self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True)
self.assertEqual(1, random.choice([1]))
self.assertRaises(IndexError, random.choice, [])
self.assertRaises(TypeError, random.choice, 1)
# Test shuffle. Lacks random parameter to specify function.
# Make copies of seq
seq = range(500)
x = list(seq)
y = list(seq)
random.shuffle(x)
random.shuffle(y)
self.assertNotEqual(x, y)
self.assertEqual(len(seq), len(x))
self.assertEqual(len(seq), len(y))
for i in range(len(seq)):
self.assertEqual(x[i] in seq, True)
self.assertEqual(y[i] in seq, True)
self.assertEqual(seq[i] in x, True)
self.assertEqual(seq[i] in y, True)
z = [1]
random.shuffle(z)
self.assertEqual(z, [1])
if sys.version_info[0] == 3:
z = bytearray(b('12'))
random.shuffle(z)
self.assertEqual(b('1') in z, True)
self.assertRaises(TypeError, random.shuffle, b('12'))
self.assertRaises(TypeError, random.shuffle, 1)
#.........这里部分代码省略.........
示例12: save
# 需要导入模块: from Cryptodome import Random [as 别名]
# 或者: from Cryptodome.Random import get_random_bytes [as 别名]
def save(self, filepath = None, password = None, keyfile = None):
"""This method saves the database.
It's possible to parse a data path to an alternative file.
"""
if (password is None and keyfile is not None and keyfile != "" and
type(keyfile) is str):
self.keyfile = keyfile
elif (keyfile is None and password is not None and password != "" and
type(password is str)):
self.password = password
elif (keyfile is not None and password is not None and
keyfile != "" and password != "" and type(keyfile) is str and
type(password) is str):
self.keyfile = keyfile
self.password = password
if self.read_only:
raise KPError("The database has been opened read-only.")
elif ((self.password is None and self.keyfile is None) or
(filepath is None and self.filepath is None) or
(keyfile == "" and password == "")):
raise KPError("Need a password/keyfile and a filepath to save the "
"file.")
elif ((type(self.filepath) is not str and self.filepath is not None) or
(type(self.password) is not str and self.password is not None) or
(type(self.keyfile) is not str and self.keyfile is not None)):
raise KPError("filepath, password and keyfile must be strings.")
elif self._num_groups == 0:
raise KPError("Need at least one group!")
content = bytearray()
# First, read out all groups
for i in self.groups:
# Get the packed bytes
# j stands for a possible field type
for j in range(1, 10):
ret_save = self._save_group_field(j, i)
# The field type and the size is always in front of the data
if ret_save is not False:
content += struct.pack('<H', j)
content += struct.pack('<I', ret_save[0])
content += ret_save[1]
# End of field
content += struct.pack('<H', 0xFFFF)
content += struct.pack('<I', 0)
# Same with entries
for i in self.entries:
for j in range(1, 15):
ret_save = self._save_entry_field(j, i)
if ret_save is not False:
content += struct.pack('<H', j)
content += struct.pack('<I', ret_save[0])
content += ret_save[1]
content += struct.pack('<H', 0xFFFF)
content += struct.pack('<I', 0)
# Generate new seed and new vector; calculate the new hash
Random.atfork()
self._final_randomseed = Random.get_random_bytes(16)
self._enc_iv = Random.get_random_bytes(16)
sha_obj = SHA256.new()
sha_obj.update(bytes(content))
self._contents_hash = sha_obj.digest()
del sha_obj
# Pack the header
header = bytearray()
header += struct.pack('<I', 0x9AA2D903)
header += struct.pack('<I', 0xB54BFB65)
header += struct.pack('<I', self._enc_flag)
header += struct.pack('<I', self._version)
header += struct.pack('<16s', self._final_randomseed)
header += struct.pack('<16s', self._enc_iv)
header += struct.pack('<I', self._num_groups)
header += struct.pack('<I', self._num_entries)
header += struct.pack('<32s', self._contents_hash)
header += struct.pack('<32s', self._transf_randomseed)
if self._key_transf_rounds < 150000:
self._key_transf_rounds = 150000
header += struct.pack('<I', self._key_transf_rounds)
# Finally encrypt everything...
if self.password is None:
masterkey = self._get_filekey()
elif self.password is not None and self.keyfile is not None:
passwordkey = self._get_passwordkey()
filekey = self._get_filekey()
sha = SHA256.new()
sha.update(passwordkey+filekey)
masterkey = sha.digest()
else:
masterkey = self._get_passwordkey()
final_key = self._transform_key(masterkey)
encrypted_content = self._cbc_encrypt(content, final_key)
del content
#.........这里部分代码省略.........