class TestTripleDESModeCFB(object):
    test_KAT = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "3DES", "CFB"),
        [
            "TCFB64invperm.rsp",
            "TCFB64permop.rsp",
            "TCFB64subtab.rsp",
            "TCFB64varkey.rsp",
            "TCFB64vartext.rsp",
        ],
        lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
    )

    test_MMT = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "3DES", "CFB"),
        [
            "TCFB64MMT1.rsp",
            "TCFB64MMT2.rsp",
            "TCFB64MMT3.rsp",
        ],
        lambda key1, key2, key3, **kwargs: algorithms.TripleDES(
            binascii.unhexlify(key1 + key2 + key3)
        ),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
    )
Example #2
0
def _lock_secret_key(packet, new_pass, fast):
    if packet.s2k_id != 0:
        raise ValueError('Cannot lock an already locked key')

    new_packet = MutableSecretKeyPacket.copy(packet)
    s2k_offset = new_packet.get_s2k_offset()
    assert (packet.s2k_id == new_packet.data[s2k_offset])

    s2k_id = 254
    secret_data = new_packet.data[s2k_offset + 1:-2]
    secret_data += hashlib.sha1(secret_data).digest()

    enc_pass = new_pass.encode('utf-8')
    s2k_salt = get_random_bytes(8)
    assert (len(s2k_salt) == 8)
    s2k_type = 3  # Salted and Iterated
    s2k_hash = 2  # SHA1
    s2k_calg = 7  # AES-128
    s2k_iter = 1 if fast else 249
    aes128_iv = get_random_bytes(16)
    encryptor = Cipher(
        algorithms.AES(s2k(enc_pass, s2k_hash, s2k_calg, s2k_salt, s2k_iter)),
        modes.CFB(aes128_iv), default_backend()).encryptor()

    encrypted_data = bytearray(
        encryptor.update(bytes(secret_data)) + encryptor.finalize())

    new_packet.set_secret_key_data(
        s2k_id, (bytearray([s2k_calg, s2k_type, s2k_hash]) + s2k_salt +
                 bytearray([s2k_iter]) + aes128_iv + encrypted_data))

    return new_packet
 def encrypt(self, data):
     key = os.urandom(32)
     iv = os.urandom(16)
     cipher = Cipher(algorithms.AES(key), modes.CFB(iv))
     encryptor = cipher.encryptor()
     encrypted = encryptor.update(data) + encryptor.finalize()
     return encrypted, key, iv
Example #4
0
def encrypt(cipher, key, data):
    iv = len(key) * b"\x00"
    ci = cipher(key)
    ciph = Cipher(ci, modes.CFB(iv), backend=default_backend())
    encr = ciph.encryptor()
    encdata = encr.update(data) + encr.finalize()
    return encdata
Example #5
0
    def process(self, msg=b"", sharedKey=b""):

        # Número da mensagem.
        self.msg_cnt += 1

        print('Input your message.')
        textInput = input().encode()

        # Derivação da Shared Key para 32 bytes ou seja 256 bits (mais seguro).
        derivedKey = HKDF(
            algorithm=hashes.SHA256(),
            length=32,
            salt=b'\x8f\x84\x82\xb0\xfc\x19\xe4!\xd6\xf3"\xce\x87o\xe4}',
            info=b'handshake data',
            backend=default_backend()).derive(sharedKey)

        # Encriptar a mensagem para mandar ao Servidor.
        cipher = Cipher(algorithms.AES(derivedKey),
                        modes.CFB(iv),
                        backend=default_backend())
        encryptor = cipher.encryptor()

        encryptMessage = encryptor.update(textInput) + encryptor.finalize()

        return encryptMessage if len(encryptMessage) > 0 else None
