Signing a message with hmac and sha256 in dart

前端 未结 2 1069
旧时难觅i
旧时难觅i 2020-12-21 21:08

I try to generate a sha256 HMAC using a base64-decoded secret key on a message. I would like to use the dart language. In python, I could do it with the following code:

2条回答
  •  心在旅途
    2020-12-21 21:41

    If you have the whole 'message' available then just call convert(). If the message is large or in pieces then deal with it in chunks.

    Your example is simple, when spelled out step by step.

      String base64Key = 'DfeRt...';
      String message = 'blabla';
    
      List messageBytes = utf8.encode(message);
      List key = base64.decode(base64Key);
      Hmac hmac = new Hmac(sha256, key);
      Digest digest = hmac.convert(messageBytes);
    
      String base64Mac = base64.encode(digest.bytes);
    

    Please read the Effective Dart guide. Note how constants are now lower case, variables in Dart use camel case, etc

提交回复
热议问题