【发布时间】: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
有什么想法可以实现吗?
【问题讨论】: