- Почему существует несоответствие между зашифрованными выходными данными в C# и Python?< /p>
- Есть ли разница в том, как режим AES ECB обрабатывается в Python pycryptodome и C# AesCryptoServiceProvider? >
- Какие изменения мне нужно внести, чтобы обе реализации выдавали одинаковый зашифрованный вывод?
import binascii
from Crypto.Cipher import AES
def get_hex_val(c):
num = ord(hex_char)
print(f"num: {num} for hex: {hex_char}")
if num < 58:
return num - 48
else:
return num - 55
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]) 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
Код C#
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
Подробнее здесь: https://stackoverflow.com/questions/790 ... aes-ecb-mo