def DESe(k, messages):
    print("Generating DES Times")
    times = list()
    for msg in messages:
        t_start = time()
        key = str.encode(k[0:16])
        DES3.adjust_key_parity(key)
        cipher = DES3.new(key, DES3.MODE_EAX)
        cipher_text = cipher.nonce + cipher.encrypt(str.encode(msg))
        t_end = time()
        total_time = t_end - t_start
        times.append(total_time)
    return times
示例#2
0
    def __init__(self, CIPHER, MODE, key=None, iv=None, nonce=None):
        key = b64decode(key) if key else get_random_bytes(
            24)  # Generamos la llave aleatoria

        if CIPHER not in self.CIPHERS:
            return 1
        CIPHER = self.CIPHERS[CIPHER]  # Obtenemos el Cipher elejido

        if CIPHER == DES3:
            key = DES3.adjust_key_parity(key)  # Key Parity para 3DES

        if MODE not in self.MODES:
            return 1

        mode = self.MODES[MODE]  #Obtenemos el modo de operación
        if (CIPHER != AES) and (MODE == "CTR"):
            nonce = b64decode(nonce) if nonce else get_random_bytes(4)
            cipher = CIPHER.new(key, mode, nonce=nonce)
        elif MODE == "ECB":
            cipher = CIPHER.new(key, mode)
        elif MODE == "CTR":
            nonce = b64decode(nonce) if nonce else None
            cipher = CIPHER.new(key, mode, nonce=nonce)
        else:
            iv = b64decode(iv) if iv else None
            cipher = CIPHER.new(key, mode, iv=iv)
        self.cipher = cipher
        self.mode = MODE
        self.key = key
示例#3
0
 def test_parity_option3(self):
     before_3k = unhexlify(
         "AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCC")
     after_3k = DES3.adjust_key_parity(before_3k)
     self.assertEqual(
         after_3k,
         unhexlify("ABABABABABABABABBABABABABABABABACDCDCDCDCDCDCDCD"))
示例#4
0
def decryptDocument(e_type: bytes, e_key: bytes, iv: bytes, ciphertext: bytes):
    '''
		Decrypt document via 3DES or AES. 
		Returns: plaintext
	'''
    print("\ndecryptDocument()")

    print("Encryption Type: ", type(e_type))
    print("Encryption Type: ", e_type)
    encryption_type = str(e_type, "UTF-8")
    print("Encryption Type After String Conversion: ", encryption_type)

    if encryption_type == "AES128" or encryption_type == "AES256":
        print("\nAES DECRYPTION")
        cipher = AES.new(e_key, AES.MODE_CBC, iv)
        plaintext = cipher.decrypt(ciphertext)
        plaintext = unpad(plaintext, AES.block_size)

    if encryption_type == "3DES":
        print("\n3DES DECRYPTION")
        e_key = DES3.adjust_key_parity(e_key)
        cipher = DES3.new(e_key, DES3.MODE_CBC, iv)
        plaintext = cipher.decrypt(ciphertext)
        plaintext = unpad(plaintext, DES3.block_size)

    if DEBUG_DECRYPT_DOCUMENT:
        print("Plaintext Type:\n", plaintext)
        print("Plaintext:\n", plaintext)  # Print entire doc

    return plaintext
def compute_key(key_seed: bytes, key_type: str, alg: str) -> bytes:
    """Compute enc and mac keys from key_seed.

    key_seed -- 16 bytes
    key_type -- type of key to be created (choices "enc", "mac", "pace")
    alg -- which algorithm to create keys for (choices "3DES", "AES-128", "AES-192", "AES-256")
    :returns: 3DES or AES key
    """
    if key_type == "enc":
        c = b"\x00\x00\x00\x01"
    elif key_type == "mac":
        c = b"\x00\x00\x00\x02"
    elif key_type == "pace":
        c = b"\x00\x00\x00\x03"
    else:
        raise ValueError('key_type must either be "enc" or "mac"')
    D = key_seed + c

    if alg == "3DES":
        hash_of_D = hashlib.sha1(D).digest()
        key_a = hash_of_D[:8]
        key_b = hash_of_D[8:16]
        return DES3.adjust_key_parity(key_a + key_b)  # set parity bits
    if alg == "AES-128":
        return hashlib.sha1(D).digest()[:16]
    if alg == "AES-192":
        return hashlib.sha256(D).digest()[:24]
    if alg == "AES-256":
        return hashlib.sha256(D).digest()
    else:
        raise ValueError("[-] Unknown encryption algorithm!")
示例#6
0
文件: main.py 项目: ga6198/5270_2
def decrypt_3des_ecb(p_bytes):
    BLOCK_SIZE = 8  # bytes
    key = DES3.adjust_key_parity("abcdefghijklmnop".encode('utf8'))
    decipher = DES3.new(key, DES3.MODE_ECB)
    msg = decipher.decrypt(p_bytes)

    with open("des3_ecb_decrypt.txt", 'ab') as output_file:
        output_file.write(msg)
示例#7
0
    def DES(self, password: str) -> bytes:
        """Encrypt data according to DES3 algorithm."""
        # Generating the key according to password
        key = DES3.adjust_key_parity(get_key(password, 24))

        # Encrypting the data
        cipher_object = DES3.new(key, DES3.MODE_CBC)
        return (cipher_object.iv + cipher_object.encrypt(pad(self.data, 8)))
示例#8
0
文件: main.py 项目: ga6198/5270_2
def encrypt_3des_cbc(p_bytes):
    BLOCK_SIZE = 8  # bytes
    key = DES3.adjust_key_parity("abcdefghijklmnop".encode('utf8'))
    cipher = DES3.new(key, DES3.MODE_CBC, iv=des3_iv)

    msg = cipher.encrypt(pad(p_bytes, BLOCK_SIZE))

    with open("des3_cbc.txt", 'ab') as output_file:
        output_file.write(msg)
示例#9
0
def DES_decrypt(key, msg):
    key = str(key)
    if (len(key) < 15):
        key = key + '0' * (15 - len(key))
    key = key.encode()
    while (len(key) != 24):
        key += b"\0"
    key = DES3.adjust_key_parity(key)
    cipher = DES3.new(key, DES3.MODE_ECB)
    plaintext = cipher.decrypt(msg)
    return plaintext
示例#10
0
    def DES(self, password: str) -> bytes:
        """Decrypt data according to DES algorithm."""
        # Generating the key according to password
        key = DES3.adjust_key_parity(get_key(password, 24))

        # Splitting data into IV & Data
        iv = self.data[:8]
        data = self.data[8:]

        # Decrypting the data
        cipher_object = DES3.new(key, DES3.MODE_CBC, IV=iv)
        return unpad(cipher_object.decrypt(data), 8)
示例#11
0
def encrypt_3des(path):
    data = open_binary(path)
    while True:
        try:
            key = DES3.adjust_key_parity(get_random_bytes(24))
            break
        except ValueError:
            pass
    cipher = DES3.new(key, DES3.MODE_CFB)
    cipher_bytes = cipher.encrypt(data)
    iv = cipher.iv
    cipher_path = path.split(".")[0] + ".enc"
    write_binary(cipher_path, data=cipher_bytes)
    insert(cipher_path, "3DES", path.split(".")[1], key, iv)
示例#12
0
def DES_encrypt(key, plaintext, isFile):
    key = str(key)
    if (len(key) < 15):
        key = key + '0' * (15 - len(key))
    key = key.encode()
    #print("" + len(key))
    while (len(key) != 24):
        key += b"\0"
    key = DES3.adjust_key_parity(key)
    cipher = DES3.new(key, DES3.MODE_ECB)
    if isFile:
        msg = cipher.encrypt(pad(plaintext, BLOCK_SIZE))
        return msg
    else:
        msg = cipher.encrypt(pad(plaintext.encode(), BLOCK_SIZE))
        return msg
