I'm working with a vendor who owns an API. In order to call the API, they require us to hash the whole body of the request and add it to a Content-Digest digest header key. Content-Digest: SHA256=<digest>. They have provided us with a RSA Private Key along with a linq LINQPad file written in C#. This script is what outputs the base64 encoded hash that goes into the Content-Digest.
The problem is, I don't know any C# and the application that we are going to be using this API for is written in Python. What I'm looking for is a way to output the exact same formatted hash in a Python Script.
This is the C# Code they provided:
void Main()
{
var payload = GetPayload();
SignData(payload);
}
private void SignData(string payload)
{
var keyFormatted = GetRSAKey();
byte[] privateKeyInDER = Convert.FromBase64String(keyFormatted);
var rsa = DecodeRSAPrivateKey(privateKeyInDER);
var data = Encoding.Default.GetBytes(payload);
using var hasher = new SHA512Managed();
var signBytes = rsa.SignData(data, hasher);
var computedSignature = Convert.ToBase64String(signBytes);
computedSignature.Dump();
}
private static int GetIntegerSize(BinaryReader binary)
{
var bt = binary.ReadByte();
if (bt != 0x02)
{
return 0;
}
bt = binary.ReadByte();
int count;
if (bt == 0x81)
{
count = binary.ReadByte();
}
else if (bt == 0x82)
{
var highbyte = binary.ReadByte();
var lowbyte = binary.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else
{
count = bt;
}
while (binary.ReadByte() == 0x00)
{
count--;
}
binary.BaseStream.Seek(-1, SeekOrigin.Current);
return count;
}
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
// --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey);
BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
try
{
var twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
{
binr.ReadByte();//advance 1 byte
}
else if (twobytes == 0x8230)
{
binr.ReadInt16();
} //advance 2 bytes
else
{
return null;
}
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
{
return null;
}
var bt = binr.ReadByte();
if (bt != 0x00)
{
return null;
}
var elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems);
// ------- create RSACryptoServiceProvider instance and initialize with private key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters
{
Modulus = MODULUS,
Exponent = E,
D = D,
P = P,
Q = Q,
DP = DP,
DQ = DQ,
InverseQ = IQ
};
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
finally
{
binr.Close();
}
}
private string GetRSAKey() {
return "private key";
}
private string GetPayload()
{
return @"{
""key"":""value"",
""key2"":{
""subkey"": true,}
}";
}
And it outputs something like this (344 Characters):
15vgzyv8Cke3Mkkwc3ryAgDMmY6olRfvgLqNyfhfti2GAfLb6s/vgrWc1p5jlWgQHh37Ir7UYThXldspriBz5NPl+BSFIW2dxXTMO2NMpzgc/5fmFN2maJCgwzDP0aqupmUGrw/DZp8zMAKtxWqs+8TGQTDthAW+4Y8g0hoLYSTEIHwvbkBUCspWo4Qr0MXj86P1Gsu5DbQ4Fs23fbajPuZqRHTyYzeANvxnma9mm30CwLD6blnKOLa+xRVd6eeuHu+Hp+F8hl5xSJS0Bcse4K0ZKccDD6sm4KSX2vaNQeQQ45fIDYLRUXYckGifqu7nJLwHILEenxue10841IHleA==
I've been trying to figure this out in Python and this is as close as I've got:
import hashlib
import base64
import hmac
key = '''
private key
'''
msg = '''
{"body to hash"}
'''
print((base64.b64encode(hmac.new(bytearray(key.upper(), "ASCII") , bytearray(msg,"ASCII") , hashlib.sha512).digest())).decode("ASCII"))
However, this returns a hash that looks like this:
9dfgSdEzLEdGHze/SrYCSGVHurEvFabe3YgBSqKowxHb96UznenFFoeTDjx2dlk2B53qq9ISKVwv+xFBXMBePQ==
If there is anyone who can help, it would be greatly appreciated!
Encoding.Defaultto convert the message to bytes. The python code uses"ASCII". Are you sure thatEncoding.Defaultis ASCII?