简体   繁体   中英

Python Cryptography AES-CTR in SSH

right now im trying to implement an SSH implementation (for educational reasons) and im trying to get the aes-ctr mode right. Im using scapy together with cryptography. I know my Plaintext is correct, because its working in the cbc mode and stays the same for ctr.

However when im encrypting and decrypting the first packet is right and can be handled by the server, but everything after that is false. Im pretty sure my mistake is somewhere at the iv (counter) range, but i cant get it. Do i need to increment the iv by myself? I tried it and it didnt work :(

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes


class _SSH_Streamcipher:
    def __init__(self, key, iv, algorithm, mode, block_length=None, key_length=None):
        self.algorithm = algorithm
        self.mode = mode
        self.block_length = block_length
        self.key_length = key_length
        self.key = key[:self.key_length]
        self.iv = iv[:self.block_length]
        self._cipher = Cipher(self.algorithm(self.key), self.mode(self.iv))

        # for stream ciphers and aes with ctr mode we need both of them the whole time
        self.decryptor = None
        self.encryptor = None

    def encrypt(self, data: bytes) -> bytes:
        if self.encryptor is None:
            self.encryptor = self._cipher.encryptor()
        ciphertext = self.encryptor.update(data)
        return ciphertext

    def decrypt(self, data: bytes) -> bytes:
        if self.decryptor is None:
            self.decryptor = self._cipher.decryptor()
        ciphertext = self.decryptor.update(data)
        return ciphertext

class SSH_Cipher_AES_256_CTR(_SSH_Streamcipher):
    def __init__(self, key, iv):
        super(SSH_Cipher_AES_256_CTR, self).__init__(key, iv,
                                                     algorithm=algorithms.AES,
                                                     mode=modes.CTR,
                                                     block_length=16, key_length=32)

question answered by myself after many hours. wrong implementation of the overall layout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM