首页 > 解决方案 > Java 到 C#:从文档哈希计算代码

问题描述

我有 Java 代码示例,说明应如何计算验证码。而且我必须将 Java 代码转换为 C#。

首先,代码计算为:

integer(SHA256(hash)[-2: -1]) mod 10000

在我们获取 SHA256 结果的地方,从中提取最右边的 2 个字节,将它们解释为大端无符号整数,并取十进制的最后 4 位数字进行显示。

Java代码:

public static String calculate(byte[] documentHash) {
    byte[] digest = DigestCalculator.calculateDigest(documentHash, HashType.SHA256);
    ByteBuffer byteBuffer = ByteBuffer.wrap(digest);
    int shortBytes = Short.SIZE / Byte.SIZE; // Short.BYTES in java 8
    int rightMostBytesIndex = byteBuffer.limit() - shortBytes;
    short twoRightmostBytes = byteBuffer.getShort(rightMostBytesIndex);
    int positiveInteger = ((int) twoRightmostBytes) & 0xffff;
    String code = String.valueOf(positiveInteger);
    String paddedCode = "0000" + code;
    return paddedCode.substring(code.length());
  }

public static byte[] calculateDigest(byte[] dataToDigest, HashType hashType) {
    String algorithmName = hashType.getAlgorithmName();
    return DigestUtils.getDigest(algorithmName).digest(dataToDigest);
  }

所以来自 Base64 字符串的 int C#: 2afAxT+nH5qNYrfM+D7F6cKAaCKLLA23pj8ro3SksqwsdwmC3xTndKJotewzu7HlDy/DiqgkR+HXBiA0sW1x0Q==

应计算代码等于:3676

任何想法如何实现这一点?

标签: c#algorithmsha256

解决方案


class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetCode("2afAxT+nH5qNYrfM+D7F6cKAaCKLLA23pj8ro3SksqwsdwmC3xTndKJotewzu7HlDy/DiqgkR+HXBiA0sW1x0Q=="));
    }


    public static string GetCode(string str)
    {
        var sha = System.Security.Cryptography.SHA256.Create();
        var hash = sha.ComputeHash(Convert.FromBase64String(str));
        var last2 = hash[^2..];
        var intVal = ((int) last2[0]) * 0x0100 + ((int) last2[1]);
        var digits = intVal % 10000;
        return $"{digits:0000}";            
    }
}

推荐阅读