class QRCipher: def __init__(self, key, file_name): self.key = key self.file_name = file_name self.cipher = AESCipher(bytes(self.key, encoding='utf8')) def set_key(self, key): self.key = key self.cipher = AESCipher(bytes(self.key, encoding='utf8')) @staticmethod def create_qr(text, qr_name): qr_code = pyqrcode.create(text) qr_code.png(qr_name, scale=6) # text_qr.svg('uca-url.svg', scale=8) # text_qr.eps('uca-url.eps', scale=2) # print(text_qr.terminal(quiet_zone=1)) return qr_code @staticmethod def decode_qr_image(image_name): data = decode(Image.open(image_name)) text = data[0].data return text def encrypt(self, plain_text): encrypted_text = self.cipher.encrypt(plain_text) return self.create_qr(encrypted_text, 'encrypted_' + self.file_name + '.png') def decrypt(self, encrypted_text): decrypted_text = self.cipher.decrypt(encrypted_text) return self.create_qr(decrypted_text, 'decrypted_' + self.file_name + '.png')
def generate_token(user): """ token contains: (generated session key, expiry date) encrypted with system wide shared secret ticket contains: ((generated session key), (generated session key, expiry date)) encrypted with clients public key """ expiry_date = (datetime.datetime.now() + datetime.timedelta(minutes=10)).timestamp() token = {"gen_session_key": " ", "expiry_date": expiry_date} token_serialised = json.dumps(token, cls=DateTimeEncoder) cipher = AESCipher(SHARED_SECRET) encode_hash_session_key = cipher.encrypt(token_serialised) ticket = json.dumps({ 'gen_session_key': user['gen_session_key'], 'token': encode_hash_session_key }) # encrypting the whole ticket with client's password or public key cipher = PKCS1_OAEP.new(user['public_key']) encode_hash_ticket = cipher.encrypt(str.encode(ticket)) return encode_hash_ticket
def encrypt_payload(self, decrypted_payload, user_id): aeskey = self.get_token(user_id) aesiv = self.get_iv(user_id) aesc = AESCipher(aeskey) aesc.set_iv(aesiv) encrypted_bytes = aesc.encrypt(decrypted_payload) return encrypted_bytes
def encrypt_payload(self, pkt, aes_key, aes_iv): #aes_key = b'\x9b\xd9\xcd\xf6\xbe+\x9dX\xfb\xd2\xef>\xd87i\xa0\xca\xf5o\xd0\xac\xc3\xe0R\xf0z\xfa\xb8\xdd\x01?E' #aes_iv = b'\xef\xaa)\x9fHQ\x0f\x04\x18\x1e\xb5;B\xff\x1c\x01' aesc = AESCipher(aes_key) aesc.set_iv(aes_iv) encrypted_bytes = aesc.encrypt(pkt) return encrypted_bytes
def process_outgoing_message(self, msg_raw, originates_from_console=False): ''' Process an outgoing message before Base64 encoding :param msg_raw: raw message :return: message to be sent to the server ''' # if the message has been typed into the console, record it, so it is never printed again during chatting if originates_from_console == True: self.update_send_ctr() # message is already seen on the console cipher = AESCipher(self.symm_key) encrypted_msg = cipher.encrypt(msg_raw) str_to_sign = MESSAGE_CODE + '|' + encrypted_msg + '|' + str( self.send_counter) sig = self.sign(str_to_sign) msg_raw = str_to_sign + '|' + sig m = Message(owner_name=self.manager.user_name, content=msg_raw) self.printed_messages.append(m) # process outgoing message here # example is base64 encoding, extend this with any crypto processing of your protocol encoded_msg = base64.encodestring(msg_raw) # post the message to the conversation self.manager.post_message_to_conversation(encoded_msg)
def run_client(port): s = socket(AF_INET, SOCK_STREAM) s.connect((HOST, port)) cred = s.recv(RECV_SIZE) while True: try: pub, sig = unpack_cred(cred) break except: cred += s.recv(RECV_SIZE) if not verify_cred(pub, sig): return key = RSA.importKey(pub) rsa = PKCS1_OAEP.new(key) sess_key = secrets.token_bytes(KEY_SIZE) enc_sess_key = rsa.encrypt(sess_key) s.sendall(pickle.dumps(enc_sess_key)) cipher = AESCipher(sess_key) messages = [] data = recvall(s) while data: chunk = pickle.loads(data) data = data[len(pickle.dumps(chunk)):] messages.append(cipher.decrypt(chunk)) with open('msgs.txt', 'wb') as f: f.write(b''.join(messages))
def DH(self, sharedKey): print '\n############### STARTING D-H ##################' # Create AES object with shared key cipher = AESCipher(sharedKey) #generate key to send to server myDiffieHellman = DiffieHellman() print 'g^a mod p value is: ', myDiffieHellman.public_key print '\n' #send key to server sendDH = cipher.encrypt(str(myDiffieHellman.public_key)) print 'Sending encrypted value: ', sendDH.encode('hex') self.send(str(sendDH)) print '\n' recvDH = self.waitToRec() #decrypt received DH value reply = cipher.decrypt(recvDH) print 'Received encrypted value: ', recvDH.encode('hex') print '\n' print 'g^b mod p value is: ', reply print '\n' #calculate session key myDiffieHellman.calc_shared_key(long(reply)) print "Calculated session key:", myDiffieHellman.key self.sessionKey = myDiffieHellman.key print '################## D-H OVER ###################\n'
def get_data(image_data, bits_to_rewrite_count, key): cipher = AESCipher(key) image_bytes_count = int(math.ceil(64 * 8 / bits_to_rewrite_count)) i_str = StringIO() for i in range(image_bytes_count): i_str.write(H.get_bits(image_data[i])[-bits_to_rewrite_count:]) bin_enc_size = i_str.getvalue()[:64 * 8] i_bytes = BytesIO() for i in range(64): i_bytes.write(bytes([int(bin_enc_size[8 * i:8 * i + 8], 2)])) enc_size = i_bytes.getvalue() size = int(cipher.decrypt(enc_size)) shift = image_bytes_count image_bytes_count = int(math.ceil(size * 8 / bits_to_rewrite_count)) for i in range(image_bytes_count): i_str.write(H.get_bits(image_data[i + shift])[-bits_to_rewrite_count:]) bin_enc_data = i_str.getvalue()[64 * 8:(size + 64) * 8] i_bytes = BytesIO() for i in range(size): i_bytes.write(bytes([int(bin_enc_data[8 * i:8 * i + 8], 2)])) enc_data = i_bytes.getvalue() data = cipher.decrypt(enc_data).encode() return data
def decrypt_file(self, file_name): aes = AESCipher(self.key) with open(file_name, 'rb') as file: text = file.read() dec = aes.decrypt(text) with open(file_name, 'wb') as file: file.write(dec)
def generate_splits(self): aes = AESCipher(self.key) cipher = aes.encrypt(self.text) message = aes.decrypt(cipher) size = 255, len(self.key) im = Image.new("1", size, "white") pix = im.load() for i in range(len(self.key)): for j in range(ord(self.key[i])): pix[j, i] = 0 im.save("original.gif") share1 = Image.new("1", size, "white") share1pix = share1.load() for i in range(len(self.key)): for j in range(255): x = randint(0,1) if x == 0: share1pix[j, i] = 0 share2 = Image.new("1", size) share2pix = share2.load() for i in range(len(self.key)): for j in range(255): if pix[j, i] == share1pix[j, i]: share2pix[j, i] = 0 else: share2pix[j, i] = 255 output = [share1, share2, cipher] x = Decrypter(cipher, [share1, share2]) x.decrypt_image() return output
def decrypt_token(ticket, privatekey): """ token contains: (generated session key, expiry date) encrypted with ticket contains: """ privkey_path = "./client.key" pubkey_path = "./client_pub.key" # encrypting the whole ticket with client's password or public key cipher = PKCS1_OAEP.new(privatekey) ticket = cipher.decrypt(ticket) ticket = json.loads(ticket) print(ticket) from AESCipher import AESCipher cipher = AESCipher(SHARED_SECRET) token = cipher.decrypt(ticket['token']) token = json.loads(token) print(token, ticket) return
def __init__(self): self.blocks = [] key_for_md5_aes = '#TCC2019-N2N#' self.aes = AESCipher(key_for_md5_aes) # Carregando com paramêtros de acesso para desenvolvedor # Instanciando um gerenciador do banco de dados TCC self.conexao_bd = conexao_servidor.TCC cursor_ultimo_bloco = self.conexao_bd.HBase.aggregate([ { "$sort": { "timestamp": -1 }, }, {"$limit": 1} ]) last_block_from_collection = list(cursor_ultimo_bloco) if(len(last_block_from_collection) > 0): print('Retomando o blockchain a partir de uma hash no banco de dados.') self.set_genesis_block(True,last_block_from_collection[0]) else: self.set_genesis_block()
def decrypt_payload(self, encrypt_payload, user_id): aeskey = self.get_token(user_id) aesiv = self.get_iv(user_id) aesc = AESCipher(aeskey) aesc.set_iv(aesiv) decrypted_bytes = aesc.decrypt(encrypt_payload) # decrypted_bytes.hex() return decrypted_bytes
def decrypt_image(self): key = self.get_key_from_image() cipher = self.cipher aes = AESCipher(key) base64_decoded = aes.decrypt(cipher) fh = open("decryptedImage.png", "wb") fh.write(base64_decoded.decode('base64')) fh.close()
def __init__(self, host, port): self.session_key = self.generate_random_key() self.host = host self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((host, port)) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.aes = AESCipher(self.session_key)
def save_session(self): data = { 'username': self.username, 'passwd': self.password } cipher = AESCipher() enc = cipher.encrypt(json.dumps(data)) with open('session', 'wb') as f: f.write(enc)
def save_session(self): data = { 'access_token': self.access_token, 'refresh_token': self.refresh_token } cipher = AESCipher() enc = cipher.encrypt(json.dumps(data)) with open('session', 'wb') as f: f.write(enc)
def test_encrypt_decrypt(self): config = utils.get_config_parser() enc = AESCipher(config.get('AES', 'key')) f = open("password.txt", "w+") f.write("Password") f.close() enc.encrypt_file("password.txt", out_filename="password.enc") password = enc.decrypt_file("password.enc") assert password == "Password", "Failed to decrypt file"
def save_record(account): print(request.content_type) if not request.json or not 'size' in request.json: raise InvalidUsage('Invalid usage of this web-service detected', status_code=400) size = int(request.json['size']) decoded_compressed_record = request.json.get('data', "") symmetricKeyEncrypted = request.json.get('key', "") compressed_record = base64.b64decode(decoded_compressed_record) encrypted_json_record_str = zlib.decompress(compressed_record) pks1OAEPForDecryption = PKS1_OAEPCipher() pks1OAEPForDecryption.readDecryptionKey('decryption.key') symmetricKeyDecrypted = pks1OAEPForDecryption.decrypt( base64.b64decode(symmetricKeyEncrypted)) aesCipherForDecryption = AESCipher() aesCipherForDecryption.setKey(symmetricKeyDecrypted) json_record_str = aesCipherForDecryption.decrypt(encrypted_json_record_str) record_as_dict = json.loads(json_record_str) # Add the account ID to the reading here record_as_dict["account"] = account #print record_as_dict post_id = mongo_collection.insert_one(record_as_dict).inserted_id print('Saved as Id: %s' % post_id) producer = KafkaProducer( bootstrap_servers=['your.kafka.server.com:9092'], value_serializer=lambda m: json.dumps(m).encode('ascii'), retries=5) # send the individual records to the Kafka queue for stream processing raw_readings = record_as_dict["data"] counter = 0 for raw_reading in raw_readings: raw_reading["id"] = str(post_id) + str(counter) raw_reading["account"] = account producer.send("car_readings", raw_reading) counter += 1 producer.flush() # send the summary to the Kafka queue in case there is some stream processing required for that as well raw_summary = record_as_dict["summary"] raw_summary["id"] = str(post_id) raw_summary["account"] = account raw_summary["eventTime"] = record_as_dict["timestamp"] producer.send("car_summaries", raw_summary) producer.flush() return jsonify({'title': str(size) + ' bytes received'}), 201
def desencriptar(self, mensaje, x_i, y_i): clave_segura = self.generar_polinomio(x_i, y_i) # Creamos un objeto de tipo AESCipher para poder utilizar los algoritmos de cifrado aes = AESCipher() mensaje = aes.desencriptar(mensaje, str(clave_segura)) return mensaje
def save(key, entries): """ Encrypt the passwords we stored in RAM and write them to the database """ db = Database() cipher = AESCipher(key) tmp = [] for entry in entries: entry_2 = cipher.encrypt(entry[2]) tmp.append([entry[0], entry[1], entry_2.decode()]) # Write the encrypted passwords to the database if (db.update(tmp)): print_error("Couldn't save")
def load_session(self): loaded_session = None cipher = AESCipher() with open('session', 'rb') as f: enc = f.read() try: plain = cipher.decrypt(enc) loaded_session = json.loads(str(plain)) self.username = loaded_session['username'] self.password = loaded_session['passwd'] finally: return loaded_session
def decrypt_image(self, k): #key = self.get_key_from_image() key = k cipher = self.cipher aes = AESCipher(key) base64_decoded = aes.decrypt(cipher) #print(type(base64_decoded)) fh = open("decryptedImage.png", "wb") fh.write(base64.b64decode(base64_decoded)) #fh.write(base64_decoded.decode('base64')) fh.close() return (base64.b64decode(base64_decoded))
def __init__(self): """ Initialize ui. Connect ui elements to functions. Initialize LoginAgent """ super(RubLogin, self).__init__() uic.loadUi('design.ui', self) self.pushButton_login.clicked.connect(self.login) self.pushButton_logout.clicked.connect(self.logout) self.checkBox_auto.clicked.connect(self.checkBoxAuto) self.checkBox_save.clicked.connect(self.checkBoxSave) self.checkBox_auto_onstartup.clicked.connect( self.checkBoxAutoOnStartup) self.loginAgent = LoginAgent(self.textArea_log, self.checkBox_fileLogging, self.statusBar) self.guiEnabled = True aes_key = "Jgj-4f;5$f-d.kg&ghkDe-Fg&kSgZ5pd" self.aesCipher = AESCipher(aes_key) if len(sys.argv) > 1: for x in sys.argv: if x == "-nogui": self.guiEnabled = False # TODO comment try: data_file = open("data.bin", "rb") self.checkBox_fileLogging.setChecked(pickle.load(data_file)) self.checkBox_auto.setChecked(pickle.load(data_file)) self.checkBox_save.setChecked(pickle.load(data_file)) self.checkBox_auto_onstartup.setChecked(pickle.load(data_file)) if self.checkBox_save.isChecked(): self.lineEdit_id.setText( self.aesCipher.decrypt(pickle.load(data_file), pickle.load(data_file))) self.lineEdit_pass.setText( self.aesCipher.decrypt(pickle.load(data_file), pickle.load(data_file))) elif not self.guiEnabled: data_file.close() self.cl_exit("No login data saved") data_file.close() except (FileNotFoundError, EOFError): if not self.guiEnabled: self.cl_exit("No login data saved") if self.guiEnabled: # systemtray icon self.trayIcon = SystemTrayIcon(QtGui.QIcon("logo.png"), self) self.show() if self.checkBox_auto_onstartup.isChecked(): self.checkBox_auto.setChecked(True) self.login()
def __init__(self, file_path, enc_key): self.Path = os.path.abspath(file_path) if not os.path.exists(self.Path): sys.exit('File does not exist!') if not os.path.isfile(self.Path): sys.exit(self.Path + ' - is not file!') try: file = open(file_path, 'rb') except Exception: sys.exit('Can not open file!') try: self.File_bytes = file.read() except Exception: sys.exit('Can not read file!') self.File_name = os.path.basename(self.Path) file_name_bytes = self.File_name.encode() if len(file_name_bytes) > 255: sys.exit('File name is too long!') self.File_name_len = bytes([len(file_name_bytes)]) self.Hash_sum = hashlib.md5(self.File_bytes).hexdigest() byte_string = self.Hash_sum.encode() \ + self.File_name_len \ + file_name_bytes \ + self.File_bytes cipher = AESCipher(enc_key) self.Encrypted_file = cipher.encrypt(byte_string.decode()) # The maximum number that is placed in the block self._max_enc_file_size = 9999999999999999999999999999999 size_enc_file = len(self.Encrypted_file) if size_enc_file > self._max_enc_file_size: sys.exit('File too large!') self.Encrypted_size = cipher.encrypt(str(size_enc_file)) self.Finally_byte_string = self.Encrypted_size + self.Encrypted_file self.Finally_size = len(self.Finally_byte_string) self.Binary_string = self.get_binary_string() file.close()
def load(key): """ Get the passwords stored in the database and decrypt them """ cipher = AESCipher(key) db = Database() entries = db.load_entries() tmp = [] for entry in entries: try: entry_2 = cipher.decrypt(entry[2]) except Error as e: print("Error: " + str(e)) tmp.append([entry[0], entry[1], entry_2]) return tmp
def mutAuthClient(self, sharedKey): try: # Create AES object with shared key cipher = AESCipher(sharedKey) # Client's challenge to server Ra = Random.new().read(16) print 'Ra:', Ra.encode('hex') message= 'Client'+ Ra print 'Sending message:', message self.send(message) # Wait for response from server reply = self.waitToRec() print 'Received:', reply.encode('hex') # Decrypt response plainText = cipher.decrypt(reply) print 'Decrypted:', plainText # Obtain Ra and Rb from response RaTest = plainText[-32:-16] print 'Ra received:', RaTest.encode('hex') Rb=plainText[-16:] print 'Rb received:', Rb.encode('hex') # Compare received Ra with sent Ra if RaTest!= Ra: print 'Different Ra received: mutual auth failed' self.close() sys.exit(1) # Encrypt "name","Rb" with shared key and send it finalReply = 'Client' + Rb print 'Encrypting reply:', finalReply finalCipher = cipher.encrypt(finalReply) print 'Sending cipher:', finalCipher.encode('hex') self.send(finalCipher) # Wait for response from server replyauth = self.waitToRec() if replyauth == 'mutual auth failed': print 'Server denied authentication: mutual auth failed' self.close() sys.exit(1) else: print 'CLIENT: mutual auth passed' except: print 'Mutual auth failed' self.close() sys.exit(1)
def receive_messages(skt, sess_key): msg = open('msgs.txt', 'w') data = skt.recv(1024) while data: data_arr = split_combined_pickle(data) for item in data_arr: if not item is None: item = pickle.loads(item) cipher = AESCipher(sess_key) decrypted = cipher.decrypt(item) msg.write(decrypted) data = skt.recv(1024) # Fetch next packet msg.close() skt.close()
def load_session(self): cipher = AESCipher() with open('session', 'rb') as f: enc = f.read() try: plain = cipher.decrypt(enc) loaded_session = json.loads(str(plain)) self.access_token = loaded_session['access_token'] self.refresh_token = loaded_session['refresh_token'] return True except: print( "error when load session, please delete session file and try again." )
def decrypt_msg(content, token): client_key = decrypt_token(token) if client_key is None: return None else: cipher = AESCipher(client_key["gen_session_key"]) try: msg = json.loads(cipher.decrypt(content)) # malicious user except json.decoder.JSONDecodeError as e: return none return msg, client_key["gen_session_key"]
def changepass(self, oldpass, newpass): if oldpass == self._password: self._password = newpass self._cipher = AESCipher(self._password) self.save() return True else: return False
def __init__(self, path, password): self._path = path self._password = password self._cipher = AESCipher(self._password) self._data = {} try: self.load() except (UnicodeDecodeError, ValueError): raise Exception("Invalid password")
def receive_messages(skt, sess_key): # because each line is sent by pickling # it might be better to read from the socket # as a stream and let pickle do its job msg = open('msgs.txt', 'w') data = skt.recv(1024) count = 1 while data: data_arr = split_combined_pickle(data) for item in data_arr: print item if not item is None: item = pickle.loads(item) cipher = AESCipher(sess_key) decrypted = cipher.decrypt(item) msg.write(decrypted) data = skt.recv(1024) # Fetch next packet count += 1 print 'received', count # Proper teardown msg.close() skt.close()
dupe_count = find_duplicate_blocks(data) if dupe_count > 2: return 2 elif dupe_count == 0: return 1 else: return -1 success = 0 fail = 0 msg = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" for i in range(200): enc_msg = generate_jibber_jabber(msg) mode = randint(1,2) if mode == 1: a = AESCipher(key=generate_key(), bs=16, iv=generate_key()) enc = a.cbc_encrypt(enc_msg) elif mode == 2: a = AESCipher(key=generate_key(), bs=16, iv=generate_key()) enc = a.ecb_encrypt(enc_msg) computed_mode = encryption_oracle(enc) if mode == computed_mode: success += 1 else: fail += 1 print "Success rate: %.3f" % float(float(success)/float((success + fail)))
from AESCipher import AESCipher a=AESCipher("0123456789ABCDEF") b=AESCipher("0123456789ABCDEF") message= a.encrypt("Hello World") print(message) decryped=b.decrypt(message) print(decryped)
conn, addr = sock.accept() # sends public key and signature pub = public_key.exportKey() conn.send(pickle.dumps(pub)) conn.send(pickle.dumps(signature)) print("Public key and signature sent.") # reads session password key = pickle.loads(conn.recv(1024)) #decrypt the password rsa = PKCS1_OAEP.new(private_key) key = rsa.decrypt(key) # create an AES key using the password cipher = AESCipher(key) print("Session key obtained.") # opens the text file for reading with open("docs.txt", "r") as f: for line in f: # encrypt the line enc = cipher.encrypt(line) # pickle and send it conn.send(pickle.dumps(enc)) conn.close() print("Document send.")
class Alice(): def __init__(self, host, port): self.session_key = self.generate_random_key() self.host = host self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((host, port)) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.aes = AESCipher(self.session_key) @staticmethod def generate_random_key(): return os.urandom(BS) def encrypt_session_key(self, public_key): self.encrypted_session_key = public_key.encrypt(self.session_key) def send_message(self, message): lol = pickle.dumps(message) self.socket.send(lol) pass def receive_message(self): return self.socket.recv(BUFFER_SIZE) def get_public_key(self): with open(PUBLIC_KEY_FILE, "r") as f: public_key = RSA.importKey(f.read()) return PKCS1_OAEP.new(public_key) def receive_all_message(self): messages = '' while(True): message = self.receive_message() if (len(message) == 0): break messages += message return messages def decode_message(self, messages): message_list = messages.split(".") full_message = '' for message in message_list: if (len(message) == 0): break real_message = pickle.loads(message+'.') full_message += self.aes.decrypt(real_message) return full_message def write_to_file(self, message): with open(OUTPUT_FILE, 'w') as f: f.seek(0) f.truncate() f.write(message) def connect(self): # get public key from file public_key = self.get_public_key() # encrypt session key self.encrypt_session_key(public_key) # send encrypted session key self.send_message(self.encrypted_session_key) # receive all message messages = self.receive_all_message() # get plaintext message messages = self.decode_message(messages) # write to file self.write_to_file(messages) # close socket self.socket.close()
from AESCipher import AESCipher def f1(s, aes): return a.cbc_encrypt("comment1=cooking%20MCs;userdata=" + s + ";comment2=%20like%20a%20pound%20of%20bacon") a = AESCipher() prefix_size = 32 block_size = 16 flp1 = "IAAAAAIAAAAAAAAA" #This is our goal first 16 blocks str1 = "AAAAAAAAAAAAAAAA3admin5true" #This is what we'll pass as the userdata to f1 enc1 = f1(str1, a) #This string has 2 bits flipped in the specfic positions required to turn the 3 into ; and 5 into = xor = "\x00" * 32 + "\x08\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00" * (len(enc1) - 48) #xor them together enc2 = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(enc1, xor)) #Great success! print a.cbc_decrypt(enc2)
def determine_block_size(aes): msg = "A" size = len(aes.ecb_encrypt(msg)) for i in range(100): msg += "A" new_size = len(aes.ecb_encrypt(msg)) if new_size > size: break return size data = b64decode('Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK') key = generate_key() a = AESCipher(key) bs = determine_block_size(a) print "Block size: %s" % bs known_data = "" char_dict = {} for i in range(1, 176): short_str = "A" * (bs-i) + known_data for j in range(256): str = short_str + known_data + chr(j) char_dict[str] = a.ecb_encrypt(str) enc = short_str + data[:i] msg = a.ecb_encrypt(enc) for k,v in char_dict.iteritems():
class PassStorage(object): def __init__(self, path, password): self._path = path self._password = password self._cipher = AESCipher(self._password) self._data = {} try: self.load() except (UnicodeDecodeError, ValueError): raise Exception("Invalid password") def load(self): if os.path.exists(self._path): with open(self._path, "rb") as f: encrypted = f.read() js_data = self._cipher.decrypt(encrypted) self._data = json.loads(js_data) else: self.save() def save(self): with open(self._path, "wb") as f: js_data = json.dumps(self._data) encrypted = self._cipher.encrypt(js_data) f.write(encrypted) def changepass(self, oldpass, newpass): if oldpass == self._password: self._password = newpass self._cipher = AESCipher(self._password) self.save() return True else: return False def rows(self): return self._data.keys() def add(self, title): if title not in self._data: self._data[title] = {} self.save() return True else: return False def remove(self, title): if title in self._data: del self._data[title] self.save() return True else: return False def modify(self, title, key, value): if title in self._data: self._data[title][key] = value self.save() return True else: return False def delkey(self, title, key): if title in self._data and key in self._data[title]: del self._data[title][key] return True else: return False def keys(self, title): return self._data[title].keys() def value(self, title, key): return self._data[title][key]
from base64 import b64decode from binascii import hexlify from AESCipher import AESCipher a = AESCipher("YELLOW SUBMARINE", 16, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") f = open('task10_data.txt', 'rb') cipher_text = b64decode(f.read()) f.close() print a.cbc_decrypt(cipher_text)
] def pad_and_encrypt(a, msg): return a.cbc_encrypt(msg) def decrypt_and_check_pad(a, enc): msg = a.cbc_decrypt(enc) try: a.pkcs7chk(msg) except ValueError: return False return msg aes = AESCipher() aes.key="YELLOW SUBMARINE" msg = strings[0] cph = aes.cbc_encrypt(msg) def print_msg(msg): if DEBUG: print msg def decrypt_block(a, cph, block, pos, char): print_msg( "%s (%s): %s" % (pos, char, repr(block))) if len(block) < 16: block.append(chr(random.randint(0,2))) block = decrypt_block(a, cph, block, len(block), ord(block[pos-1]))
from AESCipher import AESCipher a = AESCipher('YELLOW SUBMARINE', 20) print "%s: %s" % (len(a.pkcs7pad('YELLOW SUBMARINE')), a.pkcs7pad('YELLOW SUBMARINE'))
if (len(sys.argv) < 2): print "need a filename" exit(1) inputname = sys.argv[1] passPhraseName= "MyPhraseName" passPhrase = "rosebud" #obtain cleartext fh = open(inputname) if (fh == None): print "bad filename" exit(1) cleartext = fh.read() fh.close() #encrypt the cleartext and write to a file #use the MD5 of the passphrase as the key enckey = hashlib.sha256(passPhrase).digest() aes = AESCipher(enckey) ciphertext = aes.encrypt(cleartext) #truncate file if it exists outfile = open("{0}.{1}".format(inputname,passPhraseName),'w+') outfile.write(ciphertext) outfile.close() print "Completed"
class Amy: def __init__(self, host, port): self.session_key = self.generate_random_key() self.host = host self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((host, port)) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.aes = AESCipher(self.session_key) @staticmethod def generate_random_key(): return os.urandom(BS) def encrypt_session_key(self, public_key): self.encrypted_session_key = public_key.encrypt(self.session_key) def send_message(self, message): lol = pickle.dumps(message) self.socket.send(lol) pass def receive_message(self): return self.socket.recv(BUFFER_SIZE) def read_ca_public_key(self): with open(CA_PUBLIC_KEY_FILE, "r") as f: content = f.read() return content def get_public_key(self, public_key_content): return PKCS1_OAEP.new(RSA.importKey(public_key_content)) def get_ca_public_key(self, public_key_content): return PKCS1_PSS.new(RSA.importKey(public_key_content)) def receive_all_message(self): messages = "" while True: message = self.receive_message() if len(message) == 0: break messages += message return messages def decode_message(self, messages): message_list = messages.split(".") full_message = "" for message in message_list: if len(message) == 0: break real_message = pickle.loads(message + ".") full_message += self.aes.decrypt(real_message) return full_message def write_to_file(self, message): with open(OUTPUT_FILE, "w") as f: f.seek(0) f.truncate() f.write(message) def verify(self, name, public_key_content, signature, ca_public_key): md5 = MD5.new() md5.update(name) md5.update(public_key_content) return ca_public_key.verify(md5, signature) def connect(self): # receive bryan public key public_key_content = pickle.loads(self.receive_message()) public_key = self.get_public_key(public_key_content) # receive signature signature = pickle.loads(self.receive_message()) # get CA public key from file ca_public_key = self.get_ca_public_key(self.read_ca_public_key()) if self.verify(RECEIVER_NAME, public_key_content, signature, ca_public_key): # encrypt session key self.encrypt_session_key(public_key) # send encrypted session key self.send_message(self.encrypted_session_key) # receive all message messages = self.receive_all_message() # get plaintext message messages = self.decode_message(messages) # write to file self.write_to_file(messages) else: print "Error:MD5 signature does not match" # close socket self.socket.close()
def decrypt_password(self, host): cipher = AESCipher(base64.decodestring(host['key'])) return cipher.decrypt(host['password'])
from pandas import * import os import math from AESCipher import AESCipher def list_files(path): files = [] for name in os.listdir(path): if os.path.isfile(os.path.join(path, name)): files.append(name) return files # Configuration csv_dir = "/Users/padmakar/PycharmProjects/csv_encrrypt/csv_sample" csv_files = list_files(os.path.join(csv_dir)) cypher_obj = AESCipher('2805') header_row = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8', 'col9', 'col10', 'col11','col12', 'col13', 'col14', 'col15'] columns_to_decrypt = ['col5'] encrpyt_mapping = [] for col in columns_to_decrypt: encrpyt_mapping.append(col) encrpyt_mapping.append(str(col) + " decrypted_value") for csv_file in csv_files: print "Parsing csv file %s" % csv_file mapping_df = DataFrame(columns=encrpyt_mapping) data = read_csv(os.path.join(csv_dir, csv_file), error_bad_lines=False, names=header_row, dtype='unicode') print "Encrypting of data in csv file %s is starting" % csv_file
if (len(sys.argv) < 2): print "need a filename" exit(1) inputname = sys.argv[1] passPhraseName= "MyPhraseName" passPhrase = "rosebud" #inputname = "declaration.txt.{0}".format(passPhraseName) outputname = "{0}-decrypted.txt".format(inputname) #obtain ciphertext fh = open(inputname) ciphertext = fh.read() fh.close() #encrypt the cleartext and write to a file #use the MD5 of the passphrase as the key enckey = hashlib.sha256(passPhrase).digest() aes = AESCipher(enckey) cleartext = aes.decrypt(ciphertext) #truncate file if it exists outfile = open(outputname,'w+') outfile.write(cleartext) outfile.close() print "Completed"
from pandas import * import os import math from AESCipher import AESCipher def list_files(path): files = [] for name in os.listdir(path): if os.path.isfile(os.path.join(path, name)): files.append(name) return files # Configuration csv_dir = "/path/to/split/dir" csv_files = list_files(os.path.join(csv_dir)) cypher_obj = AESCipher('2805') header_row = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8', 'col9', 'col10', 'col11', 'col12', 'col13', 'col14', 'col15'] columns_to_encrypt = ['col6', 'col7'] encrpyt_mapping = [] for col in columns_to_encrypt: encrpyt_mapping.append(col) encrpyt_mapping.append(str(col) + " encrypted_value") for csv_file in csv_files: print "Parsing csv file %s" % csv_file mapping_df = DataFrame(columns=encrpyt_mapping) data = read_csv(os.path.join(csv_dir, csv_file), error_bad_lines=False, names=header_row, dtype='unicode') print "Encrypting of data in csv file %s is starting" % csv_file