Search code examples
flutterdartcryptographybase64hmac

Using Hmac and base64 to sign


I am trying to connect to a server, and the password is a bit tricky. the password should be generated like this

base64(hmac(secret,timestamp:userid)

I have the secret and userid we can consider them SECRET and 0. I am using Flutter and in Flutter hmac function takes a HASH and a list so I cant hash two strings/

can you help with this issue?


Solution

  • The crypto package contains an implementation of HMAC. As you would expect, it needs a key and a message. See the sample code:

    var key = utf8.encode('p@ssw0rd'); // key gets converted to bytes (using utf8)
    var bytes = utf8.encode("foobar"); // message gets converted to bytes (utf8)
    
    var hmacSha256 = Hmac(sha256, key); // HMAC-SHA256 (using the key bytes)
    var digest = hmacSha256.convert(bytes); // the hmac is generated from the message
    

    In your case you'd use:

    var key = utf8.encode('SECRET'); 
    var bytes = utf8.encode('0');
    
    var hmacSha256 = Hmac(sha256, key); // HMAC-SHA256
    var digest = hmacSha256.convert(bytes);
    print(base64.encode(digest.bytes));
    

    All HMACs need a hash function. You need to find out which HMAC hash your API requires.