I need to generate MAC based on ISO 9797 Alg3 from a plaintext. I already wrote a same function in java and C# by "BouncyCastle" tool very easy as following code. But, there is not any sample for python around the internet.
using System.Text;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Macs;
using System.Security.Cryptography;
using System.IO;
namespace TestGenerateMAC2
{
class Program
{
public static string getMac(string text, string key)
{
byte[] keyBytes = StringToByteArray(key);
byte[] data = Encoding.UTF8.GetBytes(text);
DesEngine cipher = new DesEngine();
ISO9797Alg3Mac mac = new ISO9797Alg3Mac(cipher);
KeyParameter keyP = new KeyParameter(keyBytes);
mac.Init(keyP);
mac.BlockUpdate(data, 0, data.Length);
byte[] outPut = new byte[8];
mac.DoFinal(outPut, 0);
return BytesToHex(outPut);
}
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();
}
public static string BytesToHex(byte[] bytes)
{
return String.Concat(Array.ConvertAll(bytes, delegate (byte x) { return x.ToString("X2"); })).ToLower();
}
}
}
Is there any same sample in python?