I am working on converting the encryption function of AES/GCM-256 in C# to Python. i found the following code in Python and i am using it, but the problem is that my data in the Python function is the same as the C# data. The output string (encoded) produced by my Python function is not the same as the output of the C# function, although my inputs (key, iv and data) are the same in both functions.
I would be grateful if someone could help me
My keyis: b'4fda3c622e966e0839441401bbd3b8f191d4267bf5f19b40812a34b212fd3ed9'
My iv is: b'4fda3c622e966e0839441401bbd3b8f191d4267bf5f19b40812a34b212fd3ed9'
C# function
public static string AesEncrypt(byte[] payload, byte[] key, byte[] iv)
{
var cipher = new GcmBlockCipher(new AesEngine());
byte[] baPayload = new byte[0];
cipher.Init(true, new AeadParameters(new KeyParameter(key), 128, iv, baPayload));
var cipherBytes = new byte[cipher.GetOutputSize(payload.Length)];
int len = cipher.ProcessBytes(payload, 0, payload.Length, cipherBytes, 0);
cipher.DoFinal(cipherBytes, len);
return Convert.ToBase64String(cipherBytes);
}
It can be converted to bytes using the following function PASSPHRASE in C#:
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
python:
PASSPHRASE= b'a4b42ed2702cb1b00a14f39a88c719cb04e5e8b29e2479634c990258e327483'
def AES_encrypt(data,iv):
global PASSPHRASE
data_json_64 = data
key = binascii.unhexlify(PASSPHRASE)
cipher = AES.new(key, AES.MODE_GCM, iv)
x = cipher.encrypt(data)
return x
Because all my data is the same, I expect my output to be the same, but it is not
My input test string to both C# and Python is::
"In publishing and graphic design, Lorem ipsum is a"
My iv to both C# and Python is:
'4fda3c622e966e0839441401bbd3b8f191d4267bf5f19b40812a34b212fd3ed9'
The encoded output in C# is:
02Em9Vve6fWtAcVNesIXzagoB327EmskwMZdRippAAaxqAzkp0VeGSjctbaguqA/01CnPHB2PkRDDOxjgZ9pAfu2
The encoded output in Python is:
HudpKzIov7lNt4UNng+a9P/FLXrzdenwDBT4uFYhIUc3XOS7TpaCzxja8I+zHCdXnvk=