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

查看:56
本文介绍了在 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('
')

这是我对 dart 的尝试:

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);

请阅读 Effective Dart 指南.注意常量现在是小写的,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天全站免登陆