【发布时间】:2026-02-06 12:35:01
【问题描述】:
我需要将 Java 中完成的某些加密逻辑转换为 C#
MessageDigest update、Digest 和 reset 函数的 C# 等效项是什么?
【问题讨论】:
标签: c# encryption
我需要将 Java 中完成的某些加密逻辑转换为 C#
MessageDigest update、Digest 和 reset 函数的 C# 等效项是什么?
【问题讨论】:
标签: c# encryption
在 C# 中,类是 HashAlgorithm。
等效于更新的是TransformBlock(...) 或TransformFinalBlock(...),在调用最终块版本后(您也可以使用空输入)您可以调用Hash 属性,该属性将为您提供摘要值。
HashAlgorithm 可能在调用最终块后可重用(这意味着它会在您下次调用 TransformBlock 时重置),您可以通过检查属性来仔细检查您的 HashAlgorithm 是否支持重用CanReuseTransform.
相当于您的 reset()/digest() 组合是一行 byte[] ComputeHash(byte[])。
【讨论】:
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(password.getBytes());
BigInteger hash = new BigInteger(1, md.digest());
hashword = hash.toString(16);
} catch (NoSuchAlgorithmException ex) {
/* error handling */
}
return hashword;
public static string HashPassword(string input)
{
var sha1 = SHA1Managed.Create();
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
byte[] outputBytes = sha1.ComputeHash(inputBytes);
return BitConverter.ToString(outputBytes).Replace("-", "").ToLower();
}
【讨论】:
对于 C# 中的摘要,类似于 Java,您可以使用类 Windows.Security.Cryptography.Core。例如,以下方法返回一个 SHA256 哈希,格式为 base64:
public static string sha256Hash(string data)
{
// create buffer and specify encoding format (here utf8)
IBuffer input = CryptographicBuffer.ConvertStringToBinary(data,
BinaryStringEncoding.Utf8);
// select algorithm
var hasher = HashAlgorithmProvider.OpenAlgorithm("SHA256");
IBuffer hashed = hasher.HashData(input);
// return hash in base64 format
return CryptographicBuffer.EncodeToBase64String(hashed);
}
【讨论】: