简体   繁体   中英

Encrypt data with accents using python crypto library

I am implementing DES3 in Python using Crypto library. I was doing some test when I've stumbled upon the next problem:

If the plain text that I want to encrypt contains strange charactes, as accents, fails.

For example, my code is working fine when I try to encrypt the next word:

Text to be encrypted(multiple of 8 in length) : "Hello Jose "

However, it fails if I try to encrypt the same text but containing an accent: Text to be encrypted (multiple of 8 in length)= "Hello José "

The error that I am getting is “ValueError: Input strings must be a multiple of 8 in length”.

If I check the length of the word, it is a multiple of 8.

plaintext="Hello Jose      "
print(" Plain text:" + plaintext)
print(" Plain Text length:" + str(len(plaintext)))

Result: Plain Text length : 16

Find next a reduced example of my code:

from Crypto.Cipher import DES3
import binascii
import base64

plaintext="Hello Jose      "
print(" Plain text:" + plaintext)
print(" Plain Text length:" + str(len(plaintext)))

#### ENCRYPTION 
key ='173JKL3D93A9CNI1G6NP9A14'
key=bytes(key, 'utf-8')
plaintext_bytes=bytes(plaintext, 'utf-8')
print(" Plain Text length:" + str(len(plaintext_bytes)))


cipher_encrypt=DES3.new(key)
encrypted_text=cipher_encrypt.encrypt(plaintext_bytes)
print( " Encrypted word:" + str(encrypted_text))

#### DECRYPTION
cipher_encrypt=DES3.new(key)
decrypted_text=cipher_encrypt.decrypt(encrypted_text)
print(" Decripted text:" + str(decrypted_text,'utf-8') + "\n")

Can anyone help me to understand why it is not working correctly?

Goyo is right. The algorithm reads the plain text as a byte-string. Knowing that, the length in bytes of one character with accent is 2. See next example:

>> a='a'
>> print("length:" + str(len(a.encode('utf-8'))))
length:1
>> a='á'
>> print("length:" + str(len(a.encode('utf-8'))))
length:2

So, firstly you have to encode the text to bytes and then calculate the length.

What you could do is calculate the next multiple of 8 and that should be the length of the plain text. After that, you could fill out the string with whitespace to that length.

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