用飞镖

时间:2018-04-14 13:16:07

标签: dart base64 sha256 hmac

我尝试在消息上使用base64解码的密钥生成sha256 HMAC。我想用dart语言。在python中,我可以使用以下代码完成:

# 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')

这是我用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?

但后来我不知道怎么回事。我找到了一些旧的示例代码,如下所示

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

但是,Hmac类中不再存在“add”方法。我也尝试了这个,但我不确定这是否正确

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

有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

如果你有完整的信息'可用然后只需调用convert()。如果消息很大或分片,则以块的形式处理。

你的例子很简单,一步一步拼写出来。

  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中的变量使用驼峰等等

答案 1 :(得分:0)

在最近的项目中,我必须与hmac签署请求以调用API。这是我所做的。希望这对您也有帮助。

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:crypto/crypto.dart';

String getHmacAuthHeader({
  @required final String inputUrl,
  @required final dynamic inputJsonContent,
  @required final String appId,
  @required final String appSecrets,
  final String method = "POST",
}) {
  final url = _encodeUrl(inputUrl);
  final seconds =
      (DateTime.now().millisecondsSinceEpoch / 1000).round().toString();
  final nonce = "N${DateTime.now().millisecondsSinceEpoch}";

  final contentHash = _getMd5HashInBase64FromJson(inputJsonContent);

  final signature = "$appId$method$url$seconds$nonce$contentHash";

  final signatureHmacHashBase64 = _getHmacHashInBase64FromString(appSecrets, signature);

  final token = "$appId:$signatureHmacHashBase64:$nonce:$seconds";

  return "hmacauth $token";
}

String _encodeUrl(String url) {
  if (!url.startsWith("/")) {
    url = "/$url";
  }
  return Uri.encodeComponent(url).toLowerCase();
}

String _getMd5HashInBase64FromJson(dynamic json) {
  final jsonString = jsonEncode(json);
  final jsonStringBytes = Utf8Encoder().convert(jsonString);

  final hashBytes = md5.convert(jsonStringBytes).bytes;
  final hashBase64 = base64Encode(hashBytes);
  return hashBase64;
}

String _getHmacHashInBase64FromString(String key, String data){
  final keyBytes = Utf8Encoder().convert(key);
  final dataBytes = Utf8Encoder().convert(data);

  final hmacBytes = Hmac(sha256, keyBytes)
      .convert(dataBytes)
      .bytes;

  final hmacBase64 = base64Encode(hmacBytes);
  return hmacBase64;
}