def test_non_bytes(self):
     padder = padding.ANSIX923(128).padder()
     with pytest.raises(TypeError):
         padder.update("abc")  # type: ignore[arg-type]
     unpadder = padding.ANSIX923(128).unpadder()
     with pytest.raises(TypeError):
         unpadder.update("abc")  # type: ignore[arg-type]
Beispiel #2
0
def main():
	parser = argparse.ArgumentParser()
	parser.add_argument('-out', help='Output encrypted file', dest='output', required=True)
	parser.add_argument('-in', help='File to be encrypted', dest='input', required=True)
	parser.add_argument('-k', help='The key to be used for encryption, must be in hex', dest='key')
	parser.add_argument('-iv', help='The initialization vector, must be in hex', dest='iv')
	parser.add_argument('-e','--encrypt', action='store_true')
	parser.add_argument('-d','--decrypt', action='store_true')
	args = parser.parse_args()
	input_content = readfile_binary(args.input)
	backend = default_backend()
	cipher = Cipher(algorithms.AES(binascii.unhexlify(args.key)), modes.CBC(binascii.unhexlify(args.iv)), backend=backend)
	if(args.decrypt):
		print('This is decrypt mode')
		decryptor = cipher.decryptor()
		plainText = decryptor.update(input_content) + decryptor.finalize()
		unpadder = padding.ANSIX923(128).unpadder()
		unpadded_data = unpadder.update(plainText)
		finalText = unpadded_data + unpadder.finalize()
		writefile_binary(args.output, finalText) 
	elif(args.encrypt):
		print('This is encrypt mode')
		encryptor = cipher.encryptor()
		padder = padding.ANSIX923(128).padder()
		padded_data = padder.update(readfile_binary(args.input))
		padded_data += padder.finalize()
		ct = encryptor.update(padded_data) + encryptor.finalize()
		writefile_binary(args.output, ct)
	else:
		print('Select -e or -d option')
Beispiel #3
0
 def test_non_bytes(self):
     padder = padding.ANSIX923(128).padder()
     with pytest.raises(TypeError):
         padder.update(u"abc")
     unpadder = padding.ANSIX923(128).unpadder()
     with pytest.raises(TypeError):
         unpadder.update(u"abc")
Beispiel #4
0
 def test_bytearray(self):
     padder = padding.ANSIX923(128).padder()
     unpadded = bytearray(b"t" * 38)
     padded = (padder.update(unpadded) + padder.update(unpadded) +
               padder.finalize())
     unpadder = padding.ANSIX923(128).unpadder()
     final = unpadder.update(padded) + unpadder.finalize()
     assert final == unpadded + unpadded
    def test_zany_py2_bytes_subclass(self):
        class mybytes(bytes):  # noqa: N801
            def __str__(self):
                return "broken"

        str(mybytes())
        padder = padding.ANSIX923(128).padder()
        padder.update(mybytes(b"abc"))
        unpadder = padding.ANSIX923(128).unpadder()
        unpadder.update(mybytes(padder.finalize()))
        assert unpadder.finalize() == b"abc"
Beispiel #6
0
    def test_use_after_finalize(self):
        padder = padding.ANSIX923(128).padder()
        b = padder.finalize()
        with pytest.raises(AlreadyFinalized):
            padder.update(b"")
        with pytest.raises(AlreadyFinalized):
            padder.finalize()

        unpadder = padding.ANSIX923(128).unpadder()
        unpadder.update(b)
        unpadder.finalize()
        with pytest.raises(AlreadyFinalized):
            unpadder.update(b"")
        with pytest.raises(AlreadyFinalized):
            unpadder.finalize()
Beispiel #7
0
    def decrypt(self, key, msg, b64decode=True):
        """Decrypts the provided ciphertext.

        The ciphertext can be optionally base64 encoded.

        Uses AES-128-CBC with an IV by default.

        :param key: The Encryption key.
        :param msg: the ciphetext, the first block is the IV

        :returns plain: the plaintext message, after padding is removed.
        """
        key = str.encode(get_valid_encryption_key(key))
        if b64decode:
            msg = base64.b64decode(msg)
        algo = self.algo(key)
        block_size_bytes = algo.block_size // 8
        iv = msg[:block_size_bytes]
        backend = backends.default_backend()
        cipher = Cipher(algo, modes.CBC(iv), backend=backend)
        decryptor = cipher.decryptor()
        padded = (decryptor.update(msg[block_size_bytes:]) +
                  decryptor.finalize())
        unpadder = padding.ANSIX923(algo.block_size).unpadder()
        plain = unpadder.update(padded) + unpadder.finalize()
        # The original padding algorithm was a slight variation on ANSI X.923,
        # where the size of the padding did not include the byte that tells
        # you the size of the padding. Therefore, we need to remove one extra
        # byte (which will be 0x00) when unpadding.
        return plain[:-1]
Beispiel #8
0
 def encrypt_text(self, message):
     # create encryptor object
     encryptor = self.cipher.encryptor()
     # create padding object, which adds some chars for text, which length is not multiple of block size (128)
     padder = padding.ANSIX923(algorithms.AES.block_size).padder()
     # adding padding to message
     message = padder.update(message) + padder.finalize()
     # return encrypted message
     return encryptor.update(message) + encryptor.finalize()
