def dencrypt(data, outpath, key = None): #print "Encrypting to %s" % outpath bs = AES.block_size if key is None: key = Random.new().read(16) else: key = base64.b64decode(key) iv = Random.new().read(bs) encryptor = AES.new(key, AES.MODE_CBC, iv) #print "Key: %s" % base64.b64encode(key) #print "IV: %s" % base64.b64encode(iv) fin = io.BytesIO(data) fout = io.BytesIO() fout.write(iv) while True: chunk = fin.read(bs*1024) if len(chunk) == 0: break elif len(chunk) % bs != 0: chunk += b' ' * (bs - len(chunk) % bs) fout.write(encryptor.encrypt(chunk)) with open(outpath, 'wb') as f: f.write(fout.getvalue()) return base64.b64encode(key)
def new_key(self): ''' Get a new AES key and iv, localbox uses a self generated iv ''' key = Random.new().read(AES.key_size[2]) iv = Random.new().read(AES.block_size) return LoxKey(key, iv)
def encrypt(self, data): if self.initialized == 0 and self.is_server == False: taddr = self.proto.factory.tun.addr taddr_hash = SHA384.new(taddr).digest() iv = Random.new().read(AES.block_size) salt = Random.new().read(SALT_LEN) passwd = self.proto.factory.passwd self.key = PBKDF2(passwd, salt, dkLen=AES_KEYLEN*2, count=PBKDF2_ITERATIONS) self.aes_e = AES.new(self.key[:AES_KEYLEN], AES.MODE_CFB, iv) self.aes_d = AES.new(self.key[AES_KEYLEN:], AES.MODE_CFB, iv) data = iv+self.aes_e.encrypt(data) tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:SHA384_LEN] data = taddr_hash+salt+data+tag self.initialized = 1 else: data = self.aes_e.encrypt(data) tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:SHA384_LEN] data = data+tag return data
def encrypt_images(self, temp_dir, opened_files, sec_key): file_list = [] iv_list = [] sim_key = Random.new().read(self.length_AES) for f in opened_files: with open(f, 'rb') as fhI: file_name = ntpath.split(f)[1] file_path = temp_dir + "/" + file_name pic_data = fhI.read() iv = Random.new().read(16) iv_list.append(self.bin2b64(iv)) aes = AES.new(sim_key, AES.MODE_CFB, iv) enc_pic_data = aes.encrypt(pic_data) enc_pic_data_hex = self.bin2b64(enc_pic_data) # ovo ti i ne treba, zbog cuvanja mesta.. madaa? Izbacices, valja radit brze:D with open(file_path, 'w') as fhO: fhO.write(enc_pic_data_hex) abs_file_path = os.path.abspath(file_path) file_list.append(abs_file_path) esk = sec_key.encrypt(sim_key, 'x')[0] esk = self.bin2b64(esk) return [file_list, esk, iv_list]
def GetElgamalParamqp(bits = 100): while 1: q = bignum(getPrime(bits-1, Random.new().read)) p = 2*q+1 if number.isPrime(p, randfunc=Random.new().read): break return q,p
def encrypt(self): try: salt=Random.new().read(16) con_key=self.get_conkey() key2=binascii.hexlify(hashlib.pbkdf2_hmac('sha256',self.key.encode('utf-8'),salt,100000,16)) chunksize = 64*1024 if not os.path.exists(self.file): return FileNotFoundError("File Does not Exist") outputFile =os.path.join(os.path.dirname(self.file), "crypt."+os.path.basename(self.file)) filesize = str(os.path.getsize(self.file)).zfill(16) IV=Random.new().read(16) encryptor = AES.new(key2, AES.MODE_CBC, IV) with open(self.file, 'rb') as infile: with open(outputFile, 'wb') as outfile: outfile.write(filesize.encode('utf-8')) outfile.write(IV) outfile.write(con_key) outfile.write(salt) while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += b' ' * (16 - (len(chunk) % 16)) outfile.write(encryptor.encrypt(chunk)) os.remove(self.file) return "successfully Encrypted" except Exception as err: return 'An error occured:%s'%err
def encrypt_hmac(key: bytes, plaintext: str) -> bytes: """ encrypt(key, plaintext) -> Encrypts plaintext using key. """ # Generate a key from a salt and hashed key. salt = Random.new().read(SALT_LEN) valid_key = key_gen(key, salt) iv = Random.new().read(IV_LEN) padded_plaintext = PKCS7_pad(plaintext.encode(), AES.block_size) encrypt_obj = AES.new(valid_key, AES.MODE_CBC, iv) # Put the salt and iv at the start of the ciphertext so when it # needs to be decrypted the same salt and iv can be used. ciphertext = salt + iv + encrypt_obj.encrypt(padded_plaintext) hmac_key = Random.new().read(32) hmac = HMAC.new(hmac_key, digestmod=SHA512) hmac.update(ciphertext) hmac_digest = hmac.digest() # Encrypt the hmac key hmac_iv = Random.new().read(IV_LEN) hmac_encrypt_obj = AES.new(valid_key, AES.MODE_CBC, hmac_iv) encrypted_hmac_key = hmac_iv + hmac_encrypt_obj.encrypt(hmac_key) # ciphertext = encrypted hmac key + hmac digest + salt + iv + # encrypted data. ciphertext = encrypted_hmac_key + hmac_digest + ciphertext return ciphertext
def edit_command(initialize=False): """ edit_command takes one argument: initialize (defaulting to False); if not set to initialize, it decrypts the password file to a temporary file for editing; in either case, it encrypts the tempfile to be the new password file after the user has finished writing. """ file_descriptor, filename = tempfile.mkstemp() if not initialize: with os.fdopen(file_descriptor, 'wb') as temp_handle: temp_handle.write(decryptf(PASSWORD_FILE)) editor_process = subprocess.Popen([os.environ['EDITOR'], filename]) editor_process.wait() salt = Random.new().read(8) iv = Random.new().read(16) key = PBKDF2(getpass.getpass('Password (for encryption): '), salt).read(32) if PBKDF2(getpass.getpass('Repeat password: '******'Encryption passwords do not match.') cipher = AES.new(key, AES.MODE_CBC, iv) with open(filename, 'rb') as temp_handle: ciphertext = ''.join([salt, iv, cipher.encrypt(pad(temp_handle.read(), 16))]) with open(PASSWORD_FILE, 'wb') as password_handle: password_handle.write(ciphertext) shred_proc = subprocess.Popen(['shred', '-u', filename]) shred_proc.wait()
def run(self): key_ts = struct.pack('!Q', int(time.time() * 1000)) key = Random.new().read(32) kds_count = -1 while (True): # KDS kds_count = kds_count + 1 if kds_count % 120 == 0: key_ts = struct.pack("!Q", int(time.time() * 1000)) key = Random.new().read(32) kds_thread = kds.SimpleKDSPublisher(Name(bld_root), self.keychain, self.cert_name, key, key_ts) kds_thread.start() kds_count = 0 # Data now = int(time.time() * 1000) # in milliseconds a = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 166, 1) b = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 167, 1) vln = (b[0] << 16) + a[0] c = self.master.execute(1, cst.READ_HOLDING_REGISTERS, 150, 1) la = c[0] payload = {'ts': now, 'vlna': vln, 'la': la} timestamp = struct.pack("!Q", now) # timestamp is in milliseconds self.publishData(key, key_ts, payload, timestamp) time.sleep(self.interval)
def encrypt(self): '''Encrypts target by key. CipherEngine.setfile and CipherEngine.keyderive must be used first.''' target = self.fpath completed = 0 self.hasher = sha2.new() #create random initialization vector, hash iv for use as first exor iv = Random.new().read(16) self.hasher.update(iv) self.enlist.append(iv) xr = str(self.hasher.hexdigest())[-16:] #read, encrypt, then exor file block by block, output to ciphertext list with open(target, 'rb') as f: while completed < self.fblocks: wrkblk = f.read(16) if len(wrkblk) < 16: wrkblk += Random.new().read(16 - len(wrkblk)) wrkblk = self._xor(wrkblk, xr) self._encryptcycle(wrkblk) xr = self.enlist[-1] completed+=1 #hash ciphertext, encrypt it and add it to ciphertext list self.hasher = sha2.new() self.hasher.update(''.join(self.enlist)) h = self.hasher.hexdigest() hblocks = 4 completed = 0 while completed < hblocks: hb = h[0:16] self._encryptcycle(hb, True) h = h[16:] completed += 1 self.enlist.append(''.join(self.hlist))
def encrypt(self, plaintext): self.salt = Random.new().read(self.block_size) iv = Random.new().read(self.block_size) # 1 iteration here because we're not really doing this for CPU intensity cipher = AES.new(pbkdf2(self.key, self.salt, iterations=1, keylen=self.key_size), AES.MODE_CBC, iv) ciphertext = cipher.encrypt(self.pad(plaintext)) return quote(urlsafe_b64encode(self.salt + iv + ciphertext))
def enc_upload(filename, path): global s, profile, ID f = open(path,'r').read() #salt = Random.new().read(AES.block_size) salt = [ord(x) for x in Random.new().read(AES.block_size)] #key_index = Random.new().read(AES.block_size) key_index = [ord(x) for x in Random.new().read(AES.block_size)] key_blocks = [ord(x) for x in Random.new().read(AES.block_size)] block_index_iv=random_str(15) #key_blocks = Random.new().read(AES.block_size) profile[filename] = {'salt':salt, 'key_index':key_index, 'key_blocks':key_blocks, 'block_index_iv':block_index_iv} hashed = hash_substrings(f, salt,block_index_iv, key_index) h = open(filename+'hash', 'w') h.write(json.dumps(hashed)) #h.write(hashed) h.close() url = "http://128.30.93.9:8080/zoobar/index.cgi/enc_upload" files = {'file': (filename+'hash', open(filename+'hash','rb'))} s.post(url, files=files) encrypted_blocks = encrypt_blocks(f,key_blocks,block_index_iv,block_length) b = open(filename+'block','w') b.write(json.dumps(encrypted_blocks)) b.close() url = "http://128.30.93.9:8080/zoobar/index.cgi/enc_upload" files = {'file': (filename+'block', open(filename+'block','rb'))} s.post(url, files=files) upload_profile(ID)
def encrypt_file(password_string, input_file, chunk_size): # input_file is the unencrypted file. # Create encryptor object. salt = Random.new().read(SALT_LENGTH) key = PBKDF2(password_string, salt, dkLen=KEY_LENGTH, count=ITERATIONS, prf=HMAC_SHA256) ivec = Random.new().read(AES.block_size) en = AES.new(key, AES.MODE_CBC, ivec) # Takes in something like file.txt and outputs file.txt.cif. with open(input_file, 'rb') as plain_file: with open((input_file + '.cif'), 'wb') as cipher_file: # Write the password salt to the output file. cipher_file.write(salt) # Write the initialization vector to the output file. cipher_file.write(ivec) # Write chunks. Look for the last one. Pad the last chunk! current_chunk = plain_file.read(chunk_size) while True: next_chunk = plain_file.read(chunk_size) if not next_chunk: padded_chunk = get_padded_chunk(current_chunk) cipher_file.write(en.encrypt(padded_chunk)) break cipher_file.write(en.encrypt(current_chunk)) current_chunk = next_chunk
def createSession(self, userId, sessionId): ''' Initialize the authentication keys that are used when verifying the entries in the log database. ''' # Generate the epoch and entity keys (both are random 32-bytes strings) - used for verification (integrity) only epochKey = Random.new().read(32) entityKey = Random.new().read(32) # These keys should be encrypted using CPABE for the (verifier role and user role) # so they can easily be recovered for verification msg = '{"userId":' + str(userId) + ',"sessionId":' + str(sessionId) + ',"payload":' + str(0) + '}' logging.debug("verify msg: " + str(msg)) policy = self.manager.ask({'command' : 'verifyPolicy', 'payload' : msg}) encryptedEpochKey = self.encryptionModule.encrypt(epochKey, policy) encryptedEntityKey = self.encryptionModule.encrypt(entityKey, policy) # Persist the encrypted keys self.keyShim.replaceInTable("initialEpochKey", "(userId, sessionId, key, inserted_at)", (userId, sessionId, encryptedEpochKey, datetime.now().ctime()), [True, True, False, False]) self.keyShim.replaceInTable("initialEntityKey", "(userId, sessionId, key, inserted_at)", (userId, sessionId, encryptedEntityKey, datetime.now().ctime()), [True, True, False, False]) logging.debug("adding data to the in-memory dictionaries") self.initialEpochKey[(userId, sessionId)] = epochKey logging.debug("initial epoch key dict = " + str(self.initialEpochKey)) self.initialEntityKey[(userId, sessionId)] = entityKey
def encrypt(filename,public_key): #Gera chave da assinatura hmac = HMAC.new(public_key) ################### key = Random.new().read(AES.block_size) #chave aleatoria iv = Random.new().read(AES.block_size) #vector inicializacao aleatorio ################## #cifra os dados da chave AES com RSA access = encryptAccess(public_key,key,iv) #ler o ficheiro original criar o temporario para conteudo cipheredFile = open('temp','w') originalFile = open(filename,'r') #le o ficheiro original as chunks e escreve a chunk cifrada no temporario cipher = AES.new(key,AES.MODE_CBC,iv) finished = False while not finished: data = originalFile.read(AES.block_size*1024) #logica de padding - Caso se leia um bloco de tamanho vazio ou nao divisivel por 16 (aes.block_size) if(len(data) == 0 or (len(data) % cipher.block_size !=0)): pad = (cipher.block_size - len(data) % cipher.block_size) data += pad * chr(pad) finished = True hmac.update(data) #assinatura cipheredFile.write(cipher.encrypt(data)) #escreve o resultado do hashing do ficheiro originalFile.close() cipheredFile.close() return (cipheredFile, access, hmac.hexdigest())
def files_auth(request): """Display authentication for filecenter.""" if "password" in request.POST: """ Encrypt the password with AES mode CFB. Create a random 32 char key, stored in a CLIENT-side cookie. Create a random 32 char IV, stored in a SERVER-side session. Store the encrypted ciphertext in a SERVER-side session. This ensures that neither side can decrypt the password without the information stored on the other end of the request. Both the server-side session variables and the client-side cookies are deleted when the user logs out. """ key = Random.new().read(32) iv = Random.new().read(16) obj = AES.new(key, AES.MODE_CFB, iv) message = request.POST.get("password") ciphertext = obj.encrypt(message) request.session["files_iv"] = base64.b64encode(iv).decode() request.session["files_text"] = base64.b64encode(ciphertext).decode() cookie_key = base64.b64encode(key).decode() nexturl = request.GET.get("next", None) if nexturl and nexturl.startswith("/files"): response = redirect(nexturl) else: response = redirect("files") response.set_cookie(key="files_key", value=cookie_key) return response else: return render(request, "files/auth.html", {})
def __call__(self, parser, namespace, values, option_string=None): pub_key_file, priv_key_file, input_file, output_file = values pub_key = RSA.importKey(open(pub_key_file, 'r').read().rstrip('\n')) priv_key = RSA.importKey(open(priv_key_file, 'r').read().rstrip('\n')) plaintext = open(input_file, 'r').read().rstrip('\n') output_f = open(output_file, 'w') # Create a random session key and initialization vector session_key = Random.new().read( 32 ) iv = Random.new().read( 16 ) # Encrypt session key using PKCS1 OAEP public key crypto cipher = PKCS1_OAEP.new(pub_key) encrypted_session_key = cipher.encrypt(session_key + iv) output_f.write(base64.b64encode(encrypted_session_key) + '\n') # Encrypt plaintext using AES symmetric encryption plaintext = pad(plaintext) cipher = AES.new(session_key, AES.MODE_CBC, iv) ciphertext = base64.b64encode(cipher.encrypt(plaintext)) output_f.write(ciphertext + '\n') # Sign the message signature_msg = Random.new().read( 64 ) signer = PKCS1_v1_5.new(priv_key) signature = signer.sign(SHA256.new(signature_msg)) output_f.write(base64.b64encode(signature_msg) + '\n') output_f.write(base64.b64encode(signature)) print "Message encrypted!"
def encrypt_file(in_file_path, out_file_path, pwd): try: with open(in_file_path, 'rb') as input: with open(out_file_path, 'wb') as output: salt = Random.new().read(AES.block_size) iv = Random.new().read(AES.block_size) key = hashlib.pbkdf2_hmac('sha1', pwd, salt, 65536, 16) enc_obj = AES.new(key, AES.MODE_CBC, iv) block1 = input.read(16) if len(block1) < AES.block_size: output.write(salt + iv + enc_obj.encrypt(pad(block1))) else: content = enc_obj.encrypt(block1) output.write(salt + iv + content) while True: iv = content block1 = input.read(16) enc_obj = AES.new(key, AES.MODE_CBC, iv) if len(block1) < AES.block_size: output.write(enc_obj.encrypt(pad(block1))) break else: content = enc_obj.encrypt(block1) output.write(content) except Exception, e: logging.error('%s %s' % (os.path.abspath(in_file_path), e))
def create_digital_envelope(input_file, envelope_file, n, e): input = open(input_file).read() digital_envelope = Writer(envelope_file) digital_envelope.open() digital_envelope.set_description("Envelope") digital_envelope.set_file_name(input_file) digital_envelope.set_method(["AES", "RSA"]) digital_envelope.set_key_length(["0100", "0400"]); # P = poruka # K = kljuc # M = (C1, C2) # C1 = AES(P, K) # C2 = RSA(K, public_key_r) K = Random.new().read(AES.key_size[2]) IV = Random.new().read(AES.block_size) aes = AES.new(K, AES.MODE_CFB, IV) rsa = RSA.construct((n, e)) C1 = aes.encrypt(input) (C2, ) = rsa.encrypt(K, '') digital_envelope.set_initialization_vector(IV) digital_envelope.set_envelope_data(C1) digital_envelope.set_envelope_crypt_key(C2) digital_envelope.close() return
def crypt(SHELL, brutelen=7, alphanum=False): nums = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' if alphanum: keyspace = nums + alpha + alpha.upper() else: keyspace = nums BLOCK_SIZE = 16 BRUTE_LENGTH = brutelen PADDING = '\x00' pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) #DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) decoded = '' secret = Random.new().read(BLOCK_SIZE-BRUTE_LENGTH) secret += ''.join(random.choice(keyspace) for i in range(BRUTE_LENGTH)) #print secret IV = Random.new().read(16) checkstring = ''.join(random.choice(nums+alpha) for i in range(BLOCK_SIZE)) cipher = AES.new(secret) encoded = EncodeAES(cipher, SHELL) control = cipher.encrypt(checkstring) encoded += secret[:-BRUTE_LENGTH] + control + checkstring encoded = base64.b64encode(encoded) return encoded
def _encrypt(key, fh_to_encrypt): """ Encrypt and yield blocks from the file until the entire file has been encrypted key:str The key to use for the encryption fh_to_encrypt:file The file handle to read from yields bytes Yields the encrypted bytes """ key = _get_key(key) iv = Random.new().read(AES.block_size) salt = Random.new().read(AES.block_size) hashed_key = b'{}{}'.format(salt, sha512(b'{}{}'.format(salt, key)).digest()) aes = AES.new(key, MODE, iv) # For the first part, we yield the iv + the encyrpted salted hash # (length 70) of the key (for decrypt verification purposes) yield b'{}{}'.format(iv, aes.encrypt(hashed_key)) # Now we read by 4k blocks and pad, if necessary, then encrypt and # yield chunks block = fh_to_encrypt.read(4096) while block: bl_len = len(block) if bl_len < 4096: pad_len = len(block) % AES.block_size if pad_len: pad_len = AES.block_size - pad_len block = b'{}{}'.format(block, PADDING * pad_len) yield aes.encrypt(block) block = fh_to_encrypt.read(4096)
def encrypt(self, msg, pubKeyStr): ''' Encrypt a message ''' # prepare for AES aes_rand = Random.new().read(32) aes_iv_rand = Random.new().read(AES.block_size) aes_key = AES.new(aes_rand,AES.MODE_CBC,aes_iv_rand) pre_msg = str(json.dumps(msg)) # Pad the msg length = 16 - (len(pre_msg) % 16) # Now encrypt AES aes_msg = aes_key.encrypt(str.encode(pre_msg) + bytes([length])*length) # Prepare PKCS1 1.5 Cipher pubKey = RSA.importKey(pubKeyStr) cipher = PKCS1_v1_5.new(pubKey) # encrypt RSA rsa_aes_key = cipher.encrypt(aes_rand) rsa_aes_iv = cipher.encrypt(aes_iv_rand) combined = rsa_aes_key + rsa_aes_iv + aes_msg b64out = base64.b64encode(combined) return b64out.decode()
def send(self, obj, commit = False): msg = {'msg' : obj} if not commit: logger.info('[+] Sending: {0}'.format(msg['msg'])) else: msg['COMMIT'] = obj # serialize input data = pickle.dumps(obj) # padding pad = AES.block_size - len(data) % AES.block_size # create an header [pck length (4 bytes), pad length (1 byte), random (3 bytes))] plaintext = pack('>IB', len(data) + pad + SHA512.digest_size, pad) plaintext += Random.new().read(AES.block_size - len(plaintext)) # add payload plus padding plaintext += data plaintext += Random.new().read(pad) # encryption ciphertext = self.cipher_out.encrypt(plaintext) # integrity hsha = HMAC.new(self.key_hmac_out, digestmod=SHA512.new()) hsha.update(plaintext) hsha.update(pack('>I', self.seq_out)) self.seq_out = (self.seq_out + 1) & 0xFFFFFFFF ciphertext += hsha.digest() self.socket.sendall(ciphertext)
def append(input): lpad = Random.new().read(5+random.randint(0, 5)) rpad = Random.new().read(5+random.randint(0, 5)) msg = lpad + input + rpad length = 16 - (len(msg) % 16) msg += bytes([length])*length return msg
def createSession(self, userId, sessionId): ''' Initialize the authentication keys that are used when verifying the entries in the log database. ''' # Generate symmetric keys for this session - OLD APPROACH #epochKey = hmac.new("\EFx" * 20, str(time.time() * (1000000 * random.random())), hashlib.sha512).hexdigest() #entityKey = hmac.new("\EFx" * 20, str(time.time() * (1000000 * random.random())), hashlib.sha512).hexdigest() # Generate the epoch and entity keys (both are random 32-bytes strings) - used for verification (integrity) only epochKey = Random.new().read(32) entityKey = Random.new().read(32) # These keys should be encrypted using CPABE for the (verifier role and user role) # so they can easily be recovered for verification msg = '{"userId":' + str(userId) + ',"sessionId":' + str(sessionId) + ',"payload":' + str(0) + '}' print "verify msg: " + str(msg) policy = self.manager.ask({'command' : 'verifyPolicy', 'payload' : msg}) encryptedEpochKey = self.encryptionModule.encrypt(epochKey, policy) encryptedEntityKey = self.encryptionModule.encrypt(entityKey, policy) # Persist the encrypted keys self.keyShim.replaceInTable("initialEpochKey", "(userId, sessionId, key, inserted_at)", (userId, sessionId, encryptedEpochKey, datetime.now().ctime())) #encryptedEpochKey self.keyShim.replaceInTable("initialEntityKey", "(userId, sessionId, key, inserted_at)", (userId, sessionId, encryptedEntityKey, datetime.now().ctime())) #encryptedEntityKey #self.logShim.replaceInTable("InitialEpochKey", (userId, sessionId, epochKey)) #self.logShim.replaceInTable("InitialEntityKey", (userId, sessionId, entityKey)) print("adding data to the in-memory dictionaries") self.initialEpochKey[(userId, sessionId)] = epochKey print("initial epoch key dict = " + str(self.initialEpochKey)) self.initialEntityKey[(userId, sessionId)] = entityKey
def createSession(userId, sessionId): """ Initialize the authentication keys that are used when verifying the entries in the log database. """ # Generate the epoch and entity keys (both are random 32-bytes strings) - used for verification (integrity) only epochKey = Random.new().read(32) logEntityKey = Random.new().read(32) eventEntityKey = Random.new().read(32) # These keys should be encrypted using CPABE for the (verifier role and user role) # so they can easily be recovered for verification msg = '{"userId":' + str(userId) + ',"sessionId":' + str(sessionId) + ',"action":' + str(0) + "}" # print("verify msg: " + str(msg)) policy = manager.ask({"command": "verifyPolicy", "payload": msg}) encryptedLogEntityKey = encryptionModule.encrypt(logEntityKey, policy) encryptedEventEntityKey = encryptionModule.encrypt(eventEntityKey, policy) # Persist the encrypted keys keyShim.replaceInTable( "InitialLogEntityKey", "(userId, sessionId, key, inserted_at)", (userId, sessionId, encryptedLogEntityKey, datetime.now().ctime()), [False, False, False, False], ) keyShim.replaceInTable( "InitialEventEntityKey", "(userId, sessionId, key, inserted_at)", (userId, sessionId, encryptedEventEntityKey, datetime.now().ctime()), [False, False, False, False], ) # print("setting initial log and event entity key...") initialLogEntityKey[(userId, sessionId)] = logEntityKey initialEventEntityKey[(userId, sessionId)] = eventEntityKey
def encrypt(self): infile = open(self.input_file, 'rb') outfile = open(self.output_file, 'wb') iv = Random.new().read(16) salt = Random.new().read(16) key = PBKDF2(self.password, salt).read(16) ctr = Counter.new(128, initial_value=int(hexlify(iv), 16)) e = AES.new(key, AES.MODE_CTR, counter=ctr) outfile.write(iv) outfile.write(salt) while True: chunk = infile.read(16) if not chunk: break ciphertext = e.encrypt(chunk) outfile.write(ciphertext) infile.close() outfile.close()
def encrypt(key, infile, outfile): """Takes key and input file object and output file object""" iv = Random.new().read(Blowfish.block_size) if verbose: print "iv: ", bytes_to_hexstr(iv) outfile.write(iv) # Write iv to outfile # calc max size to see if last chunk need padding (and number of padding bytes) file_size = os.fstat(infile.fileno()).st_size pad_len = 8-(file_size%8) if pad_len == 8: if verbose: print "wow no padding needed" outfile.write(chr(0)) else: if verbose: print "Padding: {}".format(pad_len) outfile.write(chr(pad_len)) cipher = Blowfish.new(key, Blowfish.MODE_OFB, iv) while True: plain_data = infile.read(CHUNK_SIZE) if not plain_data: break # Nothing more to read if len(plain_data) != 4096 and pad_len != 8: # last package so pad it padding = Random.new().read(pad_len) outfile.write(cipher.encrypt(plain_data + padding)) else: outfile.write(cipher.encrypt(plain_data))
def encrypt_file(password, path, file_data): salt = Random.new().read(FileCryptoTool.SALT_SIZE) iv = Random.new().read(FileCryptoTool.IV_SIZE) key = PBKDF2(password, salt, dkLen=FileCryptoTool.KEY_SIZE, count=FileCryptoTool.ITERATIONS) encryptor = AES.new(key, AES.MODE_CFB, iv) with open(path,'wb') as out_file: out_file.write(salt + iv + encryptor.encrypt(file_data))
def __genDHParams__(self): ''' Generates DH parameters ''' self.DH_PRIME = getPrime(self.DH_PARAM_SIZE,Random.new().read) self.DH_PRIVATE = getPrime(self.DH_PARAM_SIZE,Random.new().read) self.DH_GENERATOR = getPrime(self.DH_PARAM_SIZE,Random.new().read) self.DH_PUBLIC = pow(self.DH_GENERATOR,self.DH_PRIVATE,self.DH_PRIME)
''' import binascii import sys import re import hmac, hashlib, base64 from Crypto.Cipher import AES from Crypto import Random """ Implementation of AES-256 with CBC cipher mode cipher = plaintext + hmac + padding IV and KEY are random there is no handshake (no need) """ IV = Random.new().read(AES.block_size) KEY = Random.new().read(AES.block_size) # generate random key and iv def randkey(): global IV IV = Random.new().read(AES.block_size) global KEY KEY = Random.new().read(AES.block_size) # padding for the CBC cipher block def pad(s): return (16 - len(s) % 16) * chr((16 - len(s) - 1) % 16)
def encrypt(message, key, key_size=256): message = pad(message) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return iv + cipher.encrypt(message)
def randkey(): global IV IV = Random.new().read(AES.block_size) global KEY KEY = Random.new().read(AES.block_size)
AES.block_size))).decode() # CBC/OFB/CTR 모드인 경우 패딩 수행 + base64 encoding def AESdecrypt(encrypted, passphrase): cipher = AES.new(passphrase, AES.MODE_CBC, IV) #return cipher.decrypt(encrypted) #return unpad(cipher.decrypt(encrypted), AES.block_size) # CBC/OFB/CTR 모드인 경우 언패딩 수행 return unpad(cipher.decrypt(base64.b32decode(encrypted)), AES.block_size) # base64 decoding + CBC/OFB/CTR 모드인 경우 언패딩 수행 ### main ### seed_number = input("Seed Number from WebServer:") key_AES = SHA256.new(seed_number.encode()).digest()[:16] ## generated AES Key IV = Random.new().read(BLOCK_SIZE) message = b"Web SeverBased Aes Enc/Dec and File Upload Test........" print("key: ", key_AES) print("key length: ", len(key_AES)) cipher_AES = AES.new(key_AES, AES.MODE_CBC, IV) encrypted_msg = base64.b32encode( cipher_AES.encrypt(pad(message, AES.block_size))).decode() file_out = open("./AES_encrypted_data_for_Upload.bin", "wb") output = IV + encrypted_msg.encode() file_out.write(output) # IV + encrypted_msg 순서로 파일에 저장 file_out.close() print("File Created!! Let's Upload to Server!!")
sockets_list = [] clients = {} rooms = ["General"] if not os.path.isdir("log"): os.mkdir("log") file = open('log/users.json', 'w') file.close() db = TinyDB('log/users.json') session_key_map = dict() session_cipher = dict() RSA_key = RSA.generate(2048, Random.new().read) server_public_key = RSA_key.publickey().export_key('PEM') server_private_key = RSA_key.export_key('PEM') decryption_cipher = PKCS1_OAEP.new(RSA.import_key(server_private_key)) print(server_public_key.decode('ascii')) print(server_private_key.decode('ascii')) class SessionKeyGen(threading.Thread): def __init__(self, username, client_socket): threading.Thread.__init__(self) self.setDaemon(True) self.username = username self.client_socket = client_socket
#!/usr/bin/env python from Crypto.publicKey import RSA from Crypto import Random ran = Random.new().read key = RSA.generate(1024, ran) public = open('mykeypublic.pem', 'w') priv = open('mykeypriv.pem', 'w') public.write(key.publickey().exportKey()) priv_key = priv.write(key.exportKey('PEM', passphrase=None, pkcs=8)) public.crane() priv.crane() key_file = open('RSA.pem', 'r') key = RSA.importKey(key_file.read()) print(key) file_empty = open('encrypt.txt', 'r') file_cipher = open('cipher.txt', 'w') text = file_empty.read() print(text.encode('base64').encode('utf-8')) enc_text = key.encrypt(text, 32) enc_text = enc_text[0] print(enc_text.encode('hex')) file_cipher.write(enc_text.encode('hex'))
def token(): random_generator = Random.new().read rsa = RSA.generate(1024, random_generator) private_pem = rsa.exportKey() return(private_pem)
def encrypt(raw, password): private_key = get_private_key(password) raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(private_key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw))
def encrypt(raw): raw = _pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw))
def encrypt_file(password, keyphrase, in_filename, out_filename=None, chunksize=DEFAULT_CHUNKSIZE): """ Encrypts a file content. :param password: {String} encryption password (used for key generation). :param keyphrase: {String} encryption keyphrase (used for salt on key generation). :param in_filename: {String} name of the input file. :param out_filename: {String} name of the output file. Defaults to '<in_filename>.enc' :param chunksize: {Integer} size of the chunk to read and encrypt the file with. Must be divisible by 16. """ if not out_filename: out_filename = in_filename + OUTPUT_FILE_DEFAULT_SUFFIX # Get the key for the current combination. key = generate_key(password, keyphrase) # Generating initialization vector (IV). # Important part of block encryption algorithms that work in chained modes (like CBC) we are using. # For maximal security, the IV is randomly generated for every encryption. ivec = Random.new().read(IVEC_SIZE) encryptor = AES.new(key, AES_MODE, ivec) filesize = os.path.getsize(in_filename) file_length_field = struct.pack('<Q', filesize) # Prepare status data for feedback. status_data = {'status': True, 'out_filename': out_filename, 'error': ''} try: with open(in_filename, 'rb') as infp: with open(out_filename, 'wb') as outfp: # First write IV to the file so we can read it later on. outfp.write(ivec) chunk = None final_chunk = False while True: # Encrypt the previous chunk, then read the next. if chunk is not None: outfp.write(encryptor.encrypt(chunk)) # If we came to the end of the file. if final_chunk: break # Get the next chunk of file. chunk = infp.read(chunksize) # When we get smaller than a full chunk, input file is done. # Adding the padding and length indicator. # This is to make sure we get a full chunk so filling in with blank space. if len(chunk) == 0 or len(chunk) % 16 != 0: padding_size = ( 16 - (len(chunk) + FILE_LENGTH_FIELD_SIZE) % 16) padding = ' ' * padding_size chunk += padding # Add the original file length at the end of the file for later extraction on decryption. chunk += file_length_field assert len(chunk) % 16 == 0 final_chunk = True except: e = sys.exc_info()[0] # Catch all possible errors and return so caller can be notified. status_data['status'] = False status_data['error'] = str(e) return status_data
def encrypt(texto_claro,key): texto_claro = pad(texto_claro) iv = Random.new().read(AES.block_size) #texto aleatorio que se anyade por seguridad cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(texto_claro)) #Convierte los caracteres a caracteres base64
from Crypto.PublicKey import RSA from Crypto import Random # generate RSA keys for encryption and decryption both public and private # keep the private key hidden and use the public to encrypt key = RSA.generate(bits=2048, randfunc=Random.new().read) # save the private key with open('private_key.pem', 'wb') as fout: fout.write(key.export_key()) # save the public key with open('public_key.pem', 'wb') as fout: fout.write(key.publickey().export_key())
def encrypt(self, raw): raw = raw.encode() raw = 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)).decode()
def encrypt(msg_bytes, shared_seed): aes256_key = shared_seed.derive_aes256_key() raw = MessageCodec.pad(msg_bytes) iv = Random.new().read(AES.block_size) cipher = AES.new(aes256_key, AES.MODE_CBC, iv) return iv + cipher.encrypt(raw)
#encrypt from Crypto.Cipher import AES from Crypto import Random key = Random.new().read(AES.block_size) iv = Random.new().read(AES.block_size) input_file = open("input.jpg") input_data = input_file.read() input_file.close() cfb_cipher = AES.new(key, AES.MODE_CFB, iv) enc_data = cfb_cipher.encrypt(input_data) enc_file = open("encrypted.enc", "w") enc_file.write(enc_data) enc_file.close()
__author__ = 'heggens' from Crypto.Cipher import DES, DES3 from Crypto import Random KEY = "The key!" iv = Random.new().read(DES3.block_size) KEY2 = Random.new().read(DES3.key_size[-1]) def encryptDES(msg): encryption = DES.new(KEY) cipher = encryption.encrypt(msg) return cipher def decryptDES(cipher): decryption = DES.new(KEY) plainOut = decryption.decrypt(cipher) return plainOut def encrypt3DES(msg): enc = DES3.new(KEY2, DES3.MODE_ECB, iv) cipher = enc.encrypt(msg) return cipher def decrypt3DES(cipher): dec = DES3.new(KEY2, DES3.MODE_ECB, iv)
def encrypt(raw): private_key = hashlib.sha256(password.encode("utf-8")).digest() raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(private_key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(bytes(raw, "utf-8")))
def newkeys(keysize): random_generator = Random.new().read key = RSA.generate(keysize, random_generator) private, public = key, key.publickey() return public, private
def new_key(self, size): return Random.new().read(size)
def encrypt(username): initialization_vector = Random.new().read(AES.block_size) aes_cipher = UsernameCipher._get_aes_cipher(initialization_vector) return urlsafe_b64encode(initialization_vector + aes_cipher.encrypt( UsernameCipher._add_padding(username.encode("utf-8"))))
def encrypt(password, key): password = pad(password) iv456 = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv456) return base64.b64encode(iv456 + cipher.encrypt(password)).decode('utf-8')
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, "1") 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 secret_key() -> bytes: key = Random.new().read(32) return key
def encrypt(self, password_s, config_s): """Encrypts the configuration and returns it as two strings If any of the public attributes is None, a random value is created. Otherwise the attribute is used for encryption. Args: password_s (str): the password to encrypt the configuration. config_s (str): the configuration to be encrypted. Returns: str: the encrypted dictionary (keySafe) as parameter 1. str: the encrypted configuration (data) as parameter 2. Raises: TypeError: if one of the public attributes has the wrong type. ValueError: if one of the public attributes or the dictionary AES key has an incorrect length. """ def encode_base64(bytes): """Encode bytes with BASE64 Args: bytes (bytes): the data to be encoded. Returns: str: the encoded string. """ return b64encode(bytes).decode() def quote_string(string_s): """Return a quoted string This function replaces 5 special characters with their quoted version. Args: string_s (str): string to be quoted. Returns: str: the quoted string. """ repls = [('/', '%2f'), ('+', '%2b'), ('-', '%2d'), (':', '%3a'), ('=', '%3d')] return reduce(lambda a, kv: a.replace(*kv), repls, string_s) def pad(data): """Add padding bytes Adds 1-16 padding bytes whose values are equal to the amount of bytes to be added. Thus the decoding process just has to read a padding byte and knows how many padding bytes were added. Args: data (bytes): data to be padded. Returns: bytes: the padded data. """ value = AES.block_size - len(data) % AES.block_size return data + value * chr(value) # Create the configuration AES key if not already set if self.aes_key2 is None: self.aes_key2 = Random.new().read(self.AES_KEY_SIZE) # Calculate the configuration hash hash = hmac.new(self.aes_key2, config_s.encode(), digestmod=hashlib.sha1) config_hash = hash.digest() del hash # Add padding bytes to the configuration (must be multiple of 16) config_dec = pad(config_s) # Create the AES Initialization Vector if not already set if self.aes_iv2 is None: self.aes_iv2 = Random.new().read(self.AES_IV_SIZE) # Encrypt the configuration and add AES IV and hash cipher = AES.new(self.aes_key2, self.__AES_MODE, self.aes_iv2) config_enc = self.aes_iv2 + cipher.encrypt(config_dec.encode()) + config_hash del cipher # Encode the configuration config_s = encode_base64(config_enc) # Encode and quote the configuration AES key config_key_s = encode_base64(self.aes_key2).replace('=','%3d') # Build the dictionary string dict_dec = 'type=key:cipher=AES-256:key={}'.format(config_key_s) # Create the password salt if not already set if self.salt is None: self.salt = Random.new().read(self.SALT_SIZE) # Encode and quote the password salt salt_s = quote_string(encode_base64(self.salt)).replace('%3d','%253d') # Create the dictionary AES Key with PBKDF2-HMAC-SHA-1 dict_key = hashlib.pbkdf2_hmac('sha1', password_s.encode(), self.salt, self.__HASH_ROUNDS, self.AES_KEY_SIZE) # Check if the result is an AES-256 key if len(dict_key) != self.AES_KEY_SIZE: msg = 'Dictionary AES key has incorrect length: {}' \ .format(len(dict_key)) raise ValueError(msg) # Calculate the dictionary hash hash = hmac.new(dict_key, dict_dec.encode(), digestmod=hashlib.sha1) dict_hash = hash.digest() del hash # Add padding bytes to the dictionary (must be multiple of 16) dict_dec = pad(dict_dec) # Create the AES Initialization Vector if not already set if self.aes_iv1 is None: self.aes_iv1 = Random.new().read(self.AES_IV_SIZE) # Encrypt the dictionary and add AES IV and hash cipher = AES.new(dict_key, self.__AES_MODE, self.aes_iv1) dict_enc = self.aes_iv1 + cipher.encrypt(dict_dec.encode()) + dict_hash del cipher # Encode the configuration dict_s = encode_base64(dict_enc) # Create the identifier if not already set if self.identifier is None: self.identifier = Random.new().read(self.IDENTIFIER_SIZE) # Encode and quote the identifier identifier_s = quote_string(encode_base64(self.identifier)) # Build the dictionary string dict_s = 'pass2key={}:cipher={}:rounds={}:salt={},{},{}' \ .format('PBKDF2-HMAC-SHA-1', 'AES-256', self.__HASH_ROUNDS, salt_s, 'HMAC-SHA-1', dict_s) # Quote the dictionary string dict_s = quote_string(dict_s) # Build the keysafe and data strings keysafe_s = 'encryption.keySafe = ' \ '"vmware:key/list/(pair/(phrase/{}/{}))"' \ .format(identifier_s, dict_s) data_s = 'encryption.data = "{}"'.format(config_s) # Return them return keysafe_s, data_s
def random_key(key_len): return Random.new().read(key_len)
# https://pythonhosted.org/pycrypto/Crypto.PublicKey.ElGamal-module.html from Crypto import Random from Crypto.Random import random from Crypto.PublicKey import ElGamal from Crypto.Util.number import GCD ''' Message that we want to encrypt ''' message = b"Hello!" encoding = 'utf-8' print('El mensaje a cifrar es: ' , message.decode(encoding)) key = ElGamal.generate(1024, Random.new().read) ''' @ElGamal.generate Description: Randomly generate a fresh, new ElGamal key. Parameters: bits: - Key length, or size (in bits) of the modulus p. randfunc: - Random number generation function; it should accept a single integer N and return a string of random data N bytes long. progress_func=None: - Optional function that will be called with a short string containing the key parameter currently being generated; it's useful for interactive applications where a user is waiting for a key to be generated.
from Crypto import Random from Crypto.PublicKey import RSA random_generator = Random.new().read rsa = RSA.generate(1024, random_generator) private_pem = rsa.exportKey() with open('private.pem','wb') as f: f.write(private_pem) public_pem = rsa.publickey().exportKey() with open('public.pem','wb') as f: f.write(public_pem)
def random_iv(): iv = Random.new().read(16) safe_iv = iv[0:8] + struct.pack(">L", 0) + iv[12:] return safe_iv
def mills_malvo(): print "Monserrate-Mills-Malvo 1.7 Attack 0.1 CPEN 503 Final Project Crypto" print "Copyright 2016 Atelier-Velvet Corporation." # IMPORTATION OF THE KEYS privateA = RSA.importKey(open('KA.der').read()) kpublicA = RSA.importKey(open('KA.der.pub').read()) privateB = RSA.importKey(open('KB.der').read()) kpublicB = RSA.importKey(open('KB.der.pub').read()) privattA = RSA.importKey(open('KAattack.der').read()) kpubattA = RSA.importKey(open('KAattack.der.pub').read()) privattB = RSA.importKey(open('KBattack.der').read()) kpubattB = RSA.importKey(open('KBattack.der.pub').read()) # REDEFINITION OF THE RSA KEYS SO THAT THEY MATCH THE CORRECT LENGTH AND ORDER (INTERNAL RSA KEY MUST BE SHORTER IN LENGTH THAN EXTERNAL RSA KEY) KAPRI = kpublicB KAPUB = privateB KBPRI = privateA KBPUB = kpublicA KAMPRI = kpubattB KAMPUB = privattB KBMPRI = privattA KBMPUB = kpubattA # ATTACK ON THE "SECURE" SCHEMA POSTULATED BY THE BOOK: RSA[KBPUB, RSA[KAPRI, K]]--->ARCRSA[KBPRI, ARCRSA[KAPUB, RSA[KBPUB, RSA[KAPRI, K]]]] print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" print "ATTACK ON THE ``SECURE'' SCHEMA POSTULATED BY THE BOOK: RSA[KBPUB, RSA[KAPRI, K]]--->ARCRSA[KBPRI, ARCRSA[KAPUB, RSA[KBPUB, RSA[KAPRI, K]]]]:" print " " print "Order of Events:" print " " print "INTERCEPTION OF THE PUBLIC KEYS:" print " " print "[TRANSMISSION FROM ALICE INTENDED TO BOB]: Alice sends Bob her public key, KAPUB." print "[TRANSMISSION FROM ALICE TO BOB INTERCEPTED BY MALVO]: Malvo swaps Alice's public key, KAPUB, with a public key from the pairs of his own, KAMPUB." print "[TRANSMISSION FROM MALVO TO BOB]: Malvo sends Bob the swap of Alice's public key, KAMPUB, and stores Alice's public key, KAPUB, in his key repository." print "[TRANSMISSION FROM BOB INTENDED TO ALICE]: Bob sends Alice his public key, KBPUB." print "[TRANSMISSION FROM BOB TO ALICE INTERCEPTED BY MALVO]: Malvo swaps Bob's public key, KBPUB, with another public key from the pairs of his own, KBMPUB." print "[TRANSMISSION FROM MALVO TO ALICE]: Malvo sends Alice the swap of Bob's public key, KBMPUB, and stores Bob's public key, KBPUB, in his key repository." print " " print "EXTRACTION OF THE SYMMETRIC KEY:" print " " print "[GENERATION OF THE 16 BYTE SYMMETRIC KEY BY ALICE]:" K = raw_input( "Alice, enter the symmetric key and press enter to send to Bob: ") print "Allice entered: ", K print " " print "[DOUBLE RSA ENCRYPTION AND TRANSMITTAL OF SYMMETRIC KEY USING ALICE'S PRIVATE KEY, THEN MALVO'S BOB COMPROMISED PUBLIC KEY]:" print " " cipher = PKCS1_OAEP.new(KAPRI) ciphertextAM0 = cipher.encrypt(K) cipher = PKCS1_OAEP.new(KBMPUB) ciphertextAM1 = cipher.encrypt(ciphertextAM0) print "[MALVO'S DOUBLE RSA DECRYPTION OF ALICE'S CIPHERTEXT TO BOB USING ALICE'S PUBLIC KEY AND MALVO'S BOB PRIVATE KEY, KBMPRI]:" cipher = PKCS1_OAEP.new(KBMPRI) ciphertextMA1 = cipher.decrypt(ciphertextAM1) cipher = PKCS1_OAEP.new(KAPUB) plaintextAM0 = cipher.decrypt(ciphertextMA1) print "[MALVO'S EXTRACTED SYMMETRIC KEY PAR INTERCEPTION FROM ALICE TO BOB IS]: ", plaintextAM0 print " " print "[GENERATION OF COMPROMISED SYMMETRIC KEY FOR MALVO TO SEND BOB AS IF WERE COMMING FROM ALICE]" K_hat = raw_input( "Enter the compromised symmetric key to send to Bob in the name of Alice, Malvoo .... : " ) print "Malvo entered: ", K_hat print " " print "[DOUBLE RSA ENCRYPTION AND TRANSMITTAL OF COMPROMISED SYMMETRIC KEY USING MALVO'S ALICE PRIVATE KEY, THEN BOB'S PUBLIC KEY]:" cipher = PKCS1_OAEP.new(KAMPRI) ciphertextMB0 = cipher.encrypt(K_hat) cipher = PKCS1_OAEP.new(KBPUB) ciphertextMB1 = cipher.encrypt(ciphertextMB0) print " " print "[BOB'S DOUBLE RSA DECRYPTION OF MALVO'S COMPROMISED CIPHERTEXT USING BOB'S PRIVATE KEY AND MALVO'S ALICE PUBLIC KEY, KAMPUB]:" cipher = PKCS1_OAEP.new(KBPRI) ciphertextBM1 = cipher.decrypt(ciphertextMB1) cipher = PKCS1_OAEP.new(KAMPUB) plaintextBM0 = cipher.decrypt(ciphertextBM1) print "[BOB RECEIVES COMPROMISED SYMMETRIC KEY]: ", plaintextBM0 print " " print "[ALICE AND BOB NOW THINK THEY SHARE THE SAME SYMMETRIC KEY ... MALVO KNOWS THEY'LL BE USING AES TO TRANSMIT ACROSS THE CHANNEL ....]" print " " print "[ALICE ---> BOB]: ALICE AES ENCRYPTS MESSAGE MA ON THE BLOCKSIZE (16 BYTES) WITH KEY K (16, 24, OR 32 BITES) AND SENDS IT TO BOB" print " " BLOCK_SIZE = 16 MA = raw_input("Alice, enter your message to bob ... It's secure !: ") print "Alice's message MA was: ", MA key = plaintextAM0 iv = Random.new().read(BLOCK_SIZE) cipher = AES.new(key.encode(), AES.MODE_CFB, iv) aciphertextAM = iv + cipher.encrypt(MA.encode()) print " " print "[MALVO INTERCEPTS ALICE'S AES ENCRYPTED CIPHERTEXT TO BOB AND DECRYPS IT USING ALICE'S EXTRACTED SYMMETRIC KEY]" AM = cipher.decrypt(aciphertextAM) print "[MALVO RECOVERS AND READS ALICE'S MESSAGE TO BOB ...]: ", AM print " " print "[MALVO NOW RE AES ENCRYPTS ALICE'S MESSAGE TO BOB BUT USING THE COMPROMISED SYMMETRIC KEY, K HAT]:" key_hat = K_hat iv = Random.new().read(BLOCK_SIZE) cipher = AES.new(key_hat.encode(), AES.MODE_CFB, iv) aciphertextMB = iv + cipher.encrypt(AM) print " " print "[BOB DECRYPTS THE COMPROMISED AES CIPHERTEXT USING THE COMPROMISED SYMMETRIC KEY, K HAT]:" BM = cipher.decrypt(aciphertextMB) print "Here it is Bob, the message so securely sent by Alice ;): ", BM
from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.ciphers import modes from cryptography.hazmat.backends import default_backend from struct import pack import socket #force python3 class Generator(object): def __init__(self): yield from range(10) key = b'Sixteen byte key' iv = Random.new().read(ARC2.block_size) ##Warn: B304 cipher = ARC2.new(key, ARC2.MODE_CFB, iv) msg = iv + cipher.encrypt(b'Attack at dawn') key = b'Very long and confidential key' nonce = Random.new().read(16) tempkey = SHA.new(key + nonce).digest() ##Warn: B304 cipher = ARC4.new(tempkey) msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL') bs = Blowfish.block_size key = b'An arbitrarily long key' iv = Random.new().read(bs) ##Warn: B304