Example #6
0
def triple_DES():
    block_size = 16  #fixed block size of 16 bytes
    #padding
    pad = lambda s: s + (block_size - len(s) % block_size) * chr(
        block_size - len(s) % block_size)
    unpad = lambda s: s[:-ord(s[len(s) - 1:])]  #unpad after decryption
    plain_text = str(input("Enter the plaintext to be encrypted: \n"))
    plain_text = pad((plain_text))  #padding the text
    #bytes conversion as input to encryption process must be binary data
    plain_text2 = bytes(plain_text, 'utf-8')
    backend = default_backend(
    )  #backend interfaces support symmetric encryption
    key = os.urandom(24)  #24 bytes key
    iv = os.urandom(
        8)  #TDES vector initializtion length=8 used along with secret key
    #utilizing Cipher Feedback(CFB)
    cipher = Cipher(algorithms.TripleDES(key), modes.CFB(iv), backend=backend)
    encryptor = cipher.encryptor()
    ct = encryptor.update(plain_text2) + encryptor.finalize()
    decryptor = cipher.decryptor()
    decrypt = decryptor.update(ct) + decryptor.finalize()
    decrypt = unpad(decrypt)  #unpad the text after decryption
    print("Key: \n" + str(key))  #drived key
    print("Text after Encryption: \n" + str(ct))  #encrypted text
    print("Text after Decryption \n" + str(decrypt))  #decrypted text
    print("Do you want to proceed with encryption?")
    user_input = input("Enter your choice as 'Yes' or 'No': ")
    if user_input == "Yes":
        symencryption()
    elif user_input == "No":
        exit()
Example #7
0
def decrypt(key, iv, byte_data):
    cipher = Cipher(algorithms.AES(key),
                    modes.CFB(iv),
                    backend=default_backend())
    decryptor = cipher.decryptor()

    return decryptor.update(byte_data) + decryptor.finalize()
Example #8
0
def _decrypt(cipher: Type[AES], key: bytes, data: bytes) -> bytes:
    iv = len(key) * b"\x00"
    ci = cipher(key)
    ciph = Cipher(ci, modes.CFB(iv), backend=default_backend())
    decr = ciph.decryptor()
    plaintextdata = decr.update(data) + decr.finalize()
    return plaintextdata
Example #9
0
def get_cipher(key, method, op, iv):
    if method == 'bypass':
        return bypass()
    if method in ('salsa20', 'chacha20', 'chacha20-ietf'):
        return Salsa20Crypto(method, key, iv, op)
    elif method == 'rc4-md5':
        md5 = hashlib.md5()
        md5.update(key)
        md5.update(iv)
        key = md5.digest()
        method = 'rc4'
    cipher = None

    if method.startswith('rc4'):
        pass
    elif method.endswith('ctr'):
        mode = modes.CTR(iv)
    elif method.endswith('ofb'):
        mode = modes.OFB(iv)
    elif method.endswith('cfb'):
        mode = modes.CFB(iv)
    else:
        raise ValueError('operation mode "%s" not supported!' % method.upper())

    if method.startswith('rc4'):
        cipher = Cipher(algorithms.ARC4(key), None, default_backend())
    elif method.startswith('aes'):
        cipher = Cipher(algorithms.AES(key), mode, default_backend())
    elif method.startswith('camellia'):
        cipher = Cipher(algorithms.Camellia(key), mode, default_backend())
    else:
        raise ValueError('crypto algorithm "%s" not supported!' %
                         method.upper())

    return cipher.encryptor() if op else cipher.decryptor()
Example #10
0
 def test_cfb(self, backend):
     with pytest.raises(ValueError):
         Cipher(
             algorithms.AES(b"\x00" * 16),
             modes.CFB(b"abc"),
             backend,
         )
Example #11
0
def _encrypt(cipher: Type[AES], key: bytes, data: bytes) -> bytes:
    iv = len(key) * b"\x00"
    ci = cipher(key)
    ciph = Cipher(ci, modes.CFB(iv), backend=default_backend())
    encr = ciph.encryptor()
    encdata = encr.update(data) + encr.finalize()
    return encdata