Beispiel #9
0
 def enc(bitstring):
     if algoname not in ['ARC4', 'ChaCha20']:
         if padd.upper() == 'PKCS7':
             padder = padding.PKCS7(algoer.block_size).padder()
             bitstring = padder.update(bitstring) + padder.finalize()
         elif padd.upper() == 'ANSIX923':
             padder = padding.ANSIX923(algoer.block_size).padder()
             bitstring = padder.update(bitstring) + padder.finalize()
     encryptor = cipher.encryptor()
     return encryptor.update(bitstring) + encryptor.finalize()
Beispiel #10
0
 def decrypt_text(self, encrypted_message):
     # create decryptor object
     decryptor = self.cipher.decryptor()
     # create unpadder object, which deletes padding
     unpadder = padding.ANSIX923(algorithms.AES.block_size).unpadder()
     # decrypt message
     encrypted_message = decryptor.update(
         encrypted_message) + decryptor.finalize()
     # remove padding
     return unpadder.update(encrypted_message) + unpadder.finalize()
Beispiel #11
0
def paswword_padding(passwd):
    passlen = len(passwd)
    passbyte = bytes(passwd, 'UTF-8')
    if passlen not in KEY_LENGTHS:
        if passlen < 16:
            padder = padding.ANSIX923(128).padder()
            pad_passwd = padder.update(passbyte)
            pad_passwd += padder.finalize()
        elif passlen < 24:
            padder = padding.ANSIX923(192).padder()
            pad_passwd = padder.update(passbyte)
            pad_passwd += padder.finalize()
        elif passlen < 32:
            padder = padding.ANSIX923(256).padder()
            pad_passwd = padder.update(passbyte)
            pad_passwd += padder.finalize()
        else:
            print('Password cant be larger than 32bytes')
    return pad_passwd
Beispiel #12
0
 def dec(bitstring):
     decryptor = cipher.decryptor()
     ddata = decryptor.update(bitstring) + decryptor.finalize()
     if algoname not in ['ARC4', 'ChaCha20']:
         if padd.upper() == 'PKCS7':
             unpadder = padding.PKCS7(algoer.block_size).unpadder()
             ddata = unpadder.update(ddata) + unpadder.finalize()
         elif padd.upper() == 'ANSIX923':
             unpadder = padding.ANSIX923(algoer.block_size).unpadder()
             ddata = unpadder.update(ddata) + unpadder.finalize()
     return ddata
Beispiel #13
0
def encryption_OFB(file_content, key, iv):
    cipher = Cipher(algorithms.TripleDES(key), modes.ECB(), default_backend())
    encrypted_data = []

    for block in file_content:
        encryptor = cipher.encryptor()

        # cazul in care ultimul bloc nu are dimensiunea de 16 bytes
        if len(block) != 16:
            padder = padding.ANSIX923(128).padder()
            block = padder.update(block) + padder.finalize()
        result = encryptor.update(iv) + encryptor.finalize()
        # criptotextul curent inainte de XOR-ul cu plaintextul
        # devine vector de initilizare pentru blocul urmator
        iv = result
        result = xor_between_arrays(block, result)
        encrypted_data.append(result)
    return encrypted_data
Beispiel #14
0
def decryption_CBC(cipher_text, key, iv):
    cipher = Cipher(algorithms.TripleDES(key), modes.ECB(), default_backend())

    decrypted_data = []

    for encrypted_block in cipher_text:
        encryptor = cipher.decryptor()
        copy_iv = iv
        iv = encrypted_block
        result = encryptor.update(encrypted_block) + encryptor.finalize()
        final = xor_between_arrays(copy_iv, result)
        decrypted_data.append(final)

    # incercam sa obtinem blocul initial, in cazul in care acesta nu a avut initial 16 bytes
    try:
        unpadder = padding.ANSIX923(128).unpadder()
        decrypted_data[-1] = unpadder.update(
            decrypted_data[-1]) + unpadder.finalize()
    except Exception as e:
        pass
    return decrypted_data
Beispiel #15
0
 def test_unpad(self, size, unpadded, padded):
     unpadder = padding.ANSIX923(size).unpadder()
     result = unpadder.update(padded)
     result += unpadder.finalize()
     assert result == unpadded
Beispiel #16
0
 def test_pad(self, size, unpadded, padded):
     padder = padding.ANSIX923(size).padder()
     result = padder.update(unpadded)
     result += padder.finalize()
     assert result == padded
Beispiel #17
0
 def test_invalid_padding(self, size, padded):
     unpadder = padding.ANSIX923(size).unpadder()
     with pytest.raises(ValueError):
         unpadder.update(padded)
         unpadder.finalize()
Beispiel #18
0
 def test_invalid_block_size(self, size):
     with pytest.raises(ValueError):
         padding.ANSIX923(size)
Beispiel #19
0
# -*- coding: utf-8 -*-

import cryptography
from codecs import encode, decode
from cryptography.hazmat.primitives import padding

secret = b'message secret'
a = encode(secret, 'hex')
#print(a)
# print(decode(a,'hex'))

padder = padding.ANSIX923(128).padder()
padded_data = padder.update(b"11111111111111112222222222")
# print(padded_data)
# print(padder.finalize())
'''def pkcs7(data,block_size):
    padding_size=(block_size-len(data))%block_size
    if padding_size==0:
       padding_size= block_size
    padding =(chr(padding_size)*padding_size).encode
    return data+ bytearray()
print (pkcs7('message secret',16))
'''


def read():
    f = open("C:\\Users\\Narutowin\\Downloads\\cipher.hex")
    return f


# Enzo's function