это мой первый пост. Поскольку я пробовал библиотеку шифрования и дешифрования с использованием E CC, и я столкнулся с проблемой
Traceback (most recent call last):
File "ecc_dec3.py", line 51, in <module>
decryptedMsg = decrypt_ECC(encryptedMsgObj, privKey)
File "ecc_dec3.py", line 22, in decrypt_ECC
sharedECCKey = privKey * ciphertextPubKey
OverflowError: cannot fit 'int' into an index-sized integer
, и это мой код шифрования:
from tinyec import registry
from Crypto.Cipher import AES
import hashlib, secrets, binascii
import json
def encrypt_AES_GCM(msg, secretKey):
aesCipher = AES.new(secretKey, AES.MODE_GCM)
ciphertext, authTag = aesCipher.encrypt_and_digest(msg)
return (ciphertext, aesCipher.nonce, authTag)
def ecc_point_to_256_bit_key(point):
sha = hashlib.sha256(int.to_bytes(point.x, 32, 'big'))
sha.update(int.to_bytes(point.y, 32, 'big'))
return sha.digest()
curve = registry.get_curve('brainpoolP256r1')
def encrypt_ECC(msg, pubKey):
ciphertextPrivKey = secrets.randbelow(curve.field.n)
sharedECCKey = ciphertextPrivKey * pubKey
secretKey = ecc_point_to_256_bit_key(sharedECCKey)
ciphertext, nonce, authTag = encrypt_AES_GCM(msg, secretKey)
ciphertextPubKey = ciphertextPrivKey * curve.g
return (ciphertext, nonce, authTag, ciphertextPubKey)
msg = b'{"led":[{"status":"ON"}]}'
print("Input message: ", msg)
privKey = secrets.randbelow(curve.field.n)
pubKey = privKey * curve.g
encryptedMsg = encrypt_ECC(msg, pubKey)
encryptedMsgObj = {
'ciphertext': binascii.hexlify(encryptedMsg[0]),
'nonce': binascii.hexlify(encryptedMsg[1]),
'authTag': binascii.hexlify(encryptedMsg[2]),
'ciphertextPubKey': hex(encryptedMsg[3].x) + hex(encryptedMsg[3].y % 2)[2:]
}
print("encrypted msg: \n", encryptedMsgObj)
'''saveJson = json.dumps(encryptedMsgObj)
with open('jsonencrypt.json','w') as encryptFile:
encryptFile.write(saveJson)'''
#Save file to JSON
def python_dict_to_json_file(file_path):
try:
# Get a file object with write permission.
file_object = open(file_path, 'w',encoding='utf-8')
dict_object = dict(ciphertext = binascii.hexlify(encryptedMsg[0]).decode("ascii"),
nonce = binascii.hexlify(encryptedMsg[1]).decode("ascii"),
authTag = binascii.hexlify(encryptedMsg[2]).decode("ascii"),
ciphertextPubKey = hex(encryptedMsg[3].x) + hex(encryptedMsg[3].y % 2)[2:]
)
# Save dict data into the JSON file.
json.dump(dict_object, file_object)
print("Save "+file_path + " created. ")
except FileNotFoundError:
print(file_path + " not found. ")
if __name__ == '__main__':
python_dict_to_json_file("./encryptData.json")
код дешифрования:
from tinyec import registry
from Crypto.Cipher import AES
import hashlib, secrets, binascii
import json
import sys
def decrypt_AES_GCM(ciphertext, nonce, authTag, secretKey):
aesCipher = AES.new(secretKey, AES.MODE_GCM, nonce)
plaintext = aesCipher.decrypt_and_verify(ciphertext, authTag)
return plaintext
def encrypt_ECC(msg, pubKey):
ciphertextPrivKey = secrets.randbelow(curve.field.n)
sharedECCKey = ciphertextPrivKey * pubKey
secretKey = ecc_point_to_256_bit_key(sharedECCKey)
ciphertext, nonce, authTag = encrypt_AES_GCM(msg, secretKey)
ciphertextPubKey = ciphertextPrivKey * curve.g
return (ciphertext, nonce, authTag, ciphertextPubKey)
def decrypt_ECC(encryptedMsgObj, privKey):
(ciphertext, nonce, authTag, ciphertextPubKey) = encryptedMsgObj
sharedECCKey = privKey * ciphertextPubKey
secretKey = ecc_point_to_256_bit_key(sharedECCKey)
plaintext = decrypt_AES_GCM(ciphertext, nonce, authTag, secretKey)
return plaintext
def ecc_point_to_256_bit_key(point):
sha = hashlib.sha256(int.to_bytes(point.x, 32, 'big'))
sha.update(int.to_bytes(point.y, 32, 'big'))
return sha.digest()
curve = registry.get_curve('brainpoolP256r1')
with open('encryptData.json','r') as fh:
dict = fh.read()
dict_object = json.loads(dict)
encryptedMsgObj = {
'ciphertext': dict_object['ciphertext'].encode("ascii"),
'nonce': dict_object['nonce'].encode("ascii"),
'authTag': dict_object['authTag'].encode("ascii"),
'ciphertextPubKey': dict_object['ciphertextPubKey'].encode("ascii")
}
strhex = (bytearray(dict_object['ciphertextPubKey'],"utf-8"))
print("ciphertext :",dict_object['ciphertext'].encode("ascii"))
print('nonce: ',dict_object['nonce'].encode("ascii"))
print('authTag: ',dict_object['authTag'].encode("ascii"))
print('ciphertextPubKey :' , dict_object['ciphertextPubKey'])
privKey = secrets.randbelow(curve.field.n)
decryptedMsg = decrypt_ECC(encryptedMsgObj, privKey)
print("decrypted msg:", decryptedMsg)
и это оригинальная кодовая ссылка: https://github.com/nakov/Practical-Cryptography-for-Developers-Book/blob/master/asymmetric-key-ciphers/ecc-encryption-decryption.md
У меня есть цель получить входящее сообщение и закодировать его, используя E CC, и сохранить его как json файл. После этого расшифруйте его, прочитав зашифрованный файл json. И сохранить в виде простого текста в текстовом виде. json