【问题标题】:Java to C#: code computing from document hashJava 到 C#:从文档哈希计算代码
【发布时间】:2020-05-11 20:12:17
【问题描述】:

我有 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# algorithm sha256


    【解决方案1】:
    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}";            
        }
    }
    

    【讨论】:

    • VS2017 及更早版本(可能低至 VS2013)的用户可以将行 var last2 = hash[^2..]; 替换为 var last2 = hash.Skip(hash.Length - 2).ToArray();
    猜你喜欢
    • 2018-07-14
    • 2017-02-04
    • 2011-12-08
    • 1970-01-01
    • 2011-02-26
    • 2016-06-23
    • 2011-10-14
    • 2012-03-28
    • 2010-09-11
    相关资源
    最近更新 更多