def __init__(self, public_key=None, private_key=None, aes_key=None, iv=None, magic_bytes=MAGIC_BYTES): """ :param public_key: RSA object, required for encrypting :param private_key: RSA object, required for decrypting :param aes_key: 16 bytes length string for symmetric encrypting, required for encrypting :param iv: initialization vector (16 bytes length string), required for encrypting :param magic_bytes: 2 bytes length string for marking enconded message """ self.public_key = public_key self.private_key = private_key self.aes_key = aes_key or Random.new().read(AES.block_size) self.iv = iv or Random.new().read(AES.block_size) self.block_size = AES.block_size self.magic_bytes = magic_bytes self.aes_hashes = {} self.enc_aes_key = None self.aes_key_hash = None self.base_message = None self.rsa_private_cipher = PKCS1_OAEP.new(self.private_key, hashAlgo=SHA256, mgfunc=self._mgf1_fun) \ if self.private_key else None self.rsa_public_cipher = PKCS1_OAEP.new(self.public_key, hashAlgo=SHA256, mgfunc=self._mgf1_fun) \ if self.public_key else None self.aes_cipher = AES.new(self.aes_key, AES.MODE_CBC, self.iv)
def encMsg(msg, key): iv = Random.new().read(16) while(sys.getsizeof(iv) != 49): iv = Random.new().read(16) cipher = AES.new(key, AES.MODE_CFB, iv) msg = DIVIDER.join([iv, cipher.encrypt(msg)]) return msg
async def _encrypt_media( self, data: AsyncIterator[bytes], ) -> AsyncIterator[Union[bytes, EncryptedMediaInfo]]: aes256_key = Random.new().read(32) init_vector = Random.new().read(8) counter = Counter.new(64, prefix=init_vector, initial_value=0) cipher = AES.new(aes256_key, AES.MODE_CTR, counter=counter) sha256 = SHA256.new() async for chunk in data: encrypted = cipher.encrypt(chunk) sha256.update(encrypted) yield encrypted yield EncryptedMediaInfo( mxc=MXC("mxc://replace/me"), init_vector=encode_base64(init_vector + b"\x00" * 8), key=encode_base64(aes256_key, urlsafe=True), sha256=encode_base64(sha256.digest()), key_operations=["encrypt", "decrypt"], key_type="oct", key_algorithm="A256CTR", key_extractable=True, version="v2", )
def setKey(self, key): #self._Key=key self._Key = Random.new().read(32) self._value = Random.new().read(AES.block_size) self._aes = AES.new(self._Key, AES.MODE_CBC, self._value)
def encrypt(plaintext, key, keylen=KEYLEN): """Encrypt bytes using AES-CBC with keys of length `keylen` (defaults to KEYLEN: 256 bits). Key is passed in KDF `PBKDF2` in order to protect weak keys against brute force attacks. @param plaintext: Data to be encrypted. @type plaintext: bytes @param key: Encryption passphrase. @type key: str, bytes @param keylen: Length of the key to use in bytes. Can be either 16, 24 or 32. @type keylen: str, bytes @return: The produced ciphertext. @rtype : bytes @raise ValueError: Incorrect padding. Happens if passphrase is incorrect. """ salt = Random.new().read(AES.block_size) iv = Random.new().read(AES.block_size) key = KDF.PBKDF2(key, salt, dkLen=keylen) plaintext = Padding.pad(plaintext, AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv=iv) return base64.b64encode(salt + iv + cipher.encrypt(plaintext))
def encrypt(message, publickeysrv): global DEBUG payload = [] timedelta = datetime.datetime.now() if DEBUG: print('[{}] [Main] > Generating signature.'.format( datetime.datetime.now())) #################################################################################################### myhash = SHA256.new(message) signature = PKCS1_v1_5.new(privatekeycli) signature = signature.sign(myhash) if DEBUG: print('[{}] [Main] > Message succesefully signed with signature.'.format( datetime.datetime.now())) # signature encrypt if DEBUG: print('[{}] [Main] > Encrypting signature.'.format( datetime.datetime.now())) cipherrsa = PKCS1_OAEP.new(publickeysrv) sig = cipherrsa.encrypt(signature[:128]) sig = sig + cipherrsa.encrypt(signature[128:]) payload.append(sig) #################################################################################################### if DEBUG: print('[{}] [Main] > Generating 256 bit session key.'.format( datetime.datetime.now())) # creation 256 bit session key sessionkey = Random.new().read(32) # 256 bit # encryption AES of the message if DEBUG: print('[{}] [Main] > Encryption AES of the message.'.format( datetime.datetime.now())) iv = Random.new().read(16) # 128 bit obj = AES.new(sessionkey, AES.MODE_CFB, iv) ciphertext = iv + obj.encrypt(message) # SEND DATA payload.append(ciphertext) # encryption RSA of the session key if DEBUG: print('[{}] [Main] > Encryption RSA of the session key.'.format( datetime.datetime.now())) cipherrsa = PKCS1_OAEP.new(publickeysrv) sessionkey = cipherrsa.encrypt(sessionkey) # SEND DATA payload.append(sessionkey) payload1 = b'\x00\x01\x01\x00'.join(payload) if DEBUG: print('[{}] [Main] > Message succesefully encrypted for {} seconds.'.format( datetime.datetime.now(), (datetime.datetime.now() - timedelta).total_seconds())) payload_recieved = payload1.split(b'\x00\x01\x01\x00') if payload == payload_recieved and len(payload) == 3: if DEBUG: print('[{}] [Main] > Payload not corrupted.'.format( datetime.datetime.now())) return(payload1) else: print('[{}] [Main] > Error : Message corrupted! Payload parts {}/{}/3'.format( datetime.datetime.now(), len(payload), len(payload_recieved))) return(b'')
def test_aes_gcm_with_iv_wrong_iv(self): key = b'Sixteen byte key' plain_text = b'Attack at dawn' hdr = b'To your eyes only' iv = Random.new().read(AES.block_size) mac, cipher_text = AESHandler.aes_gcm_encrypt_with_iv(plain_text, hdr, key, iv) iv = Random.new().read(AES.block_size) decrypt_out = AESHandler.aes_gcm_decrypt_with_iv(cipher_text, hdr, mac, key, iv) self.assertNotEqual(plain_text, decrypt_out)
def predict_rating(self, i, k): # predict rating of user i, item k denoted P_i,k enc_obj = ElGamal.construct( (self.p, self.g, self.user_list[i].getPubKey())) encrypted_ratings = self.user_list[i].sendRatings(self.m) sum_of_sims = 0 l = 10 #modified top_l = sorted(range(len(self.simMat[k])), key=lambda i: self.simMat[k][i])[-1 * l:] #modified #print(top_l) #print(self.simMat[k]) for j in range(self.m): if k != j: sum_of_sims += self.simMat[k][j] R_k = self.avg_ratings[k] * 200 #print(R_k) #print(sum_of_sims) #print(R_k*sum_of_sims) a = number.getRandomRange(2, self.p - 1, Random.new().read) first_term = elgEncrypt(enc_obj, pow(self.g, int(R_k * sum_of_sims), self.p), a) result = (1, 1) result = self.addElgamal(result, first_term, self.p) for j in range(self.m): if k != j: a = number.getRandomRange(2, self.p - 1, Random.new().read) R_j = self.avg_ratings[j] * 200 denom = elgEncrypt(enc_obj, pow(self.g, int(R_j), self.p), a) denom_inv = self.inv_pair(denom) inter_result = self.addElgamal(encrypted_ratings[j], denom_inv, self.p) #inter_result = encrypted_ratings[j] inter_result = (inter_result[0]**self.simMat[k][j], inter_result[1]**self.simMat[k][j]) result = self.addElgamal(result, inter_result, self.p) a = number.getRandomRange(2, self.p - 1, Random.new().read) encrypted_denom = elgEncrypt(enc_obj, pow(self.g, sum_of_sims, self.p), a) # send results to user obtain rating predicted_rating = self.user_list[i].calculate_prediction( result, encrypted_denom) result = predicted_rating / 200 #result = self.avg_ratings[k]# only the average if result > 5: result = 5 return result
def send_precinct(): id = ObjectId(request.args.get('id')) text = request.args.get('text') if session['rank'] == 'worker2.1' or session[ 'rank'] == 'worker2.2' or session['rank'] == 'worker2.3': privatekey = RSA.importKey( db.find_one({'username': session['username']})['privatekey']) myhash = SHA.new(bytes(text, encoding='ascii')) signature = PKCS1_v1_5.new(privatekey) signature = signature.sign(myhash) publickey = RSA.importKey( db.find_one({'rank': 'worker3'})['publickey']) cipherrsa = PKCS1_OAEP.new(publickey) sig = cipherrsa.encrypt(signature[:128]) sig = sig + cipherrsa.encrypt(signature[128:]) sig = bytes(sig) sessionkey = Random.new().read(32) iv = Random.new().read(16) obj = AES.new(sessionkey, AES.MODE_CFB, iv) ciphertext = iv + obj.encrypt(bytes(text, encoding='ascii')) ciphertext = bytes(ciphertext) sessionkey = cipherrsa.encrypt(sessionkey) sessionkey = bytes(sessionkey) applic.update_one({'application': text}, { "$set": { 'check': None, 'level': 'worker3', 'sessionkey': sessionkey, 'application': ciphertext, 'signature': sig, 'publickey1': db.find_one({'username': session['username']})['publickey'] } }) flash('You sent the application!') elif session['rank'] == 'worker3': applic.update_one( {'_id': id}, {"$set": { 'check': None, 'level': 'end', 'status': 'Finished' }}) flash('You finished this case!') return redirect('/profile')
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_tampering(self): password = '******' * 100 key = passwort.generate_key() k1 = passwort.Keychain() k1.use_key(key) k1.set('example.com', passwort.Keychain.PASSWORD_FIELD, password) k1.save(self.temp_filename) v1 = k1.get('example.com', passwort.Keychain.PASSWORD_FIELD) self.assertEqual(v1, password) k2 = passwort.Keychain() k2.use_key(key) k2.load(self.temp_filename) v2 = k2.get('example.com', passwort.Keychain.PASSWORD_FIELD) self.assertEqual(v2, v1) tmp = open(self.temp_filename) data = json.load(tmp) tmp.close() enc_password_value = base64.b64decode(data['example.com']['password']['text']) tampered_value = Random.new().read(16) + enc_password_value[16:] data['example.com']['password']['text'] = base64.b64encode(tampered_value).decode() f = open(self.temp_filename, "w") f.write(json.dumps(data)) f.close() k3 = passwort.Keychain() k3.use_key(key) k3.load(self.temp_filename) with self.assertRaises(NameError): k3.get('example.com', passwort.Keychain.PASSWORD_FIELD)
def generate_keys(): random_generator = Random.new().read key = RSA.generate(1024, random_generator) with open(PRIVATE_KEY_FILE, 'wb') as f: f.write(key.exportKey('DER')) with open(PUBLIC_KEY_FILE, 'wb') as f: f.write(key.publickey().exportKey('DER'))
def newkeys(keysize): logger = logging.getLogger(__name__) logger.info("Generating key, size=%dc" % keysize) random_generator = Random.new().read key = RSA.generate(keysize, random_generator) private, public = key, key.publickey() return public, private
def build_cipher(key, iv, alg="aes_128_cbc"): """ :param key: encryption key :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ typ, bits, cmode = alg.split("_") if not iv: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise AESError("Unsupported key length") try: assert len(key) == int(bits) >> 3 except AssertionError: raise AESError("Wrong Key length") try: return AES.new(tobytes(key), POSTFIX_MODE[cmode], tobytes(iv)), iv except KeyError: raise AESError("Unsupported chaining mode")
def __encrypt(self, cipher, data): "Encrypts data" # get data sizes blocks = (len(data) // 7) + 1 size = 8 * blocks # add noise rand = Random.new() data += b'\x00' + rand.read(size - len(data) - 1) # rotate data rotated = b"" for block in range(blocks): for offset in range(8): rotated += bytes((data[offset * blocks + block], )) data = rotated # encrypt data data = cipher.encrypt(data) # ascii-armor data res = b"" for i in range(len(data)): high = data[i] // 16 low = data[i] - high * 16 res += bytes((ord("a") + high, ord("a") + low)) data = res return data
def _generateRSAKey(self, BITS=2048, PKCS=8): random_generator = Random.new().read passPhrase = self._passPhrase # ValueError: RSA key format is not supported passPhrase = None # Funziona print ('generating..... key') key = Crypto.PublicKey.RSA.generate(BITS, random_generator) print ('created.......', key) print ('encrypting..... key') privateKey = key.exportKey(passphrase=passPhrase, pkcs=PKCS, protection="scryptAndAES128-CBC") print ('creating....... PrivateKey to file:', self._privateKeyFile) file = open(self._privateKeyFile, "wb") file.write(privateKey) file.close() print ('creating....... PublicKey to file:', self._publicKeyFile) file = open(self._publicKeyFile, "wb") file.write(key.publickey().exportKey()) file.close() print ('key.can_encrypt......: ', key.can_encrypt()) print ('key.can_sign.........: ', key.can_sign()) print ('key.has_private......: ', key.has_private())
def decrypt(self, ciphertext, key, padding="pkcs1_padding"): if padding == "pkcs1_padding": cipher = PKCS1_v1_5.new(key) if self.with_digest: dsize = SHA.digest_size else: dsize = 0 sentinel = Random.new().read(32 + dsize) text = cipher.decrypt(ciphertext, sentinel) if dsize: _digest = text[-dsize:] _msg = text[:-dsize] digest = SHA.new(_msg).digest() if digest == _digest: text = _msg else: raise DecryptionFailed() else: if text == sentinel: raise DecryptionFailed() elif padding == "pkcs1_oaep_padding": cipher = PKCS1_OAEP.new(key) text = cipher.decrypt(ciphertext) else: raise Exception("Unsupported padding") return text
def build_cipher(self, iv="", alg="aes_128_cbc"): """ :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ typ, bits, cmode = alg.split("_") if not iv: if self.iv: iv = self.iv else: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise Exception("Unsupported key length") try: assert len(self.key) == int(bits) >> 3 except AssertionError: raise Exception("Wrong Key length") try: return AES.new(self.key, POSTFIX_MODE[cmode], iv), iv except KeyError: raise Exception("Unsupported chaining mode")
def aes(origin): print("\ncipher type(DES/DES3/AES/ARS4): AES") while True: key = input("key(16/24/32): ").encode('utf-8') if len(key) not in (16, 24, 32): print( "check key's length, input key's length should be (16,24,32)") else: break bs = AES.block_size # bs(block size) : 16 byte iv = Random.new().read(bs) # initial vector : 16 byte string = _pad(origin, bs) #padding 함 # encrypt cipher = AES.new(key, AES.MODE_CBC, IV=iv) cipher_text = iv + cipher.encrypt(string.encode('utf-8')) print(f"encrypted: {cipher_text}") # decrypt iv = cipher_text[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, IV=iv) plain_text = _unpad(cipher.decrypt( cipher_text[AES.block_size:])).decode('utf-8') print(f"decrypted: {plain_text}")
def generate_keys(self): private_key = RSA.generate(1024, CRandom.new().read) public_key = private_key.publickey() read_private_key = binascii.hexlify(private_key.exportKey(format='DER')).decode('ascii') read_public_key = binascii.hexlify(public_key.exportKey(format='DER')).decode('ascii') self.__private_key = read_private_key self.__public_key = read_public_key
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 encrypt(key, raw): assert type(raw) == bytes, "input data is bytes" key = b64decode(key.encode()) raw = AESCipher._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return iv + cipher.encrypt(raw)
def encrypt(message, passphrase): salt = Random.new().read(8) key_iv = bytes_to_key(passphrase, salt, 32 + 16) key = key_iv[:32] iv = key_iv[32:] aes = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(b"Salted__" + salt + aes.encrypt(pad(message)))
def encrypt(self, raw, key, iv=None): raw = self._pad(raw) if iv is None: iv = Random.new().read(AES.block_size) hashkey = hashlib.sha256(key.encode()).digest() cipher = AES.new(hashkey, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw.encode()))
def encrypt_data(self, login_id, login_password, account_password, certificate_password, given_key=None, file_name=None): plain_data = ';'.join((login_id, login_password, account_password, certificate_password)) if file_name is not None: self.file_name = file_name # key setting random = Random.new() raw_key = given_key if raw_key is None: raw_key = self.raw_key set_key = self.set_key(raw_key) iv = random.read(AES.block_size) encoded_key = set_key.encode() key = strxor.strxor(encoded_key, iv) # Encryption encoded_data = plain_data.encode() padded_data = Padding.pad(encoded_data, AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) encrypted_data = cipher.encrypt(padded_data) # File writing with open(self.file_name, 'wb') as file: file.write(iv) file.write(encrypted_data)
def encrypt_aes(): from Cryptodome.Cipher import AES from Cryptodome import Random import binascii text = 'Welcome to AES' # 密钥key 长度必须为16(AES-128)、24(AES-192)或 32(AES-256)的Bytes长度 key = b'1234567890ABCDEF' # 生成长度等于AES块大小的不可重复的密钥向量 iv = Random.new().read(AES.block_size) # 使用 key 和 iv 初始化AES对象,使用 AES.MODE_CFB 模式 aes = AES.new(key, AES.MODE_CFB, iv) # 加密 result = aes.encrypt(text.encode()) # 解密 # 不能在encrypt()之后调用decrypt() # 需要用相同的key和iv初始化新的AES对象 decrypt_aes = AES.new(key, AES.MODE_CFB, iv) print('密钥:', key) print('iv:', iv) print('十六进制的iv:', binascii.b2a_hex(iv)) print('加密后的数据:', result) print('转为十六进制:', binascii.b2a_hex(result)) print('解密后的数据:', decrypt_aes.decrypt(result))
def generate_keys(self, keys_size=2048, public_key_format='PEM', private_key_format='PEM'): """Generates new RSA keys Args: keys_size (int or None): Keys size (default is 2048) [optional] public_key_format (str or None): Public key format (default is PEM) [optional] private_key_format (str or None): Private key format (default is PEM) [optional] Note: Keys formats: - **PEM** (default) - text encoding - **DER** - binary encoding - **OpenSSH** - textual encoding, done according to OpenSSH specification. Only suitable for public keys. """ random_generator = Random.new().read keys = RSA.generate(keys_size, random_generator) with open(self.__public_key_loc, 'wb') as public_key_file: public_key_file.write(keys.publickey().exportKey( format=public_key_format, passphrase=self.__public_key_passphrase)) with open(self.__private_key_loc, 'wb') as private_key_file: private_key_file.write( keys.exportKey(format=private_key_format, passphrase=self.__private_key_passphrase))
def hide(self, input_filename, output_filename, data): """ Encrypt and save the data inside the image. :param input_filename: Input image file path :param output_filename: Output image file path :param data: Information to be encrypted and saved :return: """ # Generate a random initialization vector iv = Random.new().read(AES.block_size) encryption_suite = AES.new(self.key, AES.MODE_CBC, iv) # If it is string convert to byte string before use it if isinstance(data, str): data = data.encode() # Encrypt the random initialization vector concatenated # with the padded data cypher_data = encryption_suite.encrypt(iv + pad(data, self.block_size)) # Convert the cypher byte string to a base64 string to avoid # decode padding error cypher_data = base64.b64encode(cypher_data).decode() # Hide the encrypted message in the image with the LSB # (Least Significant Bit) technique. secret = lsb.hide(input_filename, cypher_data) # Save the image file secret.save(output_filename)
def encrypt(key, filename): chunk_size = 64 * 1024 output_file = "encrypted" + filename file_size = os.path.getsize(filename) iv = Random.new().read(DES3.block_size) cipher = DES3.new(key=key, mode=DES3.MODE_CBC, iv=iv) with open(filename, 'rb') as in_file: with open(output_file, 'wb') as out_file: out_file.write(struct.pack('<Q', file_size)) out_file.write(iv) while True: chunk = in_file.read(chunk_size) if len(chunk) == 0: break elif len(chunk) % 8 != 0: chunk += b' ' * (8 - len(chunk) % 8) out_file.write(cipher.encrypt(chunk)) output_key = filename + '.key' with open(output_key, 'wb') as out_key: out_key.write(key)
def __init__(self,key,iv=None,mode=AES.MODE_CFB): self.key=key self.mode=mode if iv: self.iv = iv else: self.iv = Random.new().read(AES.block_size)
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: print "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 encrypt(self, raw): raw = raw.encode() length = AES.block_size - (len(raw) % AES.block_size) raw += bytes([length]) * length # store padding length length'th times iv = Random.new().read(AES.block_size) aes = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + aes.encrypt(raw))
def encipher(keyA_fname, keyB_fname, file, password): # Opening file to encrypt in binary reading mode f = open(file, "rb") buffer = f.read() f.close() # Generating file's signature (and saving it) sigGenerator(keyA_fname, file, password) # Generating initializing vector for AES Encryption iv = Random.new().read(AES.block_size) # Generating symmetric key for use (and saving it) k = keyGenerator(keyB_fname, file, iv) # Encrypting and saving result to *.bin file. Using CFB mode keyCipher = AES.new(str(k), AES.MODE_CFB, iv) f = open(file.split('.')[0] + ".bin", "wb") f.write(keyCipher.encrypt(buffer)) f.close()
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 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_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 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: print "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 __init__(self, key): self.rndfile = Random.new() if key == None: log.write("Initalizing key") self.key = self.rndfile.read(self.KEY_SIZE) keyfile = open(self.KEYFILE, 'wb'); keyfile.write(self.key) else: self.key = key self.IV = b"jamsomwareiscool"
def enc(enc_key, hmac_key, plaintext=None): plaintext_bytes = plaintext.encode() iv = Random.new().read(IV_SIZE) h = hmac(hmac_key) h.update(plaintext_bytes) hmac_tag = base64.b64encode(h.digest()).decode() ciphertext = base64.b64encode(cipher(enc_key, iv).encrypt(pad(plaintext_bytes))).decode() return dict(algorithm=ALGO_NAME, timestamp=calendar.timegm(time.gmtime()), iv=base64.b64encode(iv).decode(), hmac=hmac_tag, text=ciphertext)
def encode(self, raw): """ Encodes data :param data: Data to be encoded :type data: str :returns: string -- Encoded data """ raw = bytes(Padding.pad(data_to_pad=raw, block_size=self.bs)) iv = Random.new().read(AES.block_size) cipher = AES.new(self.crypt_key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw))
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))
def _random(**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 Integer.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 AesEncrypt(key, clearData, block_size=32, retType='hex'): b_clearData = clearData if isinstance(clearData, bytes) else clearData.encode(MY_UNICODE).strip() # covert to bytes b_key = key if isinstance(key, bytes) else key.encode(MY_UNICODE).strip() # covert to bytes # generate nounce b_nounce = Random.new().read(AES.block_size) # oppure nounce = Random.get_random_bytes(AES.block_size) # cript Data cipher = _getCipher(key=b_key, nounce=b_nounce, blkSize=block_size) b_cipheredData = cipher.encrypt(b_clearData) # cript key with cipheredData as key cipher = _getCipher(key=b_cipheredData, nounce=b_nounce, blkSize=block_size) b_cipheredKey = cipher.encrypt(b_key) if retType == 'hex': h_nounce = ''.join("%02x" % b for b in b_nounce) h_key = ''.join("%02x" % b for b in b_cipheredKey) h_data = ''.join("%02x" % b for b in b_cipheredData) myData = '' myData += '{:02x}'.format(len(h_nounce)) myData += '{:02x}'.format(len(h_key)) myData += '{:02x}'.format(len(h_data)) myData += '{:02x}'.format(block_size) myData += h_nounce myData += h_key myData += h_data elif retType == 'base64': nounce = base64.b64encode(b_nounce) data = base64.b64encode(cipheredData) key = base64.b64encode(cipheredKey) elif retType == 'bytes': pass return myData
def build_cipher(key, iv, alg="aes_128_cbc"): """ :param key: encryption key :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ typ, bits, cmode = alg.split("_") if not iv: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise AESError("Unsupported key length") if len(key) != int(bits) >> 3: raise AESError("Wrong Key length") try: return AES.new(tobytes(key), POSTFIX_MODE[cmode], tobytes(iv)), iv except KeyError: raise AESError("Unsupported chaining mode")
def generateRSAKey(passPhrase): print ('generating..... key') from Cryptodome.PublicKey import RSA from Cryptodome import Random random_generator = Random.new().read key = RSA.generate(2048, random_generator) print ('created.......', key) print ('encrypting..... key') encrypted_key = key.exportKey(passphrase=passPhrase, pkcs=8, protection="scryptAndAES128-CBC") print ('creating....... PrivateKey to file:', RSA_privKeyFile) file = open(RSA_privKeyFile, "wb") file.write(encrypted_key) file.close() print ('creating....... PublicKey to file:', RSA_pubKeyFile) file = open(RSA_pubKeyFile, "wb") file.write(key.publickey().exportKey()) file.close() print ('key.can_encrypt......: ', key.can_encrypt()) print ('key.can_sign.........: ', key.can_sign()) print ('key.has_private......: ', key.has_private())
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()
This file is part of Python TripleSec - a Python implementation of TripleSec Released under The BSD 3-Clause License Copyright (c) 2013 Keybase """ from __future__ import absolute_import import binascii import getpass import struct import six import sys from Cryptodome import Random rndfile = Random.new() from .utils import ( MAGIC_BYTES, TripleSecFailedAssertion, TripleSecDecryptionError, TripleSecError, _constant_time_compare, win32_utf8_argv ) from .versions import get_version, valid_version, LATEST_VERSION ### MAIN CLASS class TripleSec(): MAGIC_BYTES = MAGIC_BYTES
def generate_key(): return Random.new().read(KEY_SIZE)
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 ``Cryptodome.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 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) 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(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 __init__(self, randfunc=None): if randfunc is None: randfunc = Random.new().read self._randfunc = randfunc
def setUp(self): self.rng = Random.new().read self.key1024 = RSA.generate(1024, self.rng)
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 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.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 xrange(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 xrange(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