Java到C#:从文档哈希计算代码

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

首先,代码计算为:

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

在我们获取SHA256结果的位置,从中提取2个最右边的字节,将它们解释为big-endian无符号整数,并以十进制的最后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);
  }

So int C# from Base64 string: 2afAxT+nH5qNYrfM+D7F6cKAaCKLLA23pj8ro3SksqwsdwmC3xTndKJotewzu7HlDy/DiqgkR+HXBiA0sW1x0Q==

should compute code equal to: 3676

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

评论