示例#13
0
    def encryptMsg(cls, msg_file):
        with open(msg_file, 'r') as secret_msg_file:
            secret_msg = secret_msg_file.read()

        while True:
            try:
                key = DES3.adjust_key_parity(get_random_bytes(24))
                break
            except ValueError:
                pass
                #('KEY SIZE ERROR AUDIO STEG')

        enc_msg = encryptTripleDES(secret_msg, key)
        cls.TDES_key = b64encode(key).decode('utf-8')

        with open('encrypted_msg_audio.txt', 'w') as enc_file:
            enc_file.write(enc_msg)
示例#14
0
def Encrypt(g_key, img_file):
    given_key = bytes(g_key, 'utf-8')
    while True:
        try:
            key = DES3.adjust_key_parity(given_key)
            break
        except ValueError:
            pass
    input_file = open(img_file, "rb")
    input_data = input_file.read()
    input_file.close()

    iv = b"abcdefgh"

    cipher = DES3.new(key, DES3.MODE_CFB, iv)
    enc_data = cipher.encrypt(input_data)
    return enc_data
示例#15
0
def Decrypt(g_key, img_file):
    given_key = bytes(g_key, 'utf-8')
    while True:
        try:
            key = DES3.adjust_key_parity(given_key)
            break
        except ValueError:
            pass
    enc_file = open(img_file, "rb")
    enc_data = enc_file.read()
    enc_file.close()

    iv = b"abcdefgh"

    decipher = DES3.new(key, DES3.MODE_CFB, iv)
    plain_text = decipher.decrypt(enc_data)
    return plain_text
示例#16
0
def process_DES3(text):
    des3 = None
    length = None
    while True:
        key = input("key(must be 16 or 24 bytes): ").encode('utf-8')
        length = len(key)
        try:
            key = DES3.adjust_key_parity(key)
            des3 = DES3.new(key, DES3.MODE_ECB)
            break
        except ValueError:
            pass
    target_text = text_padding(text, 8)
    encrypted = des3.encrypt(target_text)
    print("encrypted: " + str(encrypted))
    decrypted = des3.decrypt(encrypted)
    decrypted = decrypted.decode('utf-8')
    print("decrypted: " + decrypted)
示例#17
0
    def encrypter(cls, msg_file, msg_save_to):
        with open(msg_file, 'r') as txt:
            plain_txt = txt.read()

        while True:
            try:
                key = DES3.adjust_key_parity(get_random_bytes(24))
                if len(key) == 24:
                    break
            except ValueError:
                print('TDES KEY SIZE ERROR')

        cipher_txt_encoded = encryptTripleDES(plain_txt, key)
        key_encoded = b64encode(key).decode('utf-8')

        with open(msg_save_to, 'w') as enc_msg_file:
            enc_msg_file.write(cipher_txt_encoded)

        cls.key['TDES'] = key_encoded

        return msg_save_to
示例#18
0
文件: triple_des.py 项目: PRMTRG/BSI2
def encrypt(key_file, input_file, output_file):
    """
    Encrypt a file using DES3.
    
    :param key_file: path to the file containing key
    :param input_file: path to the message file which we want to encrypt
    :param output_file: path where the encrypted file shall be saved.
    :return: nothing
    """
    k = utils.read_file_b(key_file)
    message = utils.read_file_s(input_file)
    data = utils.message_to_data(message, DES3.block_size)
    while True:
        try:
            key = DES3.adjust_key_parity(k)
            break
        except ValueError:
            pass
    cipher = DES3.new(key, DES3.MODE_CFB)
    msg = cipher.iv + cipher.encrypt(data)
    utils.write_to_file_b(output_file, msg)
示例#19
0
def encryptDocument(encryption_type: str, encryption_key: bytes,
                    plaintext: bytes):
    '''
		Pad byte array to appropriate block size. Encrypt document in manner specified by config scheme w/ AES_CBC or3DES_CBC 

		Returns: initialization vector and ciphertext 
	'''

    print("\nencryptDocument()")

    if DEBUG_ENCRYPT_DOCUMENT_I:
        print("Encryption Type Type: ", type(encryption_type))
        print("Encryption Type: ", encryption_type)
        print("Encryption Key Type: ", type(encryption_key))
        print("Encryption Key Length: ", len(encryption_key))
        print("Encryption Key: ", encryption_key)
        print("Plaintext Type: ", type(plaintext))
        # print("Plaintext: ", plaintext) # print whole doc

    if encryption_type == "AES128" or encryption_type == "AES256":
        print("\nAES ENCRYPTION")
        cipher = AES.new(encryption_key, AES.MODE_CBC)
        ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
        iv = cipher.iv

    if encryption_type == "3DES":
        print("\n3DES ENCRYPTION")
        encryption_key = DES3.adjust_key_parity(encryption_key)
        cipher = DES3.new(encryption_key, DES3.MODE_CBC)
        ciphertext = cipher.encrypt(pad(plaintext, DES3.block_size))
        iv = cipher.iv

    if DEBUG_ENCRYPT_DOCUMENT_O:
        print("IV Type: ", type(iv))
        print("IV: ", iv, end='\n\n')

        print("Ciphertext Type: ", type(ciphertext))
        # print("Ciphertext:\n", ciphertext, end='\n\n') # Prints whole document

    return iv, ciphertext
