使用 ECC 加密时出现错误

问题描述 投票:0回答:1

我正在尝试创建一个 POC,其中我需要创建公钥和私钥来加密文本

最初我可以使用 DER 格式来归档密钥和生成的加密文本

但是我被告知要以 Base64 utf8 格式管理密钥和加密值。我试图修改我的Python代码,只是对值进行编码,它适用于加密,但不适用于解密

希望您能对此有所了解,这是我的代码

from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
import base64

def generateKeys():
    # Generar clave privada
    private_key = ec.generate_private_key(ec.SECP256R1())
    private_key_der = private_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )

    # Generar clave pública
    public_key = private_key.public_key()
    public_key_der = public_key.public_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )

    # Guarda estas claves en un lugar seguro y usa los valores DER en los ejemplos a continuación
    return privateKeyBase64 = base64.b64encode(private_key_der).decode('utf-8'), base64.b64encode(public_bytes_der).decode('utf-8') 
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import base64
import os

def encrypt_message(message: str, public_key_base64: str) -> str:
    # Decode the base64 public key
    public_key_der = base64.b64decode(public_key_base64.encode('utf-8'))
    
    # Load the public key from DER format
    public_key = serialization.load_der_public_key(public_key_der)
    
    # Generate ephemeral key
    ephemeral_key = ec.generate_private_key(ec.SECP256R1())
    shared_key = ephemeral_key.exchange(ec.ECDH(), public_key)
    
    # Derive a symmetric key
    derived_key = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=None,
        info=b'encryption'
    ).derive(shared_key)
    
    # Encrypt the message using AES-GCM
    iv = os.urandom(12)
    encryptor = Cipher(
        algorithms.AES(derived_key),
        modes.GCM(iv)
    ).encryptor()
    
    # Validar los nulos y convertirlos a blanco
    message = "" if message is None else message
    
    ciphertext = encryptor.update(message.encode('utf-8')) + encryptor.finalize()
    
    # Concatenate the ephemeral public key, IV, tag, and ciphertext
    encrypted_data = (
        ephemeral_key.public_key().public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        ) + iv + encryptor.tag + ciphertext
    )
    
    # Encode the encrypted data to base64 and utf-8
    encrypted_data_base64 = base64.b64encode(encrypted_data).decode('utf-8')
    
    return encrypted_data_base64
def decrypt_message(encrypted_data_base64: str, private_key_base64: str) -> str:
    # Decode the message
    encrypted_message = base64.b64decode(encrypted_data_base64.encode('utf-8'))

    # Decode the base64 private key 
    private_key_der = base64.b64decode(private_key_base64.encode('utf-8'))
    
    # Load the private key from DER format
    private_key = serialization.load_der_private_key(private_key_der, password=None)
    
    # Extract the ephemeral public key, IV, tag, and ciphertext from the encrypted message
    ephemeral_public_key_der = encrypted_message[:91]
    iv = encrypted_message[91:103]
    tag = encrypted_message[103:119]
    ciphertext = encrypted_message[119:]
    
    # Load the ephemeral public key
    ephemeral_public_key = serialization.load_der_public_key(ephemeral_public_key_der)
    
    # Generate shared key
    shared_key = private_key.exchange(ec.ECDH(), ephemeral_public_key)
    
    # Derive a symmetric key
    derived_key = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=None,
        info=b'encryption'
    ).derive(shared_key)
    
    # Decrypt the message using AES-GCM
    decryptor = Cipher(
        algorithms.AES(derived_key),
        modes.GCM(iv, tag)
    ).decryptor()
    
    decrypted_message = decryptor.update(ciphertext) + decryptor.finalize()
    
    return decrypted_message.decode()

这是我打电话给defs的时候

privateKey,publicKey = generateKeys()
originalText = "hello world!"
encryptedText = encrypt_message(originalText,publicKey)
decryptedText = decrypt_message(encryptedText, privateKey)

它在解密的文本行上失败并显示以下消息

InvalidTag                                Traceback (most recent call last)
File <command-1520670422353806>:24
     22 originalText = frase
     23 encryptedText = encrypt_message(frase,publicKey)
---> 24 decryptedText = decrypt_message(encryptedText, privateKey)
     26 #print(f"Llave Publica : {publicKey}", f"\nOriginal : {originalText}", f"\nCifrado : {encryptedText}")
     27 print(f"Original : {originalText}", f"\nCifrado : {encryptedText}",f"\nDescifrado : {decryptedText}")

File <command-1520670422353807>:37, in decrypt_message(encrypted_data_base64, private_key_base64)
     31 # Decrypt the message using AES-GCM
     32 decryptor = Cipher(
     33     algorithms.AES(derived_key),
     34     modes.GCM(iv, tag)
     35 ).decryptor()
---> 37 decrypted_message = decryptor.update(ciphertext) + decryptor.finalize()
     39 return decrypted_message.decode()

File /databricks/python/lib/python3.9/site-packages/cryptography/hazmat/primitives/ciphers/base.py:187, in _AEADCipherContext.finalize(self)
    185 if self._ctx is None:
    186     raise AlreadyFinalized("Context was already finalized.")

我的直觉告诉我,base64 utf8 的编码可能会改变私钥或加密文本中的某些内容。

请帮帮我!!!

python encryption encryption-asymmetric
1个回答
0
投票

为了澄清,现在的第一块代码中有一个拼写错误

返回privateKeyBase64 =base64.b64encode(private_key_der).decode('utf-8'),base64.b64encode(public_bytes_der).decode('utf-8')

确实如此 返回base64.b64encode(private_key_der).decode('utf-8'),base64.b64encode(public_bytes_der).decode('utf-8')

© www.soinside.com 2019 - 2024. All rights reserved.