def _o2proxy_encrypted_session(
    secret: bytes, user: Optional[str], email: str, expires: datetime, token: str
) -> bytes:
    """
    Take in the data for an encrypting an oauth2_proxy session and
    return the encrypted session and handle.
    :param user: username, if any
    :param email: email, if any
    :param expires: expiration of the token
    :param token: The encoded JWT.
    :return: encrypted session bytes
    """
    email = email or ""
    session_obj = dict(
        IDToken=_o2proxy_encrypt_field(token).decode(),
        Email=_o2proxy_encrypt_field(email).decode(),
        User=_o2proxy_encrypt_field(email).decode(),
        CreatedAt=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
        ExpiresOn=expires.strftime("%Y-%m-%dT%H:%M:%SZ"),
    )
    session_payload_str = json.dumps(session_obj)
    backend = default_backend()
    cipher = Cipher(algorithms.AES(secret), modes.CFB(secret), backend=backend)
    encryptor = cipher.encryptor()
    cipher_text = encryptor.update(session_payload_str.encode()) + encryptor.finalize()
    return cipher_text
def create_cipher(mode_selection, key, iv):
    if mode_selection == "1":
        cipher = Cipher(
            algorithm=algorithms.AES(key),
            mode=modes.CBC(iv),
            backend=backend)
    elif mode_selection == "2":
        cipher = Cipher(
            algorithm=algorithms.AES(key),
            mode=modes.ECB(),
            backend=backend)
    elif mode_selection == "3":
        cipher = Cipher(
            algorithm=algorithms.AES(key),
            mode=modes.CTR(iv),
            backend=backend)
    elif mode_selection == "4":
        cipher = Cipher(
            algorithm=algorithms.AES(key),
            mode=modes.OFB(iv),
            backend=backend)
    elif mode_selection == "5":
        cipher = Cipher(
            algorithm=algorithms.AES(key),
            mode=modes.CFB(iv),
            backend=backend)
    return cipher
Example #14
0
def decode_with_ssh_key(key_path: str, encoded_string: str) -> str:
    """ decrypts a plain string using some data from key file

    :param key_path: path to key file
    :param encoded_string: text that has to be decrypted
    :return: decrypted text
    """
    key, iv = get_key_and_iv(key_path)
    encrypted_bytes = base64.b64decode(encoded_string)
    try:
        from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
        from cryptography.hazmat.backends import default_backend
        backend = default_backend()
        cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=backend)
        decryptor = cipher.decryptor()
        decrypted_bytes = decryptor.update(
            encrypted_bytes) + decryptor.finalize()
    except ModuleNotFoundError:
        import Crypto.PublicKey.RSA  # used for generating ssh key
        import Crypto.Cipher.AES

        cipher = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CFB, iv)
        decrypted_bytes = cipher.decrypt(encrypted_bytes)

    return decrypted_bytes.decode()
Example #15
0
def client(port):
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.connect('tcp://127.0.0.1:{}'.format(port))
    socket.setsockopt(zmq.SUBSCRIBE, b'\x00\x00\x00\x00')

    running = True

    def stopReading(signal, frame): 
        nonlocal running
        running = False
    signal.signal(signal.SIGINT, stopReading)

    key = b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
    backend = default_backend()

    while running:
        try:
            topicID, iv, cipher = socket.recv_multipart(zmq.NOBLOCK)
        except zmq.ZMQError:
            time.sleep(0.1)
        else:
            aes = Cipher(algorithms.AES(key), modes.CFB(iv), backend=backend)
            decryptor = aes.decryptor()
            msg = decryptor.update(cipher) + decryptor.finalize()

            planets = Planets.GetRootAsPlanets(msg, 0)
            for i in range(planets.PlanetsLength()):
                p = planets.Planets(i)
                x, y, z = p.X(), p.Y(), p.Z()
                print('Planet(x={:f}, y={:f}, z={:f})'.format(x, y, z))
            print('')

    socket.close()
