Пример #1
0
    def runTest(self):

        data = b"0123"
        key = b"9" * 32
        nonce = b"t" * 8

        # Encryption
        data_mv = memoryview(bytearray(data))
        key_mv = memoryview(bytearray(key))
        nonce_mv = memoryview(bytearray(nonce))

        cipher1 = ChaCha20.new(key=key, nonce=nonce)
        ct = cipher1.encrypt(data)

        cipher2 = ChaCha20.new(key=key_mv, nonce=nonce_mv)
        key_mv[:1] = b'\xFF'
        nonce_mv[:1] = b'\xFF'
        ct_test = cipher2.encrypt(data_mv)

        self.assertEqual(ct, ct_test)
        self.assertEqual(cipher1.nonce, cipher2.nonce)

        # Decryption
        key_mv = memoryview(bytearray(key))
        nonce_mv = memoryview(bytearray(nonce))
        ct_mv = memoryview(bytearray(ct))

        cipher3 = ChaCha20.new(key=key_mv, nonce=nonce_mv)
        key_mv[:1] = b'\xFF'
        nonce_mv[:1] = b'\xFF'
        pt_test = cipher3.decrypt(ct_mv)

        self.assertEqual(data, pt_test)
Пример #2
0
    def runTest(self):

        # Encryption
        data = b("0123")
        key = b("9") * 32
        nonce = b("t") * 8

        cipher1 = ChaCha20.new(key=key, nonce=nonce)
        ref1 = cipher1.encrypt(data)

        cipher2 = ChaCha20.new(key=bytearray(key), nonce=bytearray(nonce))
        ref2 = cipher2.encrypt(bytearray(data))

        self.assertEqual(ref1, ref2)
        self.assertEqual(cipher1.nonce, cipher2.nonce)

        # Decryption

        cipher3 = ChaCha20.new(key=key, nonce=nonce)
        ref3 = cipher3.decrypt(data)

        cipher4 = ChaCha20.new(key=bytearray(key), nonce=bytearray(nonce))
        ref4 = cipher4.decrypt(bytearray(data))

        self.assertEqual(ref3, ref4)
Пример #3
0
    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(""))
Пример #4
0
    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(""))
Пример #5
0
    def test_nonce(self):
        key = b'A' * 32

        nonce1 = b'P' * 8
        cipher1 = ChaCha20.new(key=key, nonce=nonce1)
        self.assertEqual(nonce1, cipher1.nonce)

        nonce2 = b'Q' * 12
        cipher2 = ChaCha20.new(key=key, nonce=nonce2)
        self.assertEqual(nonce2, cipher2.nonce)
Пример #6
0
    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"))
Пример #7
0
    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"))
Пример #8
0
def chacha20(key, data):
    #print(b64encode(data))
    cipher = ChaCha20.new(key=key, nonce=nonce_chacha20)

    encrypted = cipher.encrypt(data)

    cipher = ChaCha20.new(key=key, nonce=nonce_chacha20)
    #plaintext = cipher.decrypt(encrypted)
    #print(len(encrypted))
    #print(b64encode(encrypted))
    #print(b64encode(plaintext))
    return encrypted
Пример #9
0
    def respond(self, msg):
        """ Processa uma mensagem (enviada pelo SERVIDOR)
        Imprime a mensagem recebida e lê do teclado a
        resposta. """
        cifra = ChaCha20.new(key=self.key, nonce=msg[8:16])
        print('Received: %r' % cifra.decrypt(msg[16:]))

        #Encripta a nova mensagem
        new = input().encode()
        nonce = os.urandom(8)
        cifra2 = ChaCha20.new(key=self.key, nonce=nonce)
        new = cifra2.encrypt(new)
        return self.name.encode() + nonce + new
Пример #10
0
    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.assertEqual(ct1, ct2)
Пример #11
0
    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)
Пример #12
0
def decrypt(key, nonce, body):
    key = key.encode('utf-8')
    nonce = a2b_hex(str(base64.b64decode(nonce), 'utf-8'))
    body = a2b_hex(str(base64.b64decode(body), 'utf-8'))
    cipher = ChaCha20.new(key=key, nonce=nonce)
    ciphertext = cipher.decrypt(body)
    return ciphertext
