I have the following method in Flash which writes two ByteArrays and then base64 encodes them
private function generateSignature(data:String, secretKey:String):String {
var secretKeyByteArray:ByteArray = new ByteArray();
secretKeyByteArray.writeUTFBytes(secretKey);
secretKeyByteArray.position = 0;
var dataByteArray:ByteArray = new ByteArray();
dataByteArray.writeUTFBytes(data);
dataByteArray.position = 0;
var hmac:HMAC = new HMAC(new SHA1());
var signatureByteArray:ByteArray = hmac.compute(secretKeyByteArray, dataByteArray);
return Base64.encodeByteArray(signatureByteArray);
}
In my C#, I have:
string GenerateSignature(string secretKey, string base64Policy)
{
byte[] secretBytes = Encoding.UTF8.GetBytes(secretKey);
byte[] dataBytes = Encoding.UTF8.GetBytes(base64Policy);
HMACSHA1 hmac = new HMACSHA1(secretBytes);
byte[] signature = hmac.ComputeHash(dataBytes);
return ByteToString(signature);
}
But, I get a different result set from the Flash version compared to the C# version. Can anyone spot anything that is obviously wrong?
EDIT
Here is the ByteToString method:
static string ByteToString(byte[] buffer)
{
string binary = string.Empty;
for (int i = 0; i < buffer.Length; i++)
{
binary += buffer[i].ToString("X2"); // Hex Format
}
return binary;
}
It looks pretty much the same; that said, I would suggest using
Convert.ToBase64Stringinstead of yourByteToStringmethod, the string concatenation in there is generally considered very bad practice.I am also not 100% sure if Base 64 encoding is logically the same as appending
byte.ToString("X2")for each byte to a string (although it could well be).Other than that, it shouldn’t be too difficult to debug and figure out where the two start to deviate…