def generate_probable_safe_prime(**kwargs): """Generate a random, probable safe prime. Note this operation is much slower than generating a simple prime. :Keywords: exact_bits : integer The desired size in bits of the probable safe prime. randfunc : callable An RNG function where candidate primes are taken from. :Return: A probable safe prime in the range 2^exact_bits > p > 2^(exact_bits-1). """ exact_bits = kwargs.pop("exact_bits", None) randfunc = kwargs.pop("randfunc", None) if kwargs: raise ValueError("Unknown parameters: " + kwargs.keys()) if randfunc is None: randfunc = Random.new().read result = COMPOSITE while result == COMPOSITE: q = generate_probable_prime(exact_bits=exact_bits - 1, randfunc=randfunc) candidate = q * 2 + 1 if candidate.size_in_bits() != exact_bits: continue result = test_probable_prime(candidate, randfunc=randfunc) return candidate
def __init__(self): self.socket = socket.socket() self.key = Random.new().read(int(16)) self.crypto = Crypto() self.Aesob = AESC(self.key) self.systemc = System.system() self.monitorc = Monitor.monitor()
def getrandbits(self, k): """Return an integer with k random bits.""" if self._randfunc is None: self._randfunc = Random.new().read mask = (1 << k) - 1 return mask & bytes_to_long(self._randfunc(ceil_div(k, 8)))
def _test_random_key(self, bits): elgObj = ElGamal.generate(bits, Random.new().read) self._check_private_key(elgObj) self._exercise_primitive(elgObj) pub = elgObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(elgObj)
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)
def test_generate_2arg(self): """RSA (default implementation) generated key (2 arguments)""" rsaObj = self.rsa.generate(1024, Random.new().read) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj)
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)
def generate_probable_prime(**kwargs): """Generate a random probable prime. The prime will not have any specific properties (e.g. it will not be a *strong* prime). Random numbers are evaluated for primality until one passes all tests, consisting of a certain number of Miller-Rabin tests with random bases followed by a single Lucas test. The number of Miller-Rabin iterations is chosen such that the probability that the output number is a non-prime is less than 1E-30 (roughly 2^{-100}). This approach is compliant to `FIPS PUB 186-4`__. :Keywords: exact_bits : integer The desired size in bits of the probable prime. It must be at least 160. randfunc : callable An RNG function where candidate primes are taken from. prime_filter : callable A function that takes an Integer as parameter and returns True if the number can be passed to further primality tests, False if it should be immediately discarded. :Return: A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1). .. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf """ exact_bits = kwargs.pop("exact_bits", None) randfunc = kwargs.pop("randfunc", None) prime_filter = kwargs.pop("prime_filter", lambda x: True) if kwargs: raise ValueError("Unknown parameters: " + kwargs.keys()) if exact_bits is None: raise ValueError("Missing exact_bits parameter") if exact_bits < 160: raise ValueError("Prime number is not big enough.") if randfunc is None: randfunc = Random.new().read result = COMPOSITE while result == COMPOSITE: candidate = Integer.random(exact_bits=exact_bits, randfunc=randfunc) | 1 if not prime_filter(candidate): continue result = test_probable_prime(candidate, randfunc) return candidate
def test_probable_prime(candidate, randfunc=None): """Test if a number is prime. A number is qualified as prime if it passes a certain number of Miller-Rabin tests (dependent on the size of the number, but such that probability of a false positive is less than 10^-30) and a single Lucas test. For instance, a 1024-bit candidate will need to pass 4 Miller-Rabin tests. :Parameters: candidate : integer The number to test for primality. randfunc : callable The routine to draw random bytes from to select Miller-Rabin bases. :Returns: ``PROBABLE_PRIME`` if the number if prime with very high probability. ``COMPOSITE`` if the number is a composite. For efficiency reasons, ``COMPOSITE`` is also returned for small primes. """ if randfunc is None: randfunc = Random.new().read if not isinstance(candidate, Integer): candidate = Integer(candidate) # First, check trial division by the smallest primes if int(candidate) in _sieve_base: return PROBABLY_PRIME try: map(candidate.fail_if_divisible_by, _sieve_base) except ValueError: return COMPOSITE # These are the number of Miller-Rabin iterations s.t. p(k, t) < 1E-30, # with p(k, t) being the probability that a randomly chosen k-bit number # is composite but still survives t MR iterations. mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10), (620, 7), (740, 6), (890, 5), (1200, 4), (1700, 3), (3700, 2)) bit_size = candidate.size_in_bits() try: mr_iterations = list(filter(lambda x: bit_size < x[0], mr_ranges))[0][1] except IndexError: mr_iterations = 1 if miller_rabin_test(candidate, mr_iterations, randfunc=randfunc) == COMPOSITE: return COMPOSITE if lucas_test(candidate) == COMPOSITE: return COMPOSITE return PROBABLY_PRIME
def encrypt(plaintext): iv = Random.new().read(AES.block_size) #add padding if (len(plaintext) % 16 != 0): plaintext += b'_' * (16 - len(plaintext) % 16) cipher = AES.new(shared_key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(plaintext) return hexlify(iv) + b"," + hexlify(ciphertext) + b"\n"
def setup_crypto(self, sn): """ Performs decryption of packets received. Stores decrypted packets in a Queue for use. """ if is_old_model(sn): self.old_model = True # print self.old_model k = ['\0'] * 16 k[0] = sn[-1] k[1] = '\0' k[2] = sn[-2] if self.is_research: k[3] = 'H' k[4] = sn[-1] k[5] = '\0' k[6] = sn[-2] k[7] = 'T' k[8] = sn[-3] k[9] = '\x10' k[10] = sn[-4] k[11] = 'B' else: k[3] = 'T' k[4] = sn[-3] k[5] = '\x10' k[6] = sn[-4] k[7] = 'B' k[8] = sn[-1] k[9] = '\0' k[10] = sn[-2] k[11] = 'H' k[12] = sn[-3] k[13] = '\0' k[14] = sn[-4] k[15] = 'P' key = ''.join(k) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_ECB, iv) # for i in k: # print "0x%.02x " % (ord(i)) while self.running: while not tasks.empty(): task = tasks.get() try: data = cipher.decrypt(task[:16]) + cipher.decrypt(task[16:]) self.packets.put_nowait(EmotivPacket(data, self.sensors, self.old_model)) self.packets_processed += 1 except: pass gevent.sleep(0) gevent.sleep(0)
def __init__(self): self.block_size = None self.block_fill = None self.current_len = None self.original_len = None self.startyet = False self.current_block = None self.current_byte = None self.data = None self.is_success = False self.rstr = Random.new().read(random.choice(range(5,20))) print(getbytestr("Original String is - ")+self.rstr) #self.rstr = getbytestr("a") self.plaintext = ""
def random(cls, **kwargs): """Generate a random natural integer of a certain size. :Keywords: exact_bits : positive integer The length in bits of the resulting random Integer number. The number is guaranteed to fulfil the relation: 2^bits > result >= 2^(bits - 1) max_bits : positive integer The maximum length in bits of the resulting random Integer number. The number is guaranteed to fulfil the relation: 2^bits > result >=0 randfunc : callable A function that returns a random byte string. The length of the byte string is passed as parameter. Optional. If not provided (or ``None``), randomness is read from the system RNG. :Return: a Integer object """ exact_bits = kwargs.pop("exact_bits", None) max_bits = kwargs.pop("max_bits", None) randfunc = kwargs.pop("randfunc", None) if randfunc is None: randfunc = Random.new().read if exact_bits is None and max_bits is None: raise ValueError( "Either 'exact_bits' or 'max_bits' must be specified") if exact_bits is not None and max_bits is not None: raise ValueError( "'exact_bits' and 'max_bits' are mutually exclusive") bits = exact_bits or max_bits bytes_needed = ((bits - 1) // 8) + 1 significant_bits_msb = 8 - (bytes_needed * 8 - bits) msb = bord(randfunc(1)[0]) if exact_bits is not None: msb |= 1 << (significant_bits_msb - 1) msb &= (1 << significant_bits_msb) - 1 return cls.from_bytes(bchr(msb) + randfunc(bytes_needed - 1))
def random_range(cls, **kwargs): """Generate a random integer within a given internal. :Keywords: min_inclusive : integer The lower end of the interval (inclusive). max_inclusive : integer The higher end of the interval (inclusive). max_exclusive : integer The higher end of the interval (exclusive). randfunc : callable A function that returns a random byte string. The length of the byte string is passed as parameter. Optional. If not provided (or ``None``), randomness is read from the system RNG. :Returns: An Integer randomly taken in the given interval. """ min_inclusive = kwargs.pop("min_inclusive", None) max_inclusive = kwargs.pop("max_inclusive", None) max_exclusive = kwargs.pop("max_exclusive", None) randfunc = kwargs.pop("randfunc", None) if kwargs: raise ValueError("Unknown keywords: " + str(kwargs.keys)) if None not in (max_inclusive, max_exclusive): raise ValueError("max_inclusive and max_exclusive cannot be both" " specified") if max_exclusive is not None: max_inclusive = max_exclusive - 1 if None in (min_inclusive, max_inclusive): raise ValueError("Missing keyword to identify the interval") if randfunc is None: randfunc = Random.new().read norm_maximum = max_inclusive - min_inclusive bits_needed = cls(norm_maximum).size_in_bits() norm_candidate = -1 while not 0 <= norm_candidate <= norm_maximum: norm_candidate = cls.random(max_bits=bits_needed, randfunc=randfunc) return norm_candidate + min_inclusive
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)
def runTest(self): """Crypto.Random.new()""" # Import the Random module and try to use it from crypto 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 crypto.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 = list(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 = list(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) self.assertRaises(TypeError, random.shuffle, "11") self.assertRaises(TypeError, random.shuffle, (1,2)) # 2to3 wraps a list() around it, alas - but I want to shoot # myself in the foot here! :D # if sys.version_info[0] == 3: # self.assertRaises(TypeError, random.shuffle, range(3)) # Test sample x = random.sample(seq, 20) y = random.sample(seq, 20) self.assertNotEqual(x, y) for i in range(20): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) z = random.sample([1], 1) self.assertEqual(z, [1]) z = random.sample((1,2,3), 1) self.assertEqual(z[0] in (1,2,3), True) z = random.sample("123", 1) self.assertEqual(z[0] in "123", True) z = random.sample(list(range(3)), 1) self.assertEqual(z[0] in range(3), True) if sys.version_info[0] == 3: z = random.sample(b("123"), 1) self.assertEqual(z[0] in b("123"), True) z = random.sample(bytearray(b("123")), 1) self.assertEqual(z[0] in bytearray(b("123")), True) self.assertRaises(TypeError, random.sample, 1)
def encrypt(data, passphrase, protection, prot_params=None, randfunc=None): """Encrypt a piece of data using a passphrase and *PBES2*. :Parameters: data : byte string The piece of data to encrypt. passphrase : byte string The passphrase to use for encrypting the data. protection : string The identifier of the encryption algorithm to use. The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'. prot_params : dictionary Parameters of the protection algorithm. +------------------+-----------------------------------------------+ | Key | Description | +==================+===============================================+ | iteration_count | The KDF algorithm is repeated several times to| | | slow down brute force attacks on passwords | | | (called *N* or CPU/memory cost in scrypt). | | | | | | The default value for PBKDF2 is 1 000. | | | The default value for scrypt is 16 384. | +------------------+-----------------------------------------------+ | salt_size | Salt is used to thwart dictionary and rainbow | | | attacks on passwords. The default value is 8 | | | bytes. | +------------------+-----------------------------------------------+ | block_size | *(scrypt only)* Memory-cost (r). The default | | | value is 8. | +------------------+-----------------------------------------------+ | parallelization | *(scrypt only)* CPU-cost (p). The default | | | value is 1. | +------------------+-----------------------------------------------+ randfunc : callable Random number generation function; it should accept a single integer N and return a string of random data, N bytes long. If not specified, a new RNG will be instantiated from ``Crypto.Random``. :Returns: The encrypted data, as a binary string. """ if prot_params is None: prot_params = {} if randfunc is None: randfunc = Random.new().read if protection == 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC': key_size = 24 module = DES3 cipher_mode = DES3.MODE_CBC enc_oid = "1.2.840.113549.3.7" elif protection in ('PBKDF2WithHMAC-SHA1AndAES128-CBC', 'scryptAndAES128-CBC'): key_size = 16 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.2" elif protection in ('PBKDF2WithHMAC-SHA1AndAES192-CBC', 'scryptAndAES192-CBC'): key_size = 24 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.22" elif protection in ('PBKDF2WithHMAC-SHA1AndAES256-CBC', 'scryptAndAES256-CBC'): key_size = 32 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.42" else: raise ValueError("Unknown PBES2 mode") # Get random data iv = randfunc(module.block_size) salt = randfunc(prot_params.get("salt_size", 8)) # Derive key from password if protection.startswith('PBKDF2'): count = prot_params.get("iteration_count", 1000) key = PBKDF2(passphrase, salt, key_size, count) kdf_info = DerSequence([ DerObjectId("1.2.840.113549.1.5.12"), # PBKDF2 DerSequence([DerOctetString(salt), DerInteger(count)]) ]) else: # It must be scrypt count = prot_params.get("iteration_count", 16384) scrypt_r = prot_params.get('block_size', 8) scrypt_p = prot_params.get('parallelization', 1) key = scrypt(passphrase, salt, key_size, count, scrypt_r, scrypt_p) kdf_info = DerSequence([ DerObjectId("1.3.6.1.4.1.11591.4.11"), # scrypt DerSequence([ DerOctetString(salt), DerInteger(count), DerInteger(scrypt_r), DerInteger(scrypt_p) ]) ]) # Create cipher and use it cipher = module.new(key, cipher_mode, iv) encrypted_data = cipher.encrypt(pad(data, cipher.block_size)) enc_info = DerSequence([DerObjectId(enc_oid), DerOctetString(iv)]) # Result enc_private_key_info = DerSequence([ # encryptionAlgorithm DerSequence([ DerObjectId("1.2.840.113549.1.5.13"), # PBES2 DerSequence([kdf_info, enc_info]), ]), DerOctetString(encrypted_data) ]) return enc_private_key_info.encode()
def setUp(self): self.rng = Random.new().read self.key1024 = RSA.generate(1024, self.rng)
def encrypt(self, raw): raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw))
def encrypt(self, text, key, key_size=256): text = self.padding(text) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return iv + cipher.encrypt(text)
#is socket server file use for response to client from socket import * import time import pyaes import hashlib import base64 # import os # from sys import path import urllib3 import ctypes from crypto import Random arr = [1, 2, 3, 4, 5, 6, 7, 78, 8] res = Random.new(arr) print(res) # ctypes. s = socket(2, 1) s.bind(('192.168.1.100', 1234)) s.listen(5) s.settimeout(10000) print("runing ...\n") # data = 'hello world alireza'.encode() # hashcode = hashlib.shake_128(data) aes = pyaes.AESModeOfOperationCTR('hello123P{/e3sc}'.encode()) en = aes.encrypt( 'hello world that is your chance for live better than another people for live better'
AES Encryption Demo This Program illustrates working of AES encryption . HMAC is also used. This program is written from windows point of view in Python 3.5 Author: Vishvajeet Patil ''' import Crypto #Same as Crypto package on linux systems. import sys sys.modules[ 'crypto'] = Crypto #Makes crypto module workable on windows systems from crypto import Random #Imports cryptographically Secure Random module from crypto.Cipher import AES #Imports AES cipher import hmac import hashlib #Key and IV(Initialization Vector) generation key = Random.new().read(AES.block_size) iv = Random.new().read(AES.block_size) #Function to pad messages def pad(s): '''This function returns the padded message for given parameter string s according to PKCS7 standard which is used with AES ciphers''' n = AES.block_size return s + ((n - len(s) % n) * chr(n - len(s) % n)).encode('UTF-8') #Function to unpad messages def unpad(s): '''This function returns the unpadded version of given parameter string s according to PKCS7 standard which is used with AES ciphers'''
def generate(): global key key = Random.new().read(AES.block_size) global iv iv = Random.new().read(AES.block_size)
def miller_rabin_test(candidate, iterations, randfunc=None): """Perform a Miller-Rabin primality test on an integer. The test is specified in Section C.3.1 of `FIPS PUB 186-4`__. :Parameters: candidate : integer The number to test for primality. iterations : integer The maximum number of iterations to perform before declaring a candidate a probable prime. randfunc : callable An RNG function where bases are taken from. :Returns: ``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``. .. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf """ if not isinstance(candidate, Integer): candidate = Integer(candidate) if candidate in (1, 2, 3, 5): return PROBABLY_PRIME if candidate.is_even(): return COMPOSITE one = Integer(1) minus_one = Integer(candidate - 1) if randfunc is None: randfunc = Random.new().read # Step 1 and 2 m = Integer(minus_one) a = 0 while m.is_even(): m >>= 1 a += 1 # Skip step 3 # Step 4 for i in iter_range(iterations): # Step 4.1-2 base = 1 while base in (one, minus_one): base = Integer.random_range(min_inclusive=2, max_inclusive=candidate - 2) assert (2 <= base <= candidate - 2) # Step 4.3-4.4 z = pow(base, m, candidate) if z in (one, minus_one): continue # Step 4.5 for j in iter_range(1, a): z = pow(z, 2, candidate) if z == minus_one: break if z == one: return COMPOSITE else: return COMPOSITE # Step 5 return PROBABLY_PRIME
import ast import time from crypto import Random from crypto.PublicKey import RSA from crypto.Cipher import PKCS1_OAEP start_time = time.time() random_generator = Random.new().read # Generates public and private key key = RSA.generate(1024, random_generator) # Exporting public key to global public_key = key.publickey() encryptor = PKCS1_OAEP.new(public_key) pause1 = time.time() # Choosing file to read message_file = input('Input filename for reading: ') with open(message_file, 'r') as message: data1 = message.read() data1 = str(data1) data1 = bytes(data1, 'utf-8') # Encryption data from read file continue1 = time.time() encrypted = encryptor.encrypt(data1)
def __init__(self, randfunc=None): if randfunc is None: randfunc = Random.new().read self._randfunc = randfunc