c# - 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
任何想法如何实现这一点?
解决方案
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}";
}
}
推荐阅读
- c# - 从文本框中读取 sql 字符串并在 datagridview 中显示
- php - 在laravel中将数组转换为对象
- python - 名称错误:使用函数时未定义名称“x”
- hadoop - 如果在 impala statestore 关闭时执行 DDL,为什么 Impala 查询会失败?
- c# - 将 MP3 转换为文件大小较小的 WAV
- xml - 使用 xquery 或 XSLT v 1.0 读取 XML 文档中的命名空间
- scala - 如何使用索引执行 EitherT[Future, Failure, Iterator[A]] 映射
- api - 我想在 API Connect 中创建一个 API 来修改请求标头
- android - 如何在项目回收器视图中设置宽度 webview 包装内容
- react-native - 平面列表未显示(反应原生)