在Dart中使用hmac和sha256签名消息 [英] Signing a message with hmac and sha256 in dart

查看:1007
本文介绍了在Dart中使用hmac和sha256签名消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在消息上使用base64解码的密钥生成sha256 HMAC.我想使用飞镖语言.在python中,我可以使用以下代码来做到这一点:

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:

# PYTHON CODE
import hmac, hashlib, base64
...
message = 'blabla'
secret = 'DfeRt[...]=='
secret_b64 = base64.b64decode(secret)
signature = hmac.new(secret_b64, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')

这是我尝试过的飞镖游戏:

Here is what I tried with dart:

// DART CODE
import 'package:crypto/crypto.dart';
import 'dart:convert';
...
String message = 'blabla';
String secret = 'DfeRt[...]=='
var secret_b64 = BASE64.decode(secret);
var hmac = new Hmac(sha256, secret_b64);
// what now?

但是后来我不知道该怎么做.我找到了一些旧的示例代码,如下所示

But then I don't know how to go on. I found some old example code which looks like the following

var message_byte = UTF8.encode(message);
hmac.add(message_byte);

但是,Hmac类中不再存在方法"add".我也尝试过,但是我不确定这是否正确

However, the method "add" does not exist any more in the Hmac class. I also tried this, but I am not sure if this is correct

var message_byte = UTF8.encode(message);    
var signature = hmac.convert(message_byte);
var signature_b64 = BASE64.encode(signature.bytes);

有人可以帮我吗?

推荐答案

如果您有完整的消息"可用,则只需调用convert()即可.如果邮件很大或成碎片,则应分块处理.

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<int> messageBytes = utf8.encode(message);
  List<int> key = base64.decode(base64Key);
  Hmac hmac = new Hmac(sha256, key);
  Digest digest = hmac.convert(messageBytes);

  String base64Mac = base64.encode(digest.bytes);

请阅读有效飞镖指南.请注意,常量现在是小写的了,Dart中的变量使用的是驼峰式的,等等.

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

这篇关于在Dart中使用hmac和sha256签名消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