示例#20
0
def contenidoHTML(texto_plano, llave):
    llave = bytes(llave, 'utf-8')  #la llave se codifica a bytes con utf-8

    while True:
        try:
            key = DES3.adjust_key_parity(llave)
            break
        except ValueError:
            pass

    cipher = DES3.new(
        key, DES3.MODE_ECB
    )  #define tipo de cifrado 3DES modo ECB con la llave entregada

    textoPad = pad(texto_plano)  #se añade el pad al string de textoplano
    text = bytes(
        textoPad,
        'utf-8')  # el textoplano con pad se codifica a bytes con utf-8

    msg_cifrado = cipher.encrypt(text)  #se encripta el texto

    return f"""
示例#21
0
def DES3Function(plain) :
    while True : 
        key = input("key(16 / 24) : ")
        if (len(key) == 16 and key[:7] != key[8:15]) or (len(key) == 24 and key[:7] != key[8:15] and key[8:15] != key[16:23]) :
            DES3key = DES3.adjust_key_parity(key.encode())
            cipher = DES3.new(DES3key, DES3.MODE_ECB)

            # make plaintext 8 bytes through padding because DES3 has a fixed data block size of 8 bytes
            # use underbar for padding char
            # DES3.block_size = 8
            plain = plain + ((DES3.block_size - (len(plain) % DES3.block_size)) * '_')
    
            cipherText = cipher.encrypt(plain.encode())
            print("encrypted : ", cipherText)

            dePlain = cipher.decrypt(cipherText)
            print("decrypted : ", dePlain.decode())
            return
        else :
            print("Please enter a key that is 16 or 24 in length.")
            print("If you enter a 16-digit key, the first eight parts and the last eight parts must be different. ")
            print("If you enter a 24-digit key, the eight parts in the middle mush be different form the first eight and the last eight")
示例#22
0
        return True, end - start
    except:
        print("Error at CFB Decryption...")
        exit(1)


if __name__ == '__main__':
    # Generation of our pseudorandom key base64
    print("================ KEY GENERATION ================\n")
    # Store it into a file
    key_file = open('Keys/3des_key.txt', "w", encoding='utf8')
    # Avoid Option 3
    while True:
        try:
            generated_key = DES3.adjust_key_parity(
                Random.get_random_bytes(KEY_112))
            break
        except ValueError:
            pass

    # Encoding key in base64 and dumping it into a json format
    key64 = base64.b64encode(generated_key).decode('utf-8')
    json_key = json.dumps({'key': key64})
    # Write to file
    key_file.write(json_key)
    # Close file
    key_file.close()

    print(
        "================ INITIALIZATION VECTOR GENERATION ================\n")
    # Store it into a file
示例#23
0
 def test_parity_option2(self):
     before_2k = unhexlify("CABF326FA56734324FFCCABCDEFACABF")
     after_2k = DES3.adjust_key_parity(before_2k)
     self.assertEqual(after_2k,
                      unhexlify("CBBF326EA46734324FFDCBBCDFFBCBBF"))
    def post(self):
        args = des3_encrypt_parser.parse_args()
        key_1 = args["key_1"]
        key_2 = args["key_2"]
        key_3 = args["key_3"]
        mode = args["mode"].upper()
        iv = args["iv"]
        message = args["message"]

        try:
            key = DES3.adjust_key_parity(
                str.encode(key_1) + str.encode(key_2) + str.encode(key_3)
            )
        except Exception as e:
            print(e)
            abort(
                400,
                "Invalid key format, each key must be of length 8. The three keys must be different from each other or key_1 == key_3 != key_2",
            )

        if iv:
            if mode == "ECB":
                abort(400, "Mode 'ECB' doesn't use an Initialization vector")
            elif len(iv.encode("utf-8")) != 8:
                abort(400, "Initialization vector must be of length 8")
            else:
                iv = str.encode(iv)

        message = str.encode(message)

        try:
            # Electronic Code Book
            if mode == "ECB":
                cipher = DES3.new(key, DES3.MODE_ECB)
                encrypted = cipher.encrypt(pad(message, DES3.block_size))
                cipher_iv = ""
            # Cipher-Block Chaining
            elif mode == "CBC":
                cipher = DES3.new(key, DES3.MODE_CBC, iv)
                encrypted = cipher.encrypt(pad(message, DES3.block_size))
                cipher_iv = b64encode(cipher.iv).decode("utf-8")
            # Cipher FeedBack
            elif mode == "CFB":
                cipher = DES3.new(key, DES3.MODE_CFB, iv)
                encrypted = cipher.encrypt(message)
                cipher_iv = b64encode(cipher.iv).decode("utf-8")
            # Output FeedBack
            elif mode == "OFB":
                cipher = DES3.new(key, DES3.MODE_OFB, iv)
                encrypted = cipher.encrypt(message)
                cipher_iv = b64encode(cipher.iv).decode("utf-8")
        except Exception as e:
            print(e)
            abort(500, "Unknown error")

        # Return base64
        data = {
            "iv": cipher_iv,
            "encrypted_message": b64encode(encrypted).decode("utf-8"),
        }

        return jsonify(data)
示例#25
0
from Crypto.Cipher import DES3
from Crypto import Random

#----GENERATING KEY & IV---------
k = Random.get_random_bytes(24)  # 24x8=192bits
#to adjust parity bits the key size must be 16 or 24 bytes
print("key taken=", k, "length=", len(k))
key = DES3.adjust_key_parity(k)  #setting parity bits for 3-des
print("key after parity drop=", key, "length=", len(key))
iv = Random.new().read(
    DES3.block_size
)  #initialize initialization vector(iv) randomly for mode CBC ,i.e., 8 block size

#-----ENCRYPTION------
#making an object for encryption in CBC
cipher_des3 = DES3.new(key, DES3.MODE_CBC, iv)
p = input(str("Enter plaintext: "))
while len(
        p
) % 8 != 0:  #length of plaintext must be multiple of 8, to make it suitable for CBC mode
    p += " "
enc_text = cipher_des3.encrypt(
    p.encode('utf-8'))  # .encode() is used to convert string to byte stream
print("encypted text = ", enc_text)

#------DECRYPTION-------
print("Decryption.....")
#making decryption object
decipher_des3 = DES3.new(key, DES3.MODE_CBC, iv)
dec_text = decipher_des3.decrypt(enc_text)
print("decypted text = ",
示例#26
0
    print "El tiempo de ejecucion fue:", tiempo_ejecucion

###############      FIN    SHA256        #########

###############      INICIO    DES        #########

from Crypto.Cipher import DES3
from Crypto import Random
from Crypto.Util import Counter
print('\n' + "--------DES---------" + '\n')
tiempo_inicial = time()
f = open("DES.txt", "r")
x = 0
for x in range(30):
    key = str.encode(f.readline()[0:16])
    DES3.adjust_key_parity(key)
    cipher = DES3.new(key, DES3.MODE_EAX)
    msg = cipher.nonce + cipher.encrypt(str.encode(f.readline()))
    tiempo_final = time()
    tiempo_ejecucion = tiempo_final - tiempo_inicial
    print "El tiempo de ejecucion fue:", tiempo_ejecucion

###############      FIN    DES        #########

###############      INICIO    AES        #########

from Crypto.Cipher import AES
print('\n' + "--------AES---------" + '\n')
tiempo_inicial = time()
f = open("AES.txt", "r")
x = 0
示例#27
0
 def test_parity_option2(self):
     before_2k = unhexlify("CABF326FA56734324FFCCABCDEFACABF")
     after_2k = DES3.adjust_key_parity(before_2k)
     self.assertEqual(after_2k,
                      unhexlify("CBBF326EA46734324FFDCBBCDFFBCBBF"))
示例#28
0
print( 'Texto cifrado: {}' .format( ciphertext ) )

decipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = decipher.decrypt(ciphertext)
try:
    decipher.verify( tag )
    print( 'Mensaje verificado' )
    print( 'Decifrando mensaje: {}' .format( plaintext ) )
except:
    print( 'Key incorrect or message corrupted' )

#3DES

while True:
    try:
        key_3_Des = DES3.adjust_key_parity( get_random_bytes(24) )
        break
    except ValueError:
        pass

#cipher
plaintext = b'Cifrando con triple DES '
iv = get_random_bytes(8)
cipher = DES3.new( key=key_3_Des , mode=DES3.MODE_CFB , iv=iv )
msg = cipher.encrypt( plaintext )
print( 'Cifrando con DES' )
print( 'Texto original: {}' .format( plaintext ) )
print( 'key: {}' .format( key_3_Des ) )
print( 'Texto cifrado: {}' .format( msg  ) )

#decipher
示例#29
0
 def test_parity_option3(self):
     before_3k = unhexlify("AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCC")
     after_3k = DES3.adjust_key_parity(before_3k)
     self.assertEqual(after_3k,
                      unhexlify("ABABABABABABABABBABABABABABABABACDCDCDCDCDCDCDCD"))
    def post(self):
        args = des3_decrypt_parser.parse_args()
        key_1 = args["key_1"]
        key_2 = args["key_2"]
        key_3 = args["key_3"]
        mode = args["mode"].upper()
        iv_mode = args["iv_mode"]
        iv = args["iv"]
        encrypted_message = args["encrypted_message"]

        # Error handling
        try:
            key = DES3.adjust_key_parity(
                str.encode(key_1) + str.encode(key_2) + str.encode(key_3)
            )
        except Exception as e:
            print(e)
            abort(
                400,
                "Invalid key format, each key must be of length 8. The three keys must be different from each other or key_1 == key_3 != key_2",
            )

        if iv:
            if mode == "ECB":
                abort(400, "Mode 'ECB' doesn't use an Initialization vector")

            # Accept both utf-8 and base64
            if iv_mode == "base64":
                try:
                    iv = b64decode(iv)
                except Exception as e:
                    print(e)
                    abort(400, "Invalid base64 string")
            elif len(iv.encode("utf-8")) != 8:
                abort(400, "Initialization vector must be of length 8")
            else:
                iv = str.encode(iv)

        try:
            encrypted_message = b64decode(encrypted_message)
        except binascii.Error as e:
            print(e)
            abort(400, "Message has to be encoded in base64")

        try:
            # Electronic Code Book
            if mode == "ECB":
                cipher = DES3.new(key, DES3.MODE_ECB)
                decrypted = unpad(cipher.decrypt(encrypted_message), DES3.block_size)
            # Cipher-Block Chaining
            elif mode == "CBC":
                cipher = DES3.new(key, DES3.MODE_CBC, iv)
                decrypted = unpad(cipher.decrypt(encrypted_message), DES3.block_size)
            # Cipher FeedBack
            elif mode == "CFB":
                cipher = DES3.new(key, DES3.MODE_CFB, iv)
                decrypted = cipher.decrypt(encrypted_message)
            # Output FeedBack
            elif mode == "OFB":
                cipher = DES3.new(key, DES3.MODE_OFB, iv)
                decrypted = cipher.decrypt(encrypted_message)
        except Exception as e:
            print(e)
            abort(500, "Unknown error")

        # Return base64
        data = {"decrypted_message": decrypted.decode()}

        return jsonify(data)