1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Discrepancy Between Encrypted Text Output in C# and Python Using AES ECB Mode

Discussão em 'Python' iniciado por Stack, Outubro 3, 2024 às 11:22.

  1. Stack

    Stack Membro Participativo

    I am facing an issue where the encrypted text output differs between C# and Python, despite using the same secret key and message. Both implementations utilize AES encryption in ECB mode. Can someone help identify why the outputs are different and suggest a solution?


    • Why is there a discrepancy between the encrypted outputs in C# and Python?


    • Is there a difference in how AES ECB mode is handled in Python pycryptodome and C# AesCryptoServiceProvider?


    • What modifications do I need to make to ensure both implementations produce the same encrypted output?

    I am attempting to encrypt the same message using AES in ECB mode with a 32-character secret key in both Python and C#. However, I am encountering discrepancies in the encrypted text outputs. Here are the details:

    import binascii
    from Crypto.Cipher import AES

    def string_to_byte_array(key_str):
    hex_str = key_str.encode("utf-8").hex()
    if len(hex_str) % 2 == 1:
    raise Exception("The binary key or input text cannot have an odd number of digits")

    byte_array = bytearray(len(hex_str) // 2)
    for i in range(len(hex_str) // 2):
    byte_array = (get_hex_val(hex_str[i * 2]) << 4) + get_hex_val(hex_str[i * 2 + 1])
    return byte_array

    def encrypt_message(message: str, secret_key: str) -> str:
    """
    Encrypts the given message using the provided secret key.

    Args:
    message (str): The message to be encrypted.
    secret_key (str): The secret key used for encryption.

    Returns:
    str: The encrypted message as a base64-encoded string.
    """
    key_bytes = string_to_byte_array(secret_key)
    plaintext_bytes = message.encode("ascii")
    print(plaintext_bytes)
    plaintext_padded = plaintext_bytes.ljust(
    AES.block_size * ((len(plaintext_bytes) + AES.block_size - 1) // AES.block_size),
    b"\x00",
    )
    cipher = AES.new(key_bytes, AES.MODE_ECB)
    ciphertext_bytes = cipher.encrypt(plaintext_padded)
    return binascii.hexlify(ciphertext_bytes).decode("ascii").upper().replace("-", "")

    key = "SOME_SECRET_KEY_WITH_32_CHARS_12"
    message = "1234"
    encrypted_value = encrypt_message(message, key)
    print(encrypted_value)
    # Output Encrypted Text: D82B2DBAFB2D5CC2A09971BFB9D9D8F0


    The C# code

    using System;
    using System.Security.Cryptography;
    using System.Text;

    public static class AesEncryption
    {
    public static string EncryptAES(string key, string input)
    {
    byte[] keyBuffer = StringToByteArray(key);
    byte[] inputBuffer = Encoding.ASCII.GetBytes(input);
    byte[] cipherbuffer = AESEncrypt(inputBuffer, keyBuffer);
    return BitConverter.ToString(cipherbuffer).Replace("-", "");
    }

    private static byte[] StringToByteArray(string hex)
    {
    if ((hex.Length % 2) == 1)
    {
    throw new Exception("The binary key or input text cannot have an odd number of digits");
    }
    byte[] buffer = new byte[hex.Length >> 1];
    for (int i = 0; i < (hex.Length >> 1); i++)
    {
    buffer = (byte)((GetHexVal(hex[i << 1]) << 4) + GetHexVal(hex[(i << 1) + 1]));
    }
    return buffer;
    }

    private static byte[] AESEncrypt(byte[] original, byte[] key)
    {
    using (AesCryptoServiceProvider cryptoProvider = new AesCryptoServiceProvider
    {
    Key = key,
    Mode = CipherMode.ECB,
    Padding = PaddingMode.Zeros
    })
    {
    ICryptoTransform transform = cryptoProvider.CreateEncryptor();
    return transform.TransformFinalBlock(original, 0, original.Length);
    }
    }

    private static int GetHexVal(char hex)
    {
    int num = hex;
    return (num - ((num < 58) ? 48 : 55));
    }
    }

    public class Program
    {
    public static void Main()
    {
    string plainText = "1234";
    string key = "SOME_SECRET_KEY_WITH_32_CHARS_12";
    try
    {
    string encrypted = AesEncryption.EncryptAES(key, plainText);
    Console.WriteLine($"Encrypted Text: {encrypted}");

    }
    catch (Exception ex)
    {
    Console.WriteLine($"Error: {ex.Message}");
    }
    }
    }

    # Output Encrypted Text: 5FBD029BA3BC7993C4431A4E6B995BD3

    Continue reading...

Compartilhe esta Página