def test_round_trip(self): pt = b("A") * 1024 c1 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8) c2 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8) ct = c1.encrypt(pt) self.assertEqual(c2.decrypt(ct), pt) self.assertEqual(c1.encrypt(b("")), b("")) self.assertEqual(c2.decrypt(b("")), b(""))
def test_eiter_encrypt_or_decrypt(self): """Verify that a cipher cannot be used for both decrypting and encrypting""" c1 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8) c1.encrypt(b("8")) self.assertRaises(TypeError, c1.decrypt, b("9")) c2 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8) c2.decrypt(b("8")) self.assertRaises(TypeError, c2.encrypt, b("9"))
def test_seek(self): cipher1 = ChaCha20.new(key=b("9") * 32, nonce=b("e") * 8) offset = 64 * 900 + 7 pt = b("1") * 64 cipher1.encrypt(b("0") * offset) ct1 = cipher1.encrypt(pt) cipher2 = ChaCha20.new(key=b("9") * 32, nonce=b("e") * 8) cipher2.seek(offset) ct2 = cipher2.encrypt(pt) self.assertEquals(ct1, ct2)
def test_streaming(self): """Verify that an arbitrary number of bytes can be encrypted/decrypted""" from Crypto.Hash import SHA1 segments = (1, 3, 5, 7, 11, 17, 23) total = sum(segments) pt = b("") while len(pt) < total: pt += SHA1.new(pt).digest() cipher1 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8) ct = cipher1.encrypt(pt) cipher2 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8) cipher3 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8) idx = 0 for segment in segments: self.assertEqual(cipher2.decrypt(ct[idx:idx+segment]), pt[idx:idx+segment]) self.assertEqual(cipher3.encrypt(pt[idx:idx+segment]), ct[idx:idx+segment]) idx += segment
def test_seek_tv(self): # Test Vector #4, A.1 from # http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 key = bchr(0) + bchr(255) + bchr(0) * 30 nonce = bchr(0) * 8 cipher = ChaCha20.new(key=key, nonce=nonce) cipher.seek(64 * 2) expected_key_stream = unhexlify(b( "72d54dfbf12ec44b362692df94137f32" "8fea8da73990265ec1bbbea1ae9af0ca" "13b25aa26cb4a648cb9b9d1be65b2c09" "24a66c54d545ec1b7374f4872e99f096" )) ct = cipher.encrypt(bchr(0) * len(expected_key_stream)) self.assertEqual(expected_key_stream, ct)
def decryptIMG(source, key): key = newHash(key) with open("iv.txt", 'br') as f: iv = f.read() kwargs = {"key": key, "nonce": iv} cipher = ChaCha20.new(**kwargs) rgbSource = source tX, tY, bX, bY = rgbSource.getbbox() decrypted = Image.new("RGB", (bX,bY), 255) for x_loc in range(0,int(bX)): for y_loc in range(0,int(bY)): r, g, b = rgbSource.getpixel((x_loc,y_loc)) r = cipher.decrypt(bytes([r])) g = cipher.decrypt(bytes([g])) b = cipher.decrypt(bytes([b])) decrypted.putpixel((x_loc,y_loc),(r[0],g[0],b[0])) return decrypted
def encryptIMG(source, key): key = newHash(key) iv = get_random_bytes(8) kwargs = {"key": key, "nonce": iv} cipher = ChaCha20.new(**kwargs) rgbSource = source.convert("RGB") tX, tY, bX, bY = rgbSource.getbbox() for x_loc in range(0,int(bX)): for y_loc in range(0,int(bY)): r, g, b = rgbSource.getpixel((x_loc,y_loc)) r = cipher.encrypt(bytes([r])) g = cipher.encrypt(bytes([g])) b = cipher.encrypt(bytes([b])) rgbSource.putpixel((x_loc,y_loc),(r[0],g[0],b[0])) with open("iv.txt", 'bw') as f: f.write(iv) return rgbSource
def __init__(self, key, nonce): """Initialize a ChaCha20-Poly1305 AEAD cipher object See also `new()` at the module level.""" self.nonce = _copy_bytes(None, None, nonce) self._next = (self.update, self.encrypt, self.decrypt, self.digest, self.verify) self._authenticator = Poly1305.new(key=key, nonce=nonce, cipher=ChaCha20) self._cipher = ChaCha20.new(key=key, nonce=nonce) self._cipher.seek(64) # Block counter starts at 1 self._len_aad = 0 self._len_ct = 0 self._mac_tag = None self._status = _CipherStatus.PROCESSING_AUTH_DATA
def runTest(self): for (key, nonce, stream) in self.tv: c = ChaCha20.new(key=unhexlify(b(key)), nonce=unhexlify(b(nonce))) ct = unhexlify(b(stream)) pt = b("\x00") * len(ct) self.assertEqual(c.encrypt(pt), ct)
# In[15]: from Crypto.Cipher import ChaCha20 from Crypto.Hash import HMAC, SHA256 path = '/home/ricardo/Documents/Cripto/plaintext.txt' myfile = open(path,'rb') mytext = myfile.read() print(mytext) #plaintext = b'Attack at dawn' secret = b'*Thirty-two byte (256 bits) key*' cipher = ChaCha20.new(key=secret) msg = cipher.nonce + cipher.encrypt(mytext) print(msg) # In[16]: from Crypto.Cipher import ChaCha20 secret = b'*Thirty-two byte (256 bits) key*' msg_nonce = msg[:8] ciphertext = msg[8:] cipher = ChaCha20.new(key=secret, nonce=msg_nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext)
def chacha20_decrypt(self, nonce, ciphertext, counter=0): return ChaCha20.new(key=self.key, nonce=nonce).decrypt(ciphertext)
def chacha20_cbc_encrypt(data, key, enc_iv): """Encrypt and return `data` with ChaCha20.""" cipher = ChaCha20.new(key=key, nonce=enc_iv) return cipher.encrypt(data)
def decrypt(ct, key, nonce): "Decrypt a message using ChaCha20 with the given key and nonce" enc = ChaCha20.new(key=key, nonce=nonce) pt = enc.decrypt(ct).decode("utf8") return pt
def generic_chacha20(self, implementation): print("") # Encrypt a test message with a known good implementation import json from base64 import b64encode from Crypto.Cipher import ChaCha20 from Crypto.Random import get_random_bytes from struct import pack, unpack from binascii import hexlify def byte_xor(ba1, ba2): """ XOR two byte strings """ return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) plaintext = b'A' * 64 # key = get_random_bytes(32) key = bytes([i for i in range(32)]) # nonce = get_random_bytes(12) nonce = bytes([(i * 16 + i) for i in range(12)]) cipher = ChaCha20.new(key=key, nonce=nonce) ciphertext = cipher.encrypt(plaintext) nonceb64 = b64encode(cipher.nonce).decode('utf-8') ciphertextb64 = b64encode(ciphertext).decode('utf-8') keystream = byte_xor(plaintext, ciphertext) keystream_hex = hexlify(keystream).decode('utf8') result = json.dumps({ 'nonce': nonceb64, 'ciphertext': ciphertextb64, 'keystream': keystream_hex }) # print(result) # cipher = ChaCha20.new(key=key, nonce=nonce) # cipher.seek(0) # print(cipher.decrypt(ciphertext)) m = Module() m.submodules.chacha20 = chacha20 = ChaCha20Cipher(implementation) key_words = unpack("<8I", key) m.d.comb += [ chacha20.i_key[i].eq(key_words[i]) for i in range(len(key_words)) ] nonce_words = unpack("<3I", nonce) m.d.comb += [ chacha20.i_nonce[i].eq(nonce_words[i]) for i in range(len(nonce_words)) ] sim = Simulator(m) sim.add_clock(1e-6, domain="sync") def process(): ks = [] iterations = 0 yield chacha20.i_en.eq(1) yield for i in range(30 * 4): # Simulate until it'd finished iterations += 1 if (yield chacha20.o_ready) != 0: yield yield yield break yield for i in range(16): ks.append((yield chacha20.o_stream[i])) keystream_hdl = pack("<16I", *ks) print(f"Took {iterations} iterations") print("Keystream generated by simulation: ", hexlify(keystream_hdl)) print("Decryption using simulation: ", byte_xor(keystream_hdl, ciphertext)) self.assertEqual(keystream_hdl, keystream) self.assertEqual(plaintext, byte_xor(keystream_hdl, ciphertext)) sim.add_sync_process(process) with sim.write_vcd("test.vcd", "test.gtkw"): sim.run()
def setup(self): self.cipher = ChaCha20.new(key=self.key, nonce=self.iv)
def encrypt(): shellcode = "\x48\x31\xc0\x50\x5a\x52\x48\xbb\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x53\x48\x89\xe7\x50\x57\x48\x89\xe6\x6a\x3b\x58\x0f\x05" # Execve-stack shellcode secret = b'G-KaPdSgVkYp3s6v9y$B&E)H@MbQeThW' cipher = ChaCha20.new(key=secret) crypted_shellcode = cipher.nonce + cipher.encrypt(shellcode) return base64.b64encode(crypted_shellcode)
def get_cipher(self, protected_stream_key): key_hash = hashlib.sha512(protected_stream_key).digest() key = key_hash[:32] nonce = key_hash[32:44] return ChaCha20.new(key=key, nonce=nonce)
def solve(): with open("crackstaller.exe", 'rb') as f: content = bytearray(f.read()) for i in offset: pt = decode(content[int(i[0], 16):int(i[0], 16) + int(i[1], 16)], git, 7) print(pt) # with open('dmp', 'wb') as f: # f.write(decode(content[0x17480: 0x17480+0x1A600], key2, 4)) # 36338 -> 3635C buf = content[0x33d38:0x33d38 + 16] buf += content[0x33d48:0x33d48 + 16] buf += content[0x33d58:0x33d58 + 5] buf[0x46 - 0x38] = 0x58 print(buf) with open("shellcode", 'wb') as f: content = f.write(buf) print('=' * 50) with open("payload.sys", 'rb') as f: content = f.read() n_offset = [ ('0x4a08', '0x0f'), ('0x4a40', '0x2e'), ('0x4a70', '0x07'), #('0x4a8c', '0x07'), ] for i in n_offset: pt = decode(content[int(i[0], 16):int(i[0], 16) + int(i[1], 16)], git, 7) print(pt) data = b'BBACABA' h = sha256() h.update(data) key = h.digest() ct = content[0x4a78:0x4a78 + 0x10] print(ct) #ct = bytes([ct[i]^i for i in range(len(ct))]) cipher = ChaCha20.new(key=key, nonce=b'\0' * 8) passwd = cipher.decrypt(ct) l = len(passwd) buf = [i for i in range(256)] v7 = 0 v8 = 0 v12 = 0 for i in range(256): v14 = buf[i] v15 = v12 + 1 v16 = passwd[v12] v12 = 0 v7 = (v7 + buf[i] + v16) & 0xff buf[i] = buf[v7] buf[v7] = v14 v17 = v8 + 1 v8 = 0 if v15 < l: v8 = v17 v12 = v15 print(len(buf), buf) with open("credHelper.dll", 'rb') as f: content = f.read() tbl = content[0x187f0:0x187f0 + 48] v4 = buf[0] v5 = 0 v6 = buf[1] ans = [] o = 2 for i in range(45): v4 += 1 v7 = buf[(v4 + o) & 0xff] v6 += v7 v8 = buf[(v6 + o) & 0xff] buf[(v4 + o) & 0xff] = v8 buf[(v6 + o) & 0xff] = v7 ans.append(chr(tbl[v5] ^ buf[(v7 + v8 + o) & 0xff])) v5 += 1 print(''.join(ans))
def setup(self): from Crypto.Cipher import ChaCha20 self.cipher = ChaCha20.new(key=self.key, nonce=self.iv)
message = (n - len(message) % n) * "\x00" + message listnya = [int(message[i:i+n].encode('hex'),16) for i in range(0, len(message), n)] nextflagraw = 0 for item in listnya: nextflagraw = nextflagraw ^ item return nextflagraw def inttoseqchar(number): numberinhex = hex(number)[2:].zfill(6) listnya = [chr(int(numberinhex[i:i+2],16)) for i in range(0, 6, 2)] return ''.join(listnya) key = 'secretkey123456!' + 'secretkey123456!' #####IV = "a9cd5e3cfb793413".decode('hex') IV = "7365c71905dd1e4c".decode('hex') encipher = ChaCha20.new(key = key, nonce=IV) #encipher = ChaCha20.new(key = key) #credentials = pika.PlainCredentials('tesis','tesis') credentials = pika.PlainCredentials('admin','admin') #recipientaddr = '192.168.18.133' recipientaddr = 'localhost' portaddr = 5672 parameters = pika.ConnectionParameters(recipientaddr, portaddr,'/',credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.queue_declare(queue='firstqueue') isLast = False IV = encipher.nonce
def decrypt(self, encrypted, key, nonce): cipher = ChaCha20.new(key=key, nonce=nonce) decrypted = cipher.decrypt(encrypted) return decrypted
def encrypt(self, data, key, nonce): if type(data) is str: data = data.encode('utf-8') cipher = ChaCha20.new(key=key, nonce=nonce) encrypted = cipher.encrypt(data) return encrypted
def test_default_nonce(self): cipher1 = ChaCha20.new(key=bchr(1) * 32) cipher2 = ChaCha20.new(key=bchr(1) * 32) self.assertEqual(len(cipher1.nonce), 8) self.assertNotEqual(cipher1.nonce, cipher2.nonce)
def get_cipher(self, master_key, encryption_iv): return ChaCha20.new(key=master_key, nonce=encryption_iv)
def callback(ch, method, properties, body): initialflag = "FFFFFF" global fullbody global nextflagraw global messageid global messageidnum global decipher global iv global counter2 global counter if body[:6] == 'IVIVIV': nextflagraw = body[6:] iv[messageidnum] = nextflagraw decipher[messageidnum] = ChaCha20.new(key=key, nonce=nextflagraw) nextflag = (xor_message_chunk(nextflagraw) ^ int(initialflag, 16)) messageid[messageidnum] = [ nextflag % 16777216, (nextflag + 256) % 16777216 ] fullbody[messageidnum] = '' counter[messageidnum] = 0 counter2[messageidnum] = 0 messageidnum = messageidnum + 1 for items in messageid: nextflagraw = messageid[items] if body[:3] == inttoseqchar(nextflagraw[0]): decipher[items] = ChaCha20.new(key=key, nonce=iv[items]) fullbody[items] = fullbody[items] + decipher[items].decrypt( body[3:]) messageid[items][0] = (nextflagraw[0] ^ xor_message_chunk(body[3:])) % 16777216 counter[items] = counter[items] + 1 counter2[items] = counter2[items] + 1 #print("Received[" + str(items) + "]: " + body) break elif body[:3] == inttoseqchar(nextflagraw[1]): if counter[items] != 4: fullbody[items] = fullbody[items] + " --ADA YANG HILANG-- " counter[items] = 1 decipher[items] = ChaCha20.new(key=key, nonce=iv[items]) fullbody[items] = fullbody[items] + decipher[items].decrypt( body[3:]) messageid[items][0] = (nextflagraw[1] ^ xor_message_chunk(body[3:])) % 16777216 messageid[items][1] = (nextflagraw[1] + 256) % 16777216 counter2[items] = 1 #print("Received[" + str(items) + "]: " + body) break elif body[:3] == inttoseqchar( nextflagraw[0] ^ int(initialflag, 16)) or body[:3] == inttoseqchar( nextflagraw[1] ^ int(initialflag, 16)) or body[:3] == inttoseqchar( (nextflagraw[1] + 256) ^ int(initialflag, 16)): if counter[items] != counter2[items]: fullbody[items] = fullbody[items] + " --ADA YANG HILANG-- " decipher[items] = ChaCha20.new(key=key, nonce=iv[items]) fullbody[items] = fullbody[items] + decipher[items].decrypt( body[3:]) if kefile: filenya.write(fullbody[items]) filenya.close() fullbody.pop(items) messageid.pop(items) exit() else: #print("Received[" + str(items) + "]: " + body) print("Printing[" + str(items) + "]: " + fullbody[items]) fullbody.pop(items) messageid.pop(items) break ch.basic_ack(delivery_tag=method.delivery_tag)
def new(key, nonce): return ChaCha20.new(key=key, nonce=nonce)
def test_nonce(self): key = b'A' * 32 nonce = b'P' * 24 cipher = ChaCha20.new(key=key, nonce=nonce) self.assertEqual(nonce, cipher.nonce)
def encrypt(pt, key, nonce): "Encrypt a message using ChaCha20 with the given key and nonce" pt = pt.encode("utf8") enc = ChaCha20.new(key=key, nonce=nonce) return enc.encrypt(pt)
import sys import secrets import uuid from Crypto.Cipher import ChaCha20 from config import CHACHA20_NONCE_SIZE, CHACHA20_OPENSSL_NONCE_SIZE from util import corrupt_key if __name__ == "__main__": mismatches = int(sys.argv[1]) user_id = uuid.uuid4() key = secrets.token_bytes(ChaCha20.key_size) corrupted_key = corrupt_key(key, mismatches) nonce = secrets.token_bytes(CHACHA20_NONCE_SIZE) chacha20 = ChaCha20.new(key=corrupted_key, nonce=nonce) cipher = chacha20.encrypt(user_id.bytes) iv = chacha20.nonce print("Key:", key.hex()) print("Corrupted Key:", corrupted_key.hex()) print("Cipher:", cipher.hex()) print("UUID:", user_id) print("IV:", (bytes(CHACHA20_OPENSSL_NONCE_SIZE - len(iv)) + iv).hex())
def pycrypto_chacha20(keysize=32, data_size=1024): plaintext = get_random_bytes(data_size * 1024) secret = get_random_bytes(keysize) cipher = ChaCha20.new(key=secret) _ = cipher.nonce + cipher.encrypt(plaintext)
transformed_key = hashlib.sha256(key_composite).digest() print(transformed_key) master_key = hashlib.sha256(b'\x00' * 0x20 + # master seed transformed_key).digest() sha256 = hashlib.sha256(header).digest() cred_check = hmac.new( hashlib.sha512(b'\xff' * 8 + hashlib.sha512(b'\x00' * 0x20 + # Master seed transformed_key + b'\x01').digest()).digest(), header, hashlib.sha256).digest() cipher = ChaCha20.new(key=master_key, nonce=b'\x00' * 0x8) data = b'\x01\x04\x00\x00\x00' + b'\x00' * 4 + b'\x00' * 5 # InnerHeader xml = b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<KeePassFile>\n\t<Meta>\n\t\t<Generator>KeePassXC</Generator>\n\t\t<DatabaseName>Passwords</DatabaseName>\n\t\t<DatabaseNameChanged>246s1Q4AAAA=</DatabaseNameChanged>\n\t\t<DatabaseDescription/>\n\t\t<DatabaseDescriptionChanged>0o6s1Q4AAAA=</DatabaseDescriptionChanged>\n\t\t<DefaultUserName/>\n\t\t<DefaultUserNameChanged>0o6s1Q4AAAA=</DefaultUserNameChanged>\n\t\t<MaintenanceHistoryDays>365</MaintenanceHistoryDays>\n\t\t<Color/>\n\t\t<MasterKeyChanged>N4+s1Q4AAAA=</MasterKeyChanged>\n\t\t<MasterKeyChangeRec>-1</MasterKeyChangeRec>\n\t\t<MasterKeyChangeForce>-1</MasterKeyChangeForce>\n\t\t<MemoryProtection>\n\t\t\t<ProtectTitle>False</ProtectTitle>\n\t\t\t<ProtectUserName>False</ProtectUserName>\n\t\t\t<ProtectPassword>True</ProtectPassword>\n\t\t\t<ProtectURL>False</ProtectURL>\n\t\t\t<ProtectNotes>False</ProtectNotes>\n\t\t</MemoryProtection>\n\t\t<CustomIcons/>\n\t\t<RecycleBinEnabled>True</RecycleBinEnabled>\n\t\t<RecycleBinUUID>AAAAAAAAAAAAAAAAAAAAAA==</RecycleBinUUID>\n\t\t<RecycleBinChanged>0o6s1Q4AAAA=</RecycleBinChanged>\n\t\t<EntryTemplatesGroup>AAAAAAAAAAAAAAAAAAAAAA==</EntryTemplatesGroup>\n\t\t<EntryTemplatesGroupChanged>0o6s1Q4AAAA=</EntryTemplatesGroupChanged>\n\t\t<LastSelectedGroup>AAAAAAAAAAAAAAAAAAAAAA==</LastSelectedGroup>\n\t\t<LastTopVisibleGroup>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleGroup>\n\t\t<HistoryMaxItems>10</HistoryMaxItems>\n\t\t<HistoryMaxSize>6291456</HistoryMaxSize>\n\t\t<SettingsChanged>0o6s1Q4AAAA=</SettingsChanged>\n\t\t<CustomData>\n\t\t\t<Item>\n\t\t\t\t<Key>KPXC_DECRYPTION_TIME_PREFERENCE</Key>\n\t\t\t\t<Value>1000</Value>\n\t\t\t</Item>\n\t\t\t<Item>\n\t\t\t\t<Key>_LAST_MODIFIED</Key>\n\t\t\t\t<Value>Sun Jan 12 03:51:58 2020 GMT</Value>\n\t\t\t</Item>\n\t\t</CustomData>\n\t</Meta>\n\t<Root>\n\t\t<Group>\n\t\t\t<UUID>F69os494TDK6douojK65vQ==</UUID>\n\t\t\t<Name>Root</Name>\n\t\t\t<Notes/>\n\t\t\t<IconID>48</IconID>\n\t\t\t<Times>\n\t\t\t\t<LastModificationTime>0o6s1Q4AAAA=</LastModificationTime>\n\t\t\t\t<CreationTime>0o6s1Q4AAAA=</CreationTime>\n\t\t\t\t<LastAccessTime>0o6s1Q4AAAA=</LastAccessTime>\n\t\t\t\t<ExpiryTime>0o6s1Q4AAAA=</ExpiryTime>\n\t\t\t\t<Expires>False</Expires>\n\t\t\t\t<UsageCount>0</UsageCount>\n\t\t\t\t<LocationChanged>0o6s1Q4AAAA=</LocationChanged>\n\t\t\t</Times>\n\t\t\t<IsExpanded>True</IsExpanded>\n\t\t\t<DefaultAutoTypeSequence/>\n\t\t\t<EnableAutoType>null</EnableAutoType>\n\t\t\t<EnableSearching>null</EnableSearching>\n\t\t\t<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>\n\t\t</Group>\n\t\t<DeletedObjects/>\n\t</Root>\n</KeePassFile>\n' data += xml # data = pad(data, 16) block_data = struct.pack("<I", len(data)) + cipher.encrypt(data) block_checksum = hmac.new( hashlib.sha512( struct.pack('<Q', 0) + hashlib.sha512(b'\x00' * 0x20 + transformed_key + b'\x01').digest()).digest(), struct.pack('<Q', 0) + struct.pack('<I', len(data)) + block_data[4:], hashlib.sha256).digest()
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+-+[]" key = ''.join([ chars[random.randrange(0, len(chars))] for i in range(key_length) ]).encode("utf8") nonce = ''.join([ chars[random.randrange(0, len(chars))] for i in range(nonce_length) ]).encode("utf8") if ENCRYPTION_TYPE == 1: cipher = AES.new(key, AES.MODE_EAX, nonce) ciphertext = cipher.encrypt(data.encode("utf8")) elif ENCRYPTION_TYPE == 2: cipher = Salsa20.new(key=key, nonce=nonce) ciphertext = cipher.encrypt(data.encode("utf8")) elif ENCRYPTION_TYPE == 3: cipher = ChaCha20.new(key=key, nonce=nonce) ciphertext = cipher.encrypt(data.encode("utf8")) print("Constructing Empty Forma...") f_l = random.randrange(MIN_LEN, MAX_LEN) forma = [] for i in range(f_l): forma.append([0, 0]) print("Status :", str(round((i / f_l) * 100, 1)) + "%", end="\r") # constructing first symbol list print("Constructing Symbol List...") c_chars = []
import socket from Crypto.Cipher import ChaCha20 host = '127.0.0.1' port = 5000 server = socket.socket() server.bind((host, port)) server.listen(1) connection, address = server.accept() print("Connection from:", str(address)) while True: data = connection.recv(1024) if not data: break secret_key = bytes("*****32 byte (256 bits) key*****", "utf-8") cipher = ChaCha20.new(key=secret_key, nonce=data[:8]) data = cipher.decrypt(data[8:]) data = str(data, "utf-8", errors="ignore") print("From client:", data) connection.send(bytes("message received", "utf-8")) connection.close()
def chacha20_encrypt(self, nonce, plaintext, counter=0): plaintext = tobytes(plaintext) return ChaCha20.new(key=self.key, nonce=nonce).encrypt(plaintext)
def get_cipher(self, iv): return ChaCha20.new(key=self.key, nonce=iv)
def test_new_positive(self): cipher = ChaCha20.new(key=b("0")*32, nonce=b("0")*8) self.assertEqual(cipher.nonce, b("0") * 8)
def test_new_positive(self): cipher = ChaCha20.new(key=b("0")*32, nonce=b"0"*8) self.assertEqual(cipher.nonce, b"0" * 8) cipher = ChaCha20.new(key=b("0")*32, nonce=b"0"*12) self.assertEqual(cipher.nonce, b"0" * 12)
print(key) print("=========================================") #pip3 install pycryptodome #pip3 install pycryptodomex #pip3 install pycrypto print("=============================================") print("=============================================") plaintext = trama key_critpy = os.environ.get("KEY_CHACHA20").encode('utf-8') cipher = ChaCha20.new(key=key_critpy) ciphertext = cipher.encrypt(plaintext) #return bytes nonce = b64encode(cipher.nonce).decode('utf-8') ct = b64encode(ciphertext).decode('utf-8') result = json.dumps({'nonce': nonce, 'ciphertext': ct}) b64 = json.loads(result) nonce2 = b64decode(b64['nonce']) ciphertext2 = b64decode(b64['ciphertext']) cipher = ChaCha20.new(key=key_critpy, nonce=nonce2) plaintext = cipher.decrypt(ciphertext2)
def test_rfc7539(self): # from https://tools.ietf.org/html/rfc7539 Annex A.1 # Each item is: key, nonce, block #, plaintext, ciphertext tvs = [ # Test Vector #1 ("00" * 32, "00" * 12, 0, "00" * 16 * 4, "76b8e0ada0f13d90405d6ae55386bd28" "bdd219b8a08ded1aa836efcc8b770dc7" "da41597c5157488d7724e03fb8d84a37" "6a43b8f41518a11cc387b669b2ee6586"), # Test Vector #2 ("00" * 31 + "01", "00" * 11 + "02", 1, "416e79207375626d697373696f6e2074" "6f20746865204945544620696e74656e" "6465642062792074686520436f6e7472" "696275746f7220666f72207075626c69" "636174696f6e20617320616c6c206f72" "2070617274206f6620616e2049455446" "20496e7465726e65742d447261667420" "6f722052464320616e6420616e792073" "746174656d656e74206d616465207769" "7468696e2074686520636f6e74657874" "206f6620616e20494554462061637469" "7669747920697320636f6e7369646572" "656420616e20224945544620436f6e74" "7269627574696f6e222e205375636820" "73746174656d656e747320696e636c75" "6465206f72616c2073746174656d656e" "747320696e2049455446207365737369" "6f6e732c2061732077656c6c20617320" "7772697474656e20616e6420656c6563" "74726f6e696320636f6d6d756e696361" "74696f6e73206d61646520617420616e" "792074696d65206f7220706c6163652c" "20776869636820617265206164647265" "7373656420746f", "a3fbf07df3fa2fde4f376ca23e827370" "41605d9f4f4f57bd8cff2c1d4b7955ec" "2a97948bd3722915c8f3d337f7d37005" "0e9e96d647b7c39f56e031ca5eb6250d" "4042e02785ececfa4b4bb5e8ead0440e" "20b6e8db09d881a7c6132f420e527950" "42bdfa7773d8a9051447b3291ce1411c" "680465552aa6c405b7764d5e87bea85a" "d00f8449ed8f72d0d662ab052691ca66" "424bc86d2df80ea41f43abf937d3259d" "c4b2d0dfb48a6c9139ddd7f76966e928" "e635553ba76c5c879d7b35d49eb2e62b" "0871cdac638939e25e8a1e0ef9d5280f" "a8ca328b351c3c765989cbcf3daa8b6c" "cc3aaf9f3979c92b3720fc88dc95ed84" "a1be059c6499b9fda236e7e818b04b0b" "c39c1e876b193bfe5569753f88128cc0" "8aaa9b63d1a16f80ef2554d7189c411f" "5869ca52c5b83fa36ff216b9c1d30062" "bebcfd2dc5bce0911934fda79a86f6e6" "98ced759c3ff9b6477338f3da4f9cd85" "14ea9982ccafb341b2384dd902f3d1ab" "7ac61dd29c6f21ba5b862f3730e37cfd" "c4fd806c22f221"), # Test Vector #3 ("1c9240a5eb55d38af333888604f6b5f0" "473917c1402b80099dca5cbc207075c0", "00" * 11 + "02", 42, "2754776173206272696c6c69672c2061" "6e642074686520736c6974687920746f" "7665730a446964206779726520616e64" "2067696d626c6520696e207468652077" "6162653a0a416c6c206d696d73792077" "6572652074686520626f726f676f7665" "732c0a416e6420746865206d6f6d6520" "7261746873206f757467726162652e", "62e6347f95ed87a45ffae7426f27a1df" "5fb69110044c0d73118effa95b01e5cf" "166d3df2d721caf9b21e5fb14c616871" "fd84c54f9d65b283196c7fe4f60553eb" "f39c6402c42234e32a356b3e764312a6" "1a5532055716ead6962568f87d3f3f77" "04c6a8d1bcd1bf4d50d6154b6da731b1" "87b58dfd728afa36757a797ac188d1") ] for tv in tvs: key = unhexlify(tv[0]) nonce = unhexlify(tv[1]) offset = tv[2] * 64 pt = unhexlify(tv[3]) ct_expect = unhexlify(tv[4]) cipher = ChaCha20.new(key=key, nonce=nonce) if offset != 0: cipher.seek(offset) ct = cipher.encrypt(pt) assert (ct == ct_expect)
from Crypto.Cipher import ChaCha20 import json from base64 import b64encode def pad_with_zeroes(key: str) -> bytes: key_bytes = key.encode('utf-8') new_key = (32 - len(key_bytes)) * b'0' + key_bytes return new_key plaintext = b"Attack on Titans" * 8 # 128 bytes key = pad_with_zeroes("Mateusz") cipher = ChaCha20.new(key=key) bytes_ciphertext = cipher.encrypt(plaintext) print("b64 encoded nonce and ciphertext") nonce = b64encode(cipher.nonce).decode('utf-8') ciphertext = b64encode(bytes_ciphertext).decode('utf-8') print(json.dumps({"nonce": nonce, "ciphertext": ciphertext}, indent=4)) with open("ciphertext.bin", 'wb+') as file: file.write(bytes_ciphertext) with open("nonce.bin", "wb+") as file: file.write(cipher.nonce)