Что такое ошибка кодирования, т.е. ошибка utf-8 при шифровании? - PullRequest
0 голосов
/ 30 мая 2020
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
import hashlib
import base64

def decrypt(enc, key_hash):                # To decrypt data
    print("\nIn Decryption method\n")
    unpad = lambda s: s[:-ord(s[-1:])]
    enc = base64.b64decode(enc)

    iv = enc[:AES.block_size]
    cipher = AES.new(key_hash, AES.MODE_CFB, iv)
    ciper_text =  cipher.decrypt(enc[AES.block_size:])
    ciper_text = ciper_text.decode('utf-16')
    ciper_text = unpad(ciper_text)
    return ciper_text

def encrypt(ID, temperature, key_hash):     # To encrypt data
    print("\nIn Encryption method\n")
    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    ID = pad(ID)
    ID = ID.encode('utf-16') 

    temperature = pad(temperature)
    temperature = temperature.encode('utf-16')
    iv = get_random_bytes(AES.block_size)
    cipher = AES.new(key= key_hash, mode= AES.MODE_CFB, iv= iv)

    ID_cipher = base64.b64encode(iv + cipher.encrypt(ID))
    temperature_cipher = base64.b64encode(iv + cipher.encrypt(temperature))
    print("Id cipher is '{0}'".format(ID_cipher))
    print("temp cipher is '{0}'".format(temperature_cipher))
    return (ID_cipher, temperature_cipher)

no = int(input("enter no of records"))
key_hash = hashlib.sha256(b"charaka").digest()       # Creating key for cipher


for i in range(no):                                    
   ID = input("enter ID\n")
   temperature = input("enter temperature\n")       
   (ID_cipher, temperature_cipher) = encrypt(ID, temperature, key_hash)
   print("Decyrpted ID is '{0}'".format((decrypt(ID_cipher, key_hash))))
   print("Decyrpted temp is '{0}'".format((decrypt(temperature_cipher, key_hash))))

Когда я хочу ввести запись, например, « ID, температура », и пытаюсь расшифровать оба идентификатора, расшифровывается нормально, но температура не расшифровывается. Иногда возникает ошибка utf-16, т.е.

ciper_text = ciper_text.decode ('utf-16') UnicodeDecodeError: код 'utf-16-le' c не может декодировать байты в позиции 4 -5: недопустимый суррогат UTF-16

иногда вывод не отображается должным образом

В методе дешифрования Decyrpted temp is '勼 ⼋'

Я сомневаюсь, что когда идентификатор хорошо расшифровывается, почему у меня возникают проблемы с расшифровкой значения температуры. Я изучал другие руководства по методам кодирования, но проблема та же.

Я использовал библиотеку pycryptodome для шифрования строк с помощью AES. Спасибо

...