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 ByteToStrin开发者_运维知识库g
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.ToBase64String
instead of your ByteToString
method, 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...
Your ByteToString function merely returns a hexadecimal version of the signature. Your flash version base 64 encodes it. There's a big difference between converting something to a hexadecimal string, and base 64 encoding.
Use Convert.ToBase64String
instead of ByteToString.
Flash might not be emitting the BOM (Byte Order Mark), where C# (.Net) does.
public static readonly Encoding Utf8NoBom = new UTF8Encoding(false);
According to the Flash Documentation you are using the correct encoding on the C# end; so this is the only possible alternative (it didn't have anything to say about the BOM).
精彩评论