【问题标题】:How to use ComputeHash in flutter如何在 Flutter 中使用 ComputeHash
【发布时间】:2022-07-28 00:50:49
【问题描述】:

我正在使用 dart 将 C# 哈希函数转换为一段代码的每个人,但我发现这两个函数的结果(使用 C# 的原始函数和我当前使用颤振的函数)并不相同.

调试后我发现问题在于将ComputeHash方法转换为flutter(我找不到类似的东西)。

原函数:

private static String sign(String data, String secretKey) {
            UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secretKey);
            HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
            
            byte[] messageBytes = encoding.GetBytes(data);
            var res = hmacsha256.ComputeHash(messageBytes);
            return Convert.ToBase64String(hmacsha256.ComputeHash(messageBytes));
 }

颤振功能:

  String sign(String data, String secretKey) {
    List<int> bytes = utf8.encode(_SECRET_KEY);
    var hmacSha256 = Hmac(sha256, bytes);

    List<int> messageBytes = utf8.encode(data);
    var code = hmacSha256.convert(messageBytes).bytes; // the problem starting here the result of code function is different comparing with hmacsha256.ComputeHash(messageBytes)
    print(base64Encode(code));
  }

注意:我正在使用加密 package

【问题讨论】:

  • 对于我们这些没有 C# 开发工具的人来说,提供示例输入和所需输出的示例可能会有所帮助。

标签: c# asp.net flutter dart hash


【解决方案1】:

我遇到了类似的问题...我的问题是密钥的编码方式。我原来的 C# 服务正在使用“Convert.FromBase64String”...解决方案是:

C#

var secretKeyByteArray = Convert.FromBase64String(_secretKey);

            byte[] signature = Encoding.UTF8.GetBytes(signatureRawData);

            using (HMACSHA256 hmac = new HMACSHA256(secretKeyByteArray))
            {
                byte[] signatureBytes = hmac.ComputeHash(signature);
                string requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
                //Setting the values in the Authorization header using custom scheme (amx)
                request.Headers.Authorization = new AuthenticationHeaderValue("hmac", string.Format("{0}:{1}:{2}:{3}", _applicationId, requestSignatureBase64String, nonce, requestTimeStamp));
        }

飞镖:

final keyBytes = base64Decode(key);
  final dataBytes = utf8.encode(data);

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

  return hmacBase64;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-26
    • 2019-03-16
    • 2013-06-18
    • 1970-01-01
    • 2016-07-22
    • 2014-05-02
    • 2019-07-29
    • 2021-12-03
    相关资源
    最近更新 更多