xamarin.formstuya

CryptoJS to C# SHA256 encryption


i have been searching for a good solution where I copied code used in an API from postman and tried to use it in Xamarin forms. Problem is that there is a method in the API that generates "signatures", which they do in JS. I have tried various solutions but it does not generate the same message.

In JS =

(function () { 
var timestamp = getTime();
pm.environment.set("timestamp",timestamp);
var clientId = pm.environment.get("client_id");
var secret = pm.environment.get("secret");
var sign = calcSign(clientId,secret,timestamp);
pm.environment.set('easy_sign', sign);
})();

function getTime(){
    var timestamp = new Date().getTime();
    return timestamp;
}

function calcSign(clientId,secret,timestamp){
    var str = clientId + timestamp;
    var hash = CryptoJS.HmacSHA256(str, secret);
    var hashInBase64 = hash.toString();
    var signUp = hashInBase64.toUpperCase();
    return signUp;
}

In C# =

public void timeStamp()
    {
        /*
         *  var str = clientId + timestamp;
            var hash = CryptoJS.HmacSHA256(str, secret);
            var hashInBase64 = hash.toString();
            var signUp = hashInBase64.toUpperCase();
            return signUp;
        */

        var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        var t = (DateTime.Now.ToUniversalTime() - timestamp);
        time = t.ToString();

        
        //CalcSign
        var str = clientID + t;
        var key = Convert.FromBase64String(secret);
        //var key = Convert.FromBase64String(str);
        Console.Write("key:");
        prtByte(key);

        var provider = new System.Security.Cryptography.HMACSHA256(key);
        var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(str));
        Console.Write("hash:");
        prtByte(hash);

        var signature = Convert.ToBase64String(hash);
        Console.WriteLine("signature:" + signature);
        var signUp = signature.ToUpper();
        sign = signUp;
    }

    

    public static void prtByte(byte[] b)
    {
        for (var i = 0; i < b.Length; i++)
        {
            Console.Write(b[i].ToString("x2"));
        }
        Console.WriteLine();
    }

The message i get back is = "The request time is invalid".


Solution

  • After a lot of troubleshooting and help from @Jason and @Jack Hua the problem was solved by using DateTime.UtcNow, formatting with String.Format, converting the values first to double and then to int, shown below.

    var timestamp = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    Console.WriteLine("Timestamp = "+timestamp.ToString());
    var t2 = String.Format("{0}",timestamp.TotalMilliseconds);     
    var t = Double.Parse(t2);
    var t3 = Convert.ToInt64(t);
    time =""+ t3;
    

    Now I only need to solve my other issue "sign invalid", but that is another question. Cheers!!