Python Cryptodome.Random.new() Examples
The following are 30
code examples of Cryptodome.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
Cryptodome.Random
, or try the search function
.
Example #1
Source File: test_pkcs1_oaep.py From jarvis with GNU General Public License v2.0 | 6 votes |
def testEncrypt1(self): # Verify encryption using all test vectors for test in self._testData: # Build the key comps = [ int(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 cipher = PKCS.new(key, test[4], randfunc=randGen(t2b(test[3]))) ct = cipher.encrypt(t2b(test[1])) self.assertEqual(ct, t2b(test[2]))
Example #2
Source File: number.py From jarvis with GNU General Public License v2.0 | 6 votes |
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
Example #3
Source File: credentials.py From plugin.video.netflix with MIT License | 6 votes |
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 #4
Source File: test_pkcs1_15.py From jarvis with GNU General Public License v2.0 | 6 votes |
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:self.idx+N] self.idx += N return r # The real test cipher = PKCS.new(key, randfunc=randGen(t2b(test[3]))) ct = cipher.encrypt(b(test[1])) self.assertEqual(ct, t2b(test[2]))
Example #5
Source File: credentials.py From plugin.video.netflix with MIT License | 6 votes |
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 #6
Source File: test_pkcs1_oaep.py From jarvis with GNU General Public License v2.0 | 6 votes |
def testEncryptDecrypt2(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,RIPEMD160): # Verify that encrypt() asks for as many random bytes # as the hash output size asked = 0 pt = self.rng(40) cipher = PKCS.new(self.key1024, hashmod, randfunc=localRng) ct = cipher.encrypt(pt) self.assertEqual(cipher.decrypt(ct), pt) self.assertEqual(asked, hashmod.digest_size)
Example #7
Source File: test_pkcs1_15.py From jarvis with GNU General Public License v2.0 | 5 votes |
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 #8
Source File: number.py From jarvis with GNU General Public License v2.0 | 5 votes |
def getPrime(N, randfunc=None): """getPrime(N:int, randfunc:callable):long Return a random N-bit prime number. If randfunc is omitted, then Random.new().read is used. """ if randfunc is None: _import_Random() randfunc = Random.new().read number=getRandomNBitInteger(N, randfunc) | 1 while (not isPrime(number, randfunc=randfunc)): number=number+2 return number
Example #9
Source File: ElGamal.py From jarvis with GNU General Public License v2.0 | 5 votes |
def __init__(self, randfunc=None): if randfunc is None: randfunc = Random.new().read self._randfunc = randfunc
Example #10
Source File: test_DSA.py From jarvis with GNU General Public License v2.0 | 5 votes |
def test_generate_2arg(self): """DSA (default implementation) generated key (2 arguments)""" dsaObj = self.dsa.generate(1024, Random.new().read) self._check_private_key(dsaObj) pub = dsaObj.publickey() self._check_public_key(pub)
Example #11
Source File: test_pkcs1_15.py From jarvis with GNU General Public License v2.0 | 5 votes |
def testVerify2(self): # Verify that decryption fails if ciphertext is not as long as # RSA modulus cipher = PKCS.new(self.key1024) self.assertRaises(ValueError, cipher.decrypt, '\x00'*127, "---") self.assertRaises(ValueError, cipher.decrypt, '\x00'*129, "---") # Verify that decryption fails if there are less then 8 non-zero padding # bytes pt = b('\x00\x02' + '\xFF'*7 + '\x00' + '\x45'*118) pt_int = bytes_to_long(pt) ct_int = self.key1024._encrypt(pt_int) ct = long_to_bytes(ct_int, 128) self.assertEqual("---", cipher.decrypt(ct, "---"))
Example #12
Source File: test_pkcs1_oaep.py From jarvis with GNU General Public License v2.0 | 5 votes |
def testEncryptDecrypt4(self): # Verify that encrypt() uses the custom MGF global mgfcalls # Helper function to monitor what's requested from MGF def newMGF(seed,maskLen): global mgfcalls mgfcalls += 1 return bchr(0x00)*maskLen mgfcalls = 0 pt = self.rng(32) cipher = PKCS.new(self.key1024, mgfunc=newMGF) ct = cipher.encrypt(pt) self.assertEqual(mgfcalls, 2) self.assertEqual(cipher.decrypt(ct), pt)
Example #13
Source File: test_pkcs1_15.py From jarvis with GNU General Public License v2.0 | 5 votes |
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 #14
Source File: test_pkcs1_15.py From jarvis with GNU General Public License v2.0 | 5 votes |
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 #15
Source File: test_pkcs1_15.py From jarvis with GNU General Public License v2.0 | 5 votes |
def testEncryptVerify1(self): # Encrypt/Verify messages of length [0..RSAlen-11] # and therefore padding [8..117] for pt_len in range(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 #16
Source File: PKCS1_v1_5.py From jarvis with GNU General Public License v2.0 | 5 votes |
def new(key, randfunc=None): """Return a cipher object `PKCS115_Cipher` that can be used to perform PKCS#1 v1.5 encryption or decryption. :Parameters: key : RSA key object The key to use to encrypt or decrypt the message. This is a `Cryptodome.PublicKey.RSA` object. Decryption is only possible if *key* is a private RSA key. randfunc : callable Function that return random bytes. The default is `Cryptodome.Random.get_random_bytes`. """ if randfunc is None: randfunc = Random.get_random_bytes return PKCS115_Cipher(key, randfunc)
Example #17
Source File: test_pkcs1_oaep.py From jarvis with GNU General Public License v2.0 | 5 votes |
def testEncryptDecrypt3(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 #18
Source File: test_RSA.py From jarvis with GNU General Public License v2.0 | 5 votes |
def test_generate_3args(self): rsaObj = self.rsa.generate(1024, Random.new().read,e=65537) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj) self.assertEqual(65537,rsaObj.e)
Example #19
Source File: number.py From jarvis with GNU General Public License v2.0 | 5 votes |
def getRandomNBitInteger(N, randfunc=None): """getRandomInteger(N:int, randfunc:callable):long Return a random number with exactly N-bits, i.e. a random number between 2**(N-1) and (2**N)-1. 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. """ value = getRandomInteger (N-1, randfunc) value |= 2 ** (N-1) # Ensure high bit is set assert size(value) >= N return value
Example #20
Source File: number.py From jarvis with GNU General Public License v2.0 | 5 votes |
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
Example #21
Source File: crypto.py From snmpfwd with BSD 2-Clause "Simplified" License | 5 votes |
def decrypt(self, key, enc): iv = enc[:16] cipher = AES.new(str2octs(key), AES.MODE_CBC, iv) return self.unpad(cipher.decrypt(enc[16:]))
Example #22
Source File: crypto.py From snmpfwd with BSD 2-Clause "Simplified" License | 5 votes |
def encrypt(self, key, raw): raw = self.pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(str2octs(key), AES.MODE_CBC, iv) return iv + cipher.encrypt(raw)
Example #23
Source File: pycryptodome.py From flake8-bandit with MIT License | 5 votes |
def test_pycrypto(): key = b'Sixteen byte key' iv = Random.new().read(AES.block_size) cipher = pycrypto_arc2.new(key, AES.MODE_CFB, iv) factory = CryptoMaterialsCacheEntry()
Example #24
Source File: state.py From SATOSA with Apache License 2.0 | 5 votes |
def __init__(self, urlstate_data=None, encryption_key=None): """ If urlstate is empty a new empty state instance will be returned. If urlstate is not empty the constructor will rebuild the state attribute objects from the urlstate string. :type urlstate_data: str :type encryption_key: str :rtype: State :param encryption_key: The key to be used for encryption. :param urlstate_data: A string created by the method urlstate in this class. :return: An instance of this class. """ self.delete = False urlstate_data = {} if urlstate_data is None else urlstate_data if urlstate_data and not encryption_key: raise ValueError("If an 'urlstate_data' is supplied 'encrypt_key' must be specified.") if urlstate_data: urlstate_data = urlstate_data.encode("utf-8") urlstate_data = base64.urlsafe_b64decode(urlstate_data) lzma = LZMADecompressor() urlstate_data = lzma.decompress(urlstate_data) urlstate_data = _AESCipher(encryption_key).decrypt(urlstate_data) lzma = LZMADecompressor() urlstate_data = lzma.decompress(urlstate_data) urlstate_data = urlstate_data.decode("UTF-8") urlstate_data = json.loads(urlstate_data) session_id = ( urlstate_data[_SESSION_ID_KEY] if urlstate_data and _SESSION_ID_KEY in urlstate_data else uuid4().urn ) urlstate_data[_SESSION_ID_KEY] = session_id super().__init__(urlstate_data)
Example #25
Source File: state.py From SATOSA with Apache License 2.0 | 5 votes |
def decrypt(self, enc): """ Decryptes the parameter enc. :type enc: bytes :rtype: bytes :param: The value to be decrypted. :return: The decrypted value. """ enc = base64.urlsafe_b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) return self._unpad(cipher.decrypt(enc[AES.block_size:]))
Example #26
Source File: state.py From SATOSA with Apache License 2.0 | 5 votes |
def encrypt(self, raw): """ Encryptes the parameter raw. :type raw: bytes :rtype: str :param: bytes to be encrypted. :return: A base 64 encoded string. """ raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.urlsafe_b64encode(iv + cipher.encrypt(raw))
Example #27
Source File: pycryptodome.py From bandit with Apache License 2.0 | 5 votes |
def test_pycrypto(): key = b'Sixteen byte key' iv = Random.new().read(AES.block_size) cipher = pycrypto_arc2.new(key, AES.MODE_CFB, iv) factory = CryptoMaterialsCacheEntry()
Example #28
Source File: aes_handler.py From ontology-python-sdk with GNU Lesser General Public License v3.0 | 5 votes |
def generate_iv() -> bytes: return Random.new().read(AES.block_size)
Example #29
Source File: api.py From Commander with MIT License | 5 votes |
def encrypt_rsa(data, rsa_public_key): cipher = PKCS1_v1_5.new(rsa_public_key) encrypted_data = cipher.encrypt(data) return (base64.urlsafe_b64encode(encrypted_data).decode('utf-8')).rstrip('=')
Example #30
Source File: api.py From Commander with MIT License | 5 votes |
def encrypt_aes_key(key_to_encrypt, encryption_key): iv = os.urandom(16) cipher = AES.new(encryption_key, AES.MODE_CBC, iv) encrypted_data = iv + cipher.encrypt(key_to_encrypt) return (base64.urlsafe_b64encode(encrypted_data).decode()).rstrip('=')