I'm trying to access the Moz API in a winform application. I looked at a guide for PHP and tried to convert it to C# but I'm running into problems.
Example for PHP: https://github.com/seomoz/SEOmozAPISamples/blob/master/php/signed_authentication_sample.php
I think it's my Signature that gets messed up. In the docs it says that:
"Signature: an HMAC-SHA1 hash of your Access ID, the Expires parameter, and your Secret Key. The secure hash must be base64 encoded then URL-encoded before Mozscape accepts the signature as valid."
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond) + 500;
var id = "mozscape-xxxxxxxx";
var secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();
var access = "mozscape-fa667096b" + "\r\n" + unixTime;
byte[] buffer = enc.GetBytes(access);
string signature = BitConverter.ToString(hmac.ComputeHash(buffer));
string signatureStep2 = System.Text.Encoding.UTF8.EncodeBase64(signature);
string signatureStep3 = HttpUtility.UrlEncode(signatureStep2);
Any ideas? The error I get is that my authentication failed.
Solved this by taking a look at https://github.com/PixelMEDIA/SEOMozLib.
This is the method that correctly generates the key:
public string CreateHashSignature(string strMozAccessId, string strMozSecretKey, string strTimeStamp)
{
string token = strMozAccessId + Environment.NewLine.Replace("\r", "") + strTimeStamp;
using (var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(strMozSecretKey), true))
{
var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(token));
var hashString = BitConverter.ToString(hash).Replace("-", "").ToLower();
return HttpUtility.UrlEncode(Convert.ToBase64String(hash));
}
}