You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Excel VBA字符串哈希函数转换为输出一致的等效C#代码

C# 与VBA逻辑完全对齐的HMACSHA1哈希实现

对齐规则说明

原VBA函数没有自定义特殊逻辑,全部调用Windows系统标准加密、编码组件,C# 内置类库可直接1:1复现,需严格匹配的规则如下:

  • 字符串转字节数组统一使用UTF-8编码,和VBA中System.Text.UTF8Encoding的行为完全一致
  • 密钥默认逻辑:如果传入的可选密钥参数为空,直接将输入文本本身作为HMAC计算的密钥
  • 哈希算法采用标准HMACSHA1,计算时传入的原始字节数组不需要额外转码、补位处理
  • 哈希结果直接转标准Base64字符串返回,和VBA中MSXML组件bin.base64的编码结果完全匹配,不需要做换行符处理、字符替换等额外操作

实现代码

using System;
using System.Security.Cryptography;
using System.Text;

public static class VbaCompatibleHash
{
    public static string HashString(string inputText, string secretKey = "")
    {
        if (secretKey == "")
        {
            secretKey = inputText;
        }

        byte[] inputBytes = Encoding.UTF8.GetBytes(inputText);
        byte[] keyBytes = Encoding.UTF8.GetBytes(secretKey);

        using (var hmacSha1 = new HMACSHA1(keyBytes))
        {
            byte[] hashResult = hmacSha1.ComputeHash(inputBytes);
            return Convert.ToBase64String(hashResult);
        }
    }
}

验证方式:取相同入参分别在VBA和C#环境调用即可,例如传入待哈希文本为test、不传入自定义密钥,两端返回结果完全一致,不存在计算偏差。

内容的提问来源于stack exchange,提问作者abdol-hamid Hosseiny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 09:54:25