Пример #13
0
def decryptPayload(passwd: bytes, salt: bytes, iv: bytes, payload: bytes):
    key = scrypt(password=passwd, salt=salt, N=(2**14), key_len=32, r=8, p=1)
    cipher = ChaCha20.new(key=key, nonce=iv)
    rv = cipher.decrypt(payload)
    print(payload)
    # print(rv)
    return rv.decode(encoding='UTF-8')
Пример #14
0
def decript(pwd):
    enc_key, mac_key = passwd(pwd)
    
    # Take usefull info in cryptogram : plain text's MAC,cypher's nonce and encrypted text
    with open("mensagem.enc","rb") as f:
        f.seek(16) # Skip the salt
        mac_tag=f.read(64) # Read plain text MAC
        enc_msg_nonce= f.read(8) # Read cypher's nonce
        enc_msg = f.read()  # Read encripted text
    
    cypher = ChaCha20.new(key=enc_key,nonce = enc_msg_nonce) # Creates cypher
    
    cleantext=cypher.decrypt(enc_msg) #decript message
    
    try:        
        #mac of decripted text
        mac = HMAC.new(mac_key,cleantext,digestmod=SHA256) 
        #compare mac of decripted text with mac tag of plain text
        mac.hexverify(mac_tag)
        
        # Writing decripted message
        with open("mensagem.dec","wb") as f:
            f.write(cleantext)
    except ValueError:
        print("If you put the correct password, you message is compromised!")
Пример #15
0
def dict_decrypt(encrypted_json_str: str, key: bytes) -> dict:
    encrypted_json = json.loads(encrypted_json_str)
    cipher_text = base64.b64decode(encrypted_json['ciphertext'])
    nonce = base64.b64decode(encrypted_json['nonce'])
    cipher = ChaCha20.new(key=key, nonce=nonce)
    json_attr = cipher.decrypt(cipher_text)
    return json.loads(json_attr)
Пример #16
0
    def unprotect_passwords(self):
        """Unprotect the password fields in the database"""
        if self.inner_random_stream_id == 2:
            # Decrypt Salsa20-protected data
            key = hashlib.sha256(self.inner_random_stream_key).digest()
            cipher = Salsa20.new(key, SALSA20_NONCE)
        elif self.inner_random_stream_id == 3:
            # Decrypt ChaCha20-protected data
            key_hash = hashlib.sha512(self.inner_random_stream_key).digest()
            cipher = ChaCha20.new(key=key_hash[:32], nonce=key_hash[32:44])
        else:
            raise NotImplementedError(
                "Inner random stream variant {} not yet implemented".format(
                    self.inner_random_stream_id))

        # Perform like the XPath query //Value[@Protected='True']
        for value_elem in self.xml_dom.getElementsByTagName('Value'):
            if value_elem.firstChild is None:
                # Empty passwords are skipped
                continue
            protected_attr = value_elem.getAttribute('Protected')
            if not protected_attr:
                continue
            if protected_attr != 'True':
                raise ValueError(
                    "Unexpected Value/Protected attribute value: {}".format(
                        repr(protected_attr)))
            protected_data_b64 = value_elem.firstChild.data.strip()
            protected_data = base64.b64decode(protected_data_b64)
            plain_text_bin = cipher.decrypt(protected_data)
            plain_text = plain_text_bin.decode(errors='replace')
            value_elem.firstChild.data = plain_text
            value_elem.setAttribute('Protected', 'Decrypted')
Пример #17
0
def enc(msgs, keys, diff=0, index=0):
    new_msgs = []
    for msg in msgs:
        if msg is not None:
            new_msgs.append(prepend(msg, index))
        else:
            new_msgs.append(None)
    msgs = new_msgs
    max_len = len(max(msgs, key=len))
    len_to_use = next_prime(rand_min(next_prime(max_len * (len(msgs) + diff))))
    ciphertexts = []
    encoder = PKCS7Encoder(len_to_use)
    nonce = get_nonce(index)
    for i in range(len_to_use):
        if i >= len(msgs) or msgs[i] is None:
            plaintext = get_random_bytes(len_to_use)
        else:
            plaintext = msgs[i]
            plaintext = encoder.encode(plaintext)
        if i >= len(keys) or keys[i] is None:
            key = get_random_bytes(32)
        else:
            key = get_key(keys[i])
        cipher = ChaCha20.new(key=key, nonce=nonce)
        ciphertext = cipher.encrypt(plaintext)
        ciphertexts.append(ciphertext)
    shuffle(ciphertexts)
    return ciphertexts
Пример #18
0
 def decrypt(self, encrypted: str) -> str:
     cipher_text, nonce = encrypted.split(self._join_string)
     cipher_text = base64.b64decode(self.un_escape(cipher_text))
     nonce = base64.b64decode(self.un_escape(nonce))
     cipher = _ChaCha20.new(key=self.key, nonce=nonce)
     plain_text = cipher.decrypt(cipher_text)
     return plain_text.decode(self.encoding)
Пример #19
0
def decrypt(key, data, salsa):
    if salsa:
        dec = Salsa20.new(key=key, nonce=data[:8])
    else:
        dec = ChaCha20.new(key=key, nonce=data[:8])

    return dec.decrypt(data[8:])
Пример #20
0
def encryptPayload(passwd: bytes, salt: bytes, iv: bytes, payload: bytes):
    key = scrypt(password=passwd, salt=salt, N=(2**14), key_len=32, r=8, p=1)
    #print(key, iv, salt)
    cipher = ChaCha20.new(key=key, nonce=iv)
    rv = cipher.encrypt(payload)
    print(rv)
    return rv
Пример #21
0
def ChaChaMe(key, nonce, plaintext):
    '''
        Take a key and a "plaintext" (which in this case is probably a string of random bytes)
        ChaCha20 them and return
    '''
    cipher = ChaCha20.new(key=key, nonce=nonce)
    return cipher.encrypt(plaintext)
Пример #22
0
 def __chacha20(self, message: bytes):
     cipher = ChaCha20.new(key=CHACHA20_KEY)
     ct_bytes = cipher.encrypt(message)
     nonce = b64encode(cipher.nonce).decode(DEFAULT_ENCODING)
     ct = b64encode(ct_bytes).decode(DEFAULT_ENCODING)
     result = {"nonce": nonce, "cipher": ct}
     return b64encode(bytes(json.dumps(result), encoding=DEFAULT_ENCODING))
Пример #23
0
def encrypt(key, data, salsa):
    if salsa:
        enc = Salsa20.new(key=key)
    else:
        enc = ChaCha20.new(key=key)

    return enc.nonce + enc.encrypt(data)
Пример #24
0
 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
     )
Пример #25
0
 def encrypt(self, plain_text: str) -> str:
     cipher = _ChaCha20.new(key=self.key)
     if isinstance(plain_text, str):
         plain_text = plain_text.encode(self.encoding)
     cipher_bytes = cipher.encrypt(plain_text)
     nonce = base64.b64encode(cipher.nonce).decode(self.encoding)
     cipher_text = base64.b64encode(cipher_bytes).decode(self.encoding)
     return f"{self.escape(cipher_text)}{self._join_string}{self.escape(nonce)}"
 def reseed(self, seed='00' * 40):
     self.seed = seed
     self.key = bytes.fromhex(seed[0:64])
     self.iv = bytes.fromhex(seed[64:80])
     self.cipher = ChaCha20.new(key=self.key, nonce=self.iv)
     self._rand_block = self.cipher.encrypt(self.zeros)
     self._next_byte_index = 0
     self._block_counter = 1
Пример #27
0
    def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        key = b'4' * 32
        nonce = b'5' * 8
        cipher = ChaCha20.new(key=key, nonce=nonce)

        pt = b'5' * 16
        ct = cipher.encrypt(pt)

        output = bytearray(16)
        cipher = ChaCha20.new(key=key, nonce=nonce)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)

        cipher = ChaCha20.new(key=key, nonce=nonce)
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

        import sys
        if sys.version[:3] != '2.6':
            output = memoryview(bytearray(16))
            cipher = ChaCha20.new(key=key, nonce=nonce)
            cipher.encrypt(pt, output=output)
            self.assertEqual(ct, output)

            cipher = ChaCha20.new(key=key, nonce=nonce)
            cipher.decrypt(ct, output=output)
            self.assertEqual(pt, output)

        cipher = ChaCha20.new(key=key, nonce=nonce)
        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0' * 16)

        cipher = ChaCha20.new(key=key, nonce=nonce)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0' * 16)

        shorter_output = bytearray(7)

        cipher = ChaCha20.new(key=key, nonce=nonce)
        self.assertRaises(ValueError,
                          cipher.encrypt,
                          pt,
                          output=shorter_output)

        cipher = ChaCha20.new(key=key, nonce=nonce)
        self.assertRaises(ValueError,
                          cipher.decrypt,
                          ct,
                          output=shorter_output)
Пример #28
0
def encrypt_chacha(text):
    nonce_rfc7539 = get_random_bytes(12)
    cipher = ChaCha20.new(key=SECRET_KEY, nonce=nonce_rfc7539)
    ciphertext = cipher.encrypt(text.encode())
    nonce = cipher.nonce
    ct = ciphertext
    result = bytearray(nonce + ct)
    return result
Пример #29
0
def dict_encrypt(plain_attr: dict, key: bytes) -> str:
    cipher = ChaCha20.new(key=key)
    json_attr = json.dumps(plain_attr).encode()
    encrypted_data_bytes = cipher.encrypt(json_attr)

    nonce = base64.b64encode(cipher.nonce).decode()
    encrypted_data = base64.b64encode(encrypted_data_bytes).decode()

    return json.dumps({'nonce': nonce, 'ciphertext': encrypted_data})
Пример #30
0
    def __chacha20_decrypt(self, message: bytes):
        text = b64decode(message)
        j = json.loads(text)
        nonce = b64decode(j['nonce'])
        ct = b64decode(j['cipher'])

        cipher = ChaCha20.new(key=CHACHA20_KEY, nonce=nonce)
        pt = cipher.decrypt(ct)
        return pt
Пример #31
0
    def cipher_encode(plain: str, master_key_derived: bytes) -> str:
        cipher = ChaCha20.new(key=master_key_derived)
        ciphered = cipher.encrypt(plain.encode())
        nonce = cipher.nonce

        ciphered_64 = b64encode(ciphered)
        nonce_64 = b64encode(nonce)

        return f"{ciphered_64.decode()}.{nonce_64.decode()}"
Пример #32
0
 def _make_enc_filename(self, filename):
     cipher = ChaCha20.new(key=self.key)
     ciphertext = cipher.encrypt(os.path.basename(filename).encode("utf8"))
     nonce = b64encode(cipher.nonce).decode('utf-8')
     ct = b64encode(ciphertext).decode('utf-8')
     outFile = os.path.join(
         os.path.dirname(filename),
         f"{ENC_SIGNATURE}{(nonce + ct).replace('/', 'XXX')}")
     return outFile
Пример #33
0
def decrypt():
    encoded_shellcode = base64.b64decode(
        "F4KWN/2CwTuRIBALnZxp1uLp6ZqnJaLPqjb6dZFC3H+jPmiUYiA="
    )  # Encoded Execve-stack shellcode
    secret = b'G-KaPdSgVkYp3s6v9y$B&E)H@MbQeThW'
    msg_nonce = encoded_shellcode[:8]
    ciphertext = encoded_shellcode[8:]
    cipher = ChaCha20.new(key=secret, nonce=msg_nonce)
    return cipher.decrypt(ciphertext)
Пример #34
0
    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
Пример #35
0
 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)
Пример #36
0
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
Пример #37
0
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
Пример #38
0
    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
Пример #39
0
 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)
Пример #40
0
 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)
Пример #41
0
 def test_new_positive(self):
     cipher = ChaCha20.new(key=b("0")*32, nonce=b("0")*8)
     self.assertEqual(cipher.nonce, b("0") * 8)
Пример #42
0
 def setup(self):
     self.cipher = ChaCha20.new(key=self.key, nonce=self.iv)
Пример #43
0
 def setup(self):
     from Crypto.Cipher import ChaCha20
     self.cipher = ChaCha20.new(key=self.key, nonce=self.iv)
Пример #44
0
 def new(key, nonce):
     return ChaCha20.new(key=key, nonce=nonce)