Example #16
0
    def __init__(self,
                 algorithm=None,
                 cipher_mode=None,
                 initialization_vector=None,
                 **kwargs):
        """Initializes a decrypter.

    Args:
      algorithm (Optional[Cryptography.CipherAlgorithm]): cipher algorithm.
      cipher_mode (Optional[str]): cipher mode.
      initialization_vector (Optional[bytes]): initialization vector.
      kwargs (dict): keyword arguments depending on the decrypter.

    Raises:
      ValueError: if the initialization_vector is required and not set.
    """
        if (cipher_mode != definitions.ENCRYPTION_MODE_ECB
                and not initialization_vector):
            raise ValueError('Missing initialization vector.')

        if cipher_mode == definitions.ENCRYPTION_MODE_CBC:
            mode = modes.CBC(initialization_vector)
        elif cipher_mode == definitions.ENCRYPTION_MODE_CFB:
            mode = modes.CFB(initialization_vector)
        elif cipher_mode == definitions.ENCRYPTION_MODE_ECB:
            mode = modes.ECB()
        elif cipher_mode == definitions.ENCRYPTION_MODE_OFB:
            mode = modes.OFB(initialization_vector)

        backend = backends.default_backend()
        cipher = ciphers.Cipher(algorithm, mode=mode, backend=backend)

        super(CryptographyBlockCipherDecrypter, self).__init__()
        self._algorithm = algorithm
        self._cipher_context = cipher.decryptor()
Example #17
0
class TestIDEAModeCFB:
    test_cfb = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "IDEA"),
        ["idea-cfb.txt"],
        lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
    )
Example #18
0
class TestBlowfishModeCFB:
    test_cfb = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "Blowfish"),
        ["bf-cfb.txt"],
        lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
    )
Example #19
0
class TestSEEDModeCFB(object):
    test_CFB = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "SEED"),
        ["seed-cfb.txt"],
        lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv))
    )
Example #20
0
def get_aes_mode(mode, iv):
    cipher_modes = {
        'CFB': modes.CFB(iv),
        'CTR': modes.CTR(iv)
    }

    assert mode in cipher_modes.keys()
    return cipher_modes[mode]
Example #21
0
class TestCAST5ModeCFB(object):
    test_cfb = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "CAST5"),
        ["cast5-cfb.txt"],
        lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify((key))),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
    )
Example #22
0
class TestSM4ModeCFB(object):
    test_cfb = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "SM4"),
        ["draft-ribose-cfrg-sm4-10-cfb.txt"],
        lambda key, **kwargs: algorithms.SM4(binascii.unhexlify((key))),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
    )
Example #23
0
class TestCamelliaModeCFB(object):
    test_CFB = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "Camellia"),
        ["camellia-cfb.txt"],
        lambda key, **kwargs: algorithms.Camellia(binascii.unhexlify(key)),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
    )
Example #24
0
 def decrypt(self, data):
     if self._first_package is True or self._transport_protocol == protocol.TRANSPORT_UDP:
         self._first_package = False
         self._iv, data = data[:self._iv_len], data[self._iv_len:]
         self._decryptor = Cipher(algorithms.AES(self._key),
                                  modes.CFB(self._iv),
                                  backend=default_backend()).decryptor()
     return self._decrypt_impl(data, self._key, self._iv)
Example #25
0
    def __init__(self, f_original: io.RawIOBase,
                 get_key_pair: typing.Callable[[str], KeyPair]):
        """
        initializer, NOTE: this starts reading the stream of f_original
        to extract header information if present!!
        :param f_original: the wrapped FLO
        :param get_key_pair: a function, called for each key_subject from the header until one does
         not throw a KeyError.
        """
        super().__init__()

        # setting wrapped stream to read from
        self._f_original = f_original

        # reading json header contained in encrypted file
        json_header = read_header(self._f_original)

        # reading iv from header
        initialization_vector = base64.b64decode(json_header['iv'])

        # try to get a key for one of the subject in the file-header
        for private_key_subject in json_header['keys'].keys():
            try:
                private_pem = get_key_pair(private_key_subject)
                # reading (wrapped) key information and extracting relevant one
                encrypted_file_key_string = json_header['keys'].get(
                    private_key_subject)
                break
            except KeyError:
                # This is part of the process finding a key, get_key_private will be called for all
                # key subjects read from the header until it returns a valid KeyPair
                pass
        else:
            # (else is executed if break was not hit in loop)
            # if own subject not in key info -> error as we cannot decrypt
            raise NoKeyError('No decryption key present')

        # store the set of available subject ids from the header
        self.subject_ids = set(json_header['keys'].keys())

        # decoding wrapped file key (symmetric)
        encrypted_file_key = base64.b64decode(encrypted_file_key_string)

        # getting private key (PEM)
        private_key = serialization.load_pem_private_key(
            private_pem, None, backend=default_backend())

        # initializing file key (AES) by unwrapping wrapped key info with private key
        self._file_key = decrypt_with_private_key(
            private_key=private_key, ciphertext=encrypted_file_key)

        # initializing cipher to decrypt using file key
        self._cypher = Cipher(
            algorithms.AES(self._file_key),
            modes.CFB(initialization_vector=initialization_vector),
            backend=default_backend())
        self._decryptor = self._cypher.decryptor()
Example #26
0
    def __init__(self, f_original, public_keys, file_key=None):
        """
        initializer

        :param f_original: the original FLO to wrap and get plaintext from
        :param public_keys: list of tuples representing public key information
        in the format of (subject, public key), where subject is the email_address
        of the recipient and public key is a string containing the RSA public key
        in PEM format
        :param file_key: the symmetric key used for encryption (AES256). If not
        passed, it will be generated randomly
        (os.urandom)
        """
        super().__init__()

        # we never encrypt a file without public keys ;)
        assert len(public_keys)

        # setting symmetric key used for file encryption
        if not file_key:
            # creating random file key if not passed
            self._file_key = os.urandom(AES_KEY_LENGTH)
        else:
            # setting file key if passed (assuming right size)
            self._file_key = file_key

        # creating random IV
        initialization_vector = os.urandom(AES_IV_LENGTH)

        # creating cipher to perform encryption using given IV
        self._cypher = Cipher(
            algorithms.AES(self._file_key),
            modes.CFB(initialization_vector=initialization_vector),
            backend=default_backend())
        self._encryptor = self._cypher.encryptor()
        self._f_original = f_original

        # wrapping encryption key (symmetric) with all public keys of intended recipients
        keys = {}
        for subject, public_key_str in public_keys.items():
            public_key = serialization.load_pem_public_key(
                public_key_str, default_backend())
            # wrapping symmetric key with public key of user
            encrypted_file_key = encrypt_with_public_key(
                public_key=public_key, plaintext=self._file_key)

            # storing wrapped file key
            keys[subject] = encrypted_file_key

        # creating header information and adding to output buffer
        self._buffer = \
            b''.join(create_header(
                initialization_vector=initialization_vector, keys=keys))

        # determining header size
        self.header_size = len(self._buffer)
Example #27
0
def write(text, key):
    cipher = Cipher(algorithms.AES(base64.urlsafe_b64decode(key)),
                    modes.CFB(iv),
                    backend=backend)
    encryptor = cipher.encryptor()
    while len(text) // 16 != len(text) / 16:
        text += b' '
    ct = encryptor.update(bytes(text)) + encryptor.finalize()
    out = base64.urlsafe_b64encode(iv + ct)
    return out
Example #28
0
 def encrypt(self, data):
     if self._first_package is True or self._transport_protocol == protocol.TRANSPORT_UDP:
         self._first_package = False
         self._iv = os.urandom(self._iv_len)
         self._encryptor = Cipher(algorithms.AES(self._key),
                                  modes.CFB(self._iv),
                                  backend=default_backend()).encryptor()
         return self._iv + self._encrypt_impl(data, self._key, self._iv)
     else:
         return self._encrypt_impl(data, self._key, self._iv)
Example #29
0
def generate_aes_cfb(key, nonce_or_iv):
    backend = default_backend()
    iv = nonce_or_iv
    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=backend)

    def do_computation(msg: bytes):
        encryptor = cipher.encryptor()
        ct = encryptor.update(msg) + encryptor.finalize()

    return do_computation
Example #30
0
 def encrypt(self, buffer, is_encrypt):
     cipher = Cipher(algorithms.AES(self.connection_info.encrypted_key),
                     modes.CFB(self.connection_info.encrypted_iv),
                     backend=default_backend())
     if is_encrypt:
         encryptor = cipher.encryptor()
         return encryptor.update(buffer) + encryptor.finalize()
     else:
         decryptor = cipher.decryptor()
         return decryptor.update(buffer) + decryptor.finalize()