예제 #1
0
 def set_passwd(self, sign, xchg, password: bytes):
     """
     Set or replace the password by encrypting the private keys and storing
     the results.
     :param sign: The signature key.
     :param xchg: The encryption key.
     :param password: The password for encrypting the keys.
     """
     # Verify key if key has been set
     if self.sign_priv:
         try:
             Ed25519PublicKey.from_public_bytes(self.sign).verify(
                 self.sign_sig, sign)
             Ed25519PublicKey.from_public_bytes(self.sign).verify(
                 self.xchg_sig, xchg)
         except cryptography.exceptions.InvalidSignature as e:
             raise SignatureMismatch(self.xchg_sig) from e
     # Do the actual encryption
     session = _gen_login_key(password, self.identity)
     self.sign_iv = urandom(16)
     context = Cipher(algorithms.ChaCha20(session, self.sign_iv), None,
                      default_backend()).encryptor()
     self.sign_priv = context.update(sign) + context.finalize()
     self.xchg_iv = urandom(16)
     context = Cipher(algorithms.ChaCha20(session, self.xchg_iv), None,
                      default_backend()).encryptor(
                      )  # Nonce reuse is considered bad practice
     self.xchg_priv = context.update(xchg) + context.finalize()
예제 #2
0
def get_stream(key: bytes, nonce: bytes) -> Iterator[int]:
	algorithm = algorithms.ChaCha20(key, nonce + b'\0' * 8)
	cipher = Cipher(algorithm, mode=None, backend=default_backend())
	encryptor = cipher.encryptor()

	while True:
		yield from encryptor.update(_EMPTY_BLOCK)
예제 #3
0
def read(args, action):
    # read the file
    with contextlib.closing(FileDecryptor(args.archive,
                                          None)) as fd:  # no decryptor yet
        # parse the header
        header = HEADER.parse(fd.read_aad(HEADER.sizeof()))

        # setup encryption
        kdf_params = header['kdf_params']
        kdf = Scrypt(salt=kdf_params['salt'],
                     length=32,
                     n=kdf_params['n'],
                     r=kdf_params['r'],
                     p=kdf_params['p'],
                     backend=BACKEND)
        key = kdf.derive(get_password().encode('utf-8'))
        logging.debug(f'[read()] key={key.hex()}')
        cipher_params = header['cipher_params']
        cipher = Cipher(algorithms.ChaCha20(key, cipher_params['nonce']),
                        modes.Poly1305(),
                        backend=BACKEND)
        fd.init(cipher.decryptor())

        # read the tag
        fd.read_tag()

        # read the archive
        tar = tarfile.open(fileobj=fd, mode='r|*')
        action(tar)
예제 #4
0
파일: encryption.py 프로젝트: hyunokoh/zeth
def encrypt(message: bytes, pk_receiver: EncryptionPublicKey) -> bytes:
    """
    Encrypts a string message under a ec25519 public key by using a custom
    dhaes-based scheme.  See: https://eprint.iacr.org/1999/007
    """
    assert \
        len(message) == NOTE_LENGTH_BYTES, \
        f"expected message length {NOTE_LENGTH_BYTES}, saw {len(message)}"

    # Generate ephemeral keypair
    eph_keypair = generate_encryption_keypair()

    # Compute shared secret and eph key
    shared_key = _exchange(eph_keypair.k_sk, pk_receiver)
    pk_sender_bytes = encode_encryption_public_key(eph_keypair.k_pk)

    # Generate key material
    sym_key, mac_key = _kdf(pk_sender_bytes, shared_key)

    # Generate symmetric ciphertext
    # Chacha encryption
    algorithm = algorithms.ChaCha20(sym_key, _SYM_NONCE_VALUE)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    encryptor = cipher.encryptor()
    sym_ciphertext = encryptor.update(message)

    # Generate mac
    mac = poly1305.Poly1305(mac_key)
    mac.update(sym_ciphertext)
    tag = mac.finalize()

    # Arrange ciphertext
    return pk_sender_bytes + sym_ciphertext + tag
예제 #5
0
    def decryption(self, data,iv=None,tag=None,nonce=None):
        backend = default_backend() 
        cipher = None
        block_size = 0

        if self.symmetric_cipher!='ChaCha20':
            if self.cipher_mode == 'ECB':
                mode = modes.ECB()
            elif self.cipher_mode == 'GCM':
                mode = modes.GCM(iv,tag)
            elif self.cipher_mode == 'CBC':
                if iv is not None:
                    mode = modes.CBC(iv)

        if self.symmetric_cipher == 'AES':
            block_size = algorithms.AES(self.symmetric_key).block_size
            cipher = Cipher(algorithms.AES(self.symmetric_key), mode, backend=backend)
        elif self.symmetric_cipher == '3DES':
            block_size = algorithms.TripleDES(self.symmetric_key).block_size
            cipher = Cipher(algorithms.TripleDES(self.symmetric_key), mode, backend=backend)
        elif self.symmetric_cipher == 'ChaCha20':
            algorithm = algorithms.ChaCha20(self.symmetric_key, nonce)
            cipher = Cipher(algorithm, mode=None, backend=default_backend())
        else:
            raise Exception("Mode not found")
            
        decryptor = cipher.decryptor()

        ct = decryptor.update(data)+decryptor.finalize()
        
        if self.cipher_mode=='GCM' or self.symmetric_cipher=='ChaCha20':
            return ct
        return ct[:-ct[-1]]
def decrypt_ChaCha20(key, nonce, data_encrypted):
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None)
    decryptor = cipher.decryptor()
    info = decryptor.update(data_encrypted)

    return info
 def decryption_file(self, block, nonce, key):
     cipher = Cipher(algorithms.ChaCha20(key, nonce),
                     mode=None,
                     backend=default_backend())
     decryptor = cipher.decryptor()
     data = decryptor.update(block) + decryptor.finalize()
     return data
예제 #8
0
def sym_decrypt_ChaCha(key, data):
    nonce = b'1111111111111111'
    algo = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algo, mode=None, backend=default_backend())
    decryptor = cipher.decryptor()
    pt = decryptor.update(data)
    return pt
예제 #9
0
    def encrypt_message(self, text, key):
        """Encrypts message with a symmetric key"""
        iv = os.urandom(16)
        cipher = None
        algorithm, iv = None, None
        mode = None

        enc_shared_key = key[len(key) // 2:]

        if self.cipher == 'AES':
            algorithm = algorithms.AES(enc_shared_key)
        elif self.cipher == '3DES':
            algorithm = algorithms.TripleDES(enc_shared_key)
        else:
            iv = os.urandom(16)
            algorithm = algorithms.ChaCha20(enc_shared_key, iv)
            logger.error('Algorithm not suported')

        if self.cipher != 'ChaCha20':
            # with ChaCha20 we do not pad the data
            iv = os.urandom(algorithm.block_size // 8)
            if self.ciphermode == 'CBC':
                mode = modes.CBC(iv)
            elif self.ciphermode == 'CTR':
                mode = modes.CTR(iv)
            padder = padding.PKCS7(algorithm.block_size).padder()
            padded_data = padder.update(text)
            padded_data += padder.finalize()
            text = padded_data
        cipher = Cipher(algorithm, mode=mode)
        encryptor = cipher.encryptor()
        cryptogram = encryptor.update(text) + encryptor.finalize()

        return cryptogram, iv
예제 #10
0
def encryptWithDH(data, key):
    nonce = os.urandom(16)
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    encryptor = cipher.encryptor()
    ct = encryptor.update(data)
    return ct, nonce
예제 #11
0
    def encrypt(self) -> None:
        to_encrypt = open(self.file_name, 'rb').read()

        if "CHACHA20" in self.cipher:
            self.iv = os.urandom(16)
            algorithm = algorithms.ChaCha20(self.key, self.iv)
            c = Cipher(algorithm, mode=None, backend=default_backend())
            text = self.chacha_encrypt(to_encrypt, c)

        elif "AES" in self.cipher and self.mode == 'GCM':
            self.iv = os.urandom(12)
            c = Cipher(algorithms.AES(self.key),
                       modes.GCM(self.iv),
                       backend=default_backend())
            text = self.aes_encrypt(to_encrypt, c)

        elif "AES" in self.cipher and self.mode == 'CBC':
            self.iv = os.urandom(16)
            c = Cipher(algorithms.AES(self.key),
                       modes.CBC(self.iv),
                       backend=default_backend())
            text = self.aes_encrypt(to_encrypt, c)

        mac = self.generate_mac(text)
        message = {
            'type': 'IV & MAC',
            'data': base64.b64encode(self.iv + mac).decode()
        }
        self._send(message)
예제 #12
0
 def __getPolyKey(self, key):
     cipher = Cipher(algo.ChaCha20(key, self._nonceCounter), None, defb())
     cipher = cipher.encryptor()
     key = cipher.update(
         b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
     )
     return key
예제 #13
0
    def decrypt_message(self, cryptogram, iv, key):
        """Decrypts messages with a symmetric key"""

        cipher = None
        algorithm = None
        mode = None
        enc_shared_key = key[len(key) // 2:]
        if self.cipher == 'AES':
            algorithm = algorithms.AES(enc_shared_key)
        elif self.cipher == '3DES':
            algorithm = algorithms.TripleDES(enc_shared_key)
        elif self.cipher == 'ChaCha20':
            # in this case the nonce is the iv
            if iv != None:
                algorithm = algorithms.ChaCha20(enc_shared_key, iv)
        else:
            logger.debug('Algorithm not suported')

        # with ChaCha20 we do not pad the data
        if self.ciphermode == 'CBC':
            mode = modes.CBC(iv)
        elif self.ciphermode == 'CTR':
            mode = modes.CTR(iv)

        cipher = Cipher(algorithm, mode=mode)
        decryptor = cipher.decryptor()
        if self.cipher == 'ChaCha20':
            return decryptor.update(cryptogram) + decryptor.finalize()
        else:
            padded_data = decryptor.update(cryptogram) + decryptor.finalize()
            unpadder = padding.PKCS7(algorithm.block_size).unpadder()
            text = unpadder.update(padded_data)
            text += unpadder.finalize()
            return text
예제 #14
0
def derive_poly1305_key(ckey: bytes, nonce: bytes) -> bytes:
    """Generate a poly1305 key.

    Args:
        ckey (bytes): The key used for the cipher
        nonce (bytes): The nonce used for the cipher. It must be 12 bytes.

    Returns:
        bytes: A Poly1305 key.

    Raises:
        ValueError: If the length of nonce is not equal to 8 or 12 bytes.
    """
    if len(nonce) not in (8, 12):
        raise ValueError("Poly1305 key must be 16 bytes long.")

    if len(nonce) == 8:
        nonce = bytes(4) + nonce

    crp = Cipher(
        algo.ChaCha20(ckey,
                      bytes(4) + nonce),
        None,
        defb(),
    ).encryptor()
    return crp.update(bytes(32))
예제 #15
0
 def reset(self):
     cipher = Cipher(
         algorithms.ChaCha20(self._key, self._nonce),
         mode=None,
         backend=default_backend(),
     )
     self._encryptor = cipher.encryptor()
     self._decryptor = cipher.decryptor()
예제 #16
0
    def chacha20Encrypt(self, text, key, nonce):
        algorithm = algorithms.ChaCha20(key, nonce)

        cipher = Cipher(algorithm, mode=None, backend=default_backend())

        encryptor = cipher.encryptor()
        encryptedText = encryptor.update(text)
        return encryptedText
예제 #17
0
def decrypt(text, key, nonce):
    algorithm = algorithms.ChaCha20(key, nonce)

    cipher = Cipher(algorithm, mode=None, backend=default_backend())

    decryptor = cipher.decryptor()
    decryptedText = decryptor.update(text)
    return decryptedText
예제 #18
0
def sym_encrypt_ChaCha(key, data):
    nonce = b'1111111111111111'
    data = bytes(data, "utf-8")
    algo = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algo, mode=None, backend=default_backend())
    encryptor = cipher.encryptor()
    ct = encryptor.update(data)
    return ct
def encrypt_ChaCha20(key, info):
    nonce = os.urandom(16)

    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None)
    encryptor = cipher.encryptor()
    data_encrypted = encryptor.update(info)
    return data_encrypted, nonce
예제 #20
0
def cryptography_chacha20(keysize=32, data_size=1024):
    plaintext = get_random_bytes(data_size * 1024)
    key = get_random_bytes(keysize)
    nonce = get_random_bytes(16)
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    encryptor = cipher.encryptor()
    _ = encryptor.update(plaintext)
예제 #21
0
 def enc(d, e):  #d=k e=mensagem
     nonce = b"0" * 16  #os.urandom(16)
     algorithm = algorithms.ChaCha20(d, nonce)
     cipher = Cipher(algorithm, mode=None, backend=default_backend())
     encryptor = cipher.encryptor()
     data = e.encode()  #Mensagem é string. Passamos para byte
     ct = encryptor.update(data)  #este é o criptograma
     return ct
예제 #22
0
def text_decryptor(main_key, secret_text, nonce):
    text_hash = generate_hash(main_key)
    # print(text_hash)
    algorithm = algorithms.ChaCha20(text_hash.encode(), nonce)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    decryptor = cipher.decryptor()

    return decryptor.update(secret_text)
예제 #23
0
 def Enc(self, key, plaintext):
     algoritmo = algorithms.ChaCha20(key[0:32], os.urandom(16))
     chacha20 = Cipher(algoritmo, mode=None, backend=self.backend)
     c = chacha20.encryptor()
     c1 = c.update(plaintext)
     h = hmac.HMAC(key[32:64], hashes.SHA256(), backend=default_backend())
     h.update(plaintext)
     c2 = h.finalize()
     return (c2 + c1)
예제 #24
0
 def test_vectors(self, vector, backend):
     key = binascii.unhexlify(vector["key"])
     nonce = binascii.unhexlify(vector["nonce"])
     ibc = struct.pack("<i", int(vector["initial_block_counter"]))
     pt = binascii.unhexlify(vector["plaintext"])
     encryptor = Cipher(algorithms.ChaCha20(key, ibc + nonce), None,
                        backend).encryptor()
     computed_ct = encryptor.update(pt) + encryptor.finalize()
     assert binascii.hexlify(computed_ct) == vector["ciphertext"]
예제 #25
0
 def test_buffer_protocol(self, backend):
     key = bytearray(os.urandom(32))
     nonce = bytearray(os.urandom(16))
     cipher = Cipher(algorithms.ChaCha20(key, nonce), None, backend)
     enc = cipher.encryptor()
     ct = enc.update(bytearray(b"hello")) + enc.finalize()
     dec = cipher.decryptor()
     pt = dec.update(ct) + dec.finalize()
     assert pt == b"hello"
예제 #26
0
    def __init__(self, human2alien, key, nonce):
        self.m2e_dic = human2alien
        self.e2m_dic = {}

        for m in self.m2e_dic.keys():
            self.e2m_dic[self.m2e_dic[m]] = m

        algorithm = algorithms.ChaCha20(key, nonce)
        self.cipher = Cipher(algorithm, mode=None, backend=default_backend())
예제 #27
0
def dechachacry(data, salt, nonce):
    keyraw = salt + bytes(getpass(), "UTF-8")
    key = hashes.Hash(hashes.BLAKE2s(32), backend=default_backend())
    key.update(keyraw)
    key = key.finalize()
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    decrypt = cipher.decryptor()
    return decrypt.update(data)
예제 #28
0
    def file_encryption(self, data):
        backend = default_backend()
        cipher = None
        block_size = 0
        mode = None

        if self.symmetric_cipher != 'ChaCha20':
            if self.cipher_mode == 'ECB':
                mode = modes.ECB()
            elif self.cipher_mode == 'GCM':
                self.iv = os.urandom(16)
                mode = modes.GCM(self.iv)
            elif self.cipher_mode == 'CBC':
                if self.symmetric_cipher == '3DES':
                    self.iv = os.urandom(8)
                elif self.symmetric_cipher == 'AES':
                    self.iv = os.urandom(16)
                mode = modes.CBC(self.iv)

        if self.symmetric_cipher == 'AES':
            block_size = algorithms.AES(self.symmetric_key).block_size
            cipher = Cipher(algorithms.AES(self.symmetric_key),
                            mode,
                            backend=backend)

        elif self.symmetric_cipher == '3DES':
            block_size = algorithms.TripleDES(self.symmetric_key).block_size
            cipher = Cipher(algorithms.TripleDES(self.symmetric_key),
                            mode,
                            backend=backend)

        elif self.symmetric_cipher == 'ChaCha20':
            nonce = os.urandom(16)
            algorithm = algorithms.ChaCha20(self.symmetric_key, nonce)
            cipher = Cipher(algorithm, mode=None, backend=default_backend())
        else:
            raise Exception("Symmetric cipher not found")

        encryptor = cipher.encryptor()

        if self.cipher_mode != 'GCM' and self.symmetric_cipher != 'ChaCha20':
            padding = block_size - len(data) % block_size

            padding = 16 if padding and self.symmetric_cipher == 'AES' == 0 else padding
            padding = 8 if padding and self.symmetric_cipher == '3DES' == 0 else padding

            data += bytes([padding] * padding)
            criptogram = encryptor.update(data)
        elif self.symmetric_cipher == 'ChaCha20':

            criptogram = encryptor.update(data)
            self.nonce = nonce
        else:
            criptogram = encryptor.update(data) + encryptor.finalize()
            self.gcm_tag = encryptor.tag

        return criptogram
 def init_chacha20(self, random_seed=None):
     if random_seed:
         self.__random_seed = random_seed
     else:
         self.generate_random_seed()
     algorithm = algorithms.ChaCha20(self.__random_seed[0:32],
                                     self.__random_seed[32:])
     self.__cipher = Cipher(algorithm, mode=None, backend=default_backend())
     self.__encryptor = self.__cipher.encryptor()
     self.__decryptor = self.__cipher.decryptor()
예제 #30
0
def chacha20_encrypt(key, nonce, message):
    counter = bytes([1, 0, 0, 0])
    #Annoyingly, PyCA only accepts sixteen-byte nonces.
    #Internally, the first four bytes of the nonce are
    #treated as the 32-bit (little-endian) counter input to the block function;
    #concatenating them this way seems to work (per RFC 7539 test vectors)
    cha = algorithms.ChaCha20(key, counter + nonce)
    enc = Cipher(cha, mode=None, backend=default_backend()).encryptor()
    ct = enc.update(message)
    return ct