全面的 .NET Core Argon2 加密实现教程
项目介绍
Argon2 是一种优化用于生成适合凭证存储、密钥派生或其他需要加密安全密码散列情况的散列生成器。Argon2 在 2015 年的密码散列竞赛中获胜。这个完全托管的 Argon2 实现在 .NET Core、.NET Framework 或 WebAssembly(通过 Blazor 或 Uno Platform)上运行。
本项目是一个完全托管代码的库,使得您可以在任何 .NET(包括 Blazor)应用程序中使用 Argon2 散列,而不需要增加额外的复杂性。
项目快速启动
安装
推荐使用 NuGet 包来开始使用:
Install-Package Isopoh.Cryptography.Argon2
您也可以克隆仓库并直接使用 .csproj 文件:
git clone https://github.com/mheyman/Isopoh.Cryptography.Argon2.git
然后在您的 .csproj 文件中添加以下项目引用:
<ItemGroup>
<ProjectReference Include="..\..\..\Isopoh.Cryptography.Argon2\Isopoh.Cryptography.SecureArray\Isopoh.Cryptography.SecureArray.csproj" />
<ProjectReference Include="..\..\..\Isopoh.Cryptography.Argon2\Isopoh.Cryptography.Blake2b\Isopoh.Cryptography.Blake2b.csproj" />
<ProjectReference Include="..\..\..\Isopoh.Cryptography.Argon2\Isopoh.Cryptography.Argon2.csproj" />
</ItemGroup>
使用
默认使用方式:
using Isopoh.Cryptography.Argon2;
var password = "password1";
var passwordHash = Argon2.Hash(password);
if (Argon2.Verify(passwordHash, password))
{
// 执行相关操作
}
设置所有选项:
using Isopoh.Cryptography.Argon2;
using Isopoh.Cryptography.SecureArray;
byte[] passwordBytes = "password1".ToCharArray().Select(c => (byte)c).ToArray();
byte[] secret = new byte[] { 0x6b, 0xc0, 0x19, 0x4c, 0x11, 0x46, 0x35, 0x69, 0x89, 0xd6, 0x50, 0x19, 0x56, 0xac, 0x69, 0x0e };
byte[] salt = new byte[16];
byte[] associatedData = "My Associated Data".ToCharArray().Select(c => (byte)c).ToArray();
new Random().NextBytes(salt);
var config = new Argon2Config
{
Type = Argon2Type.DataIndependentAddressing,
Version = Argon2Version.Nineteen,
TimeCost = 10,
MemoryCost = 32768,
Lanes = 5,
Threads = Environment.ProcessorCount,
Password = passwordBytes,
Salt = salt,
Secret = secret,
AssociatedData = associatedData,
HashLength = 20
};
var argon2A = new Argon2(config);
string hashString;
using (SecureArray<byte> hashA = argon2A.Hash())
{
hashString = config.EncodeString(hashA.Buffer);
}
// 假设 "passwordBytes" 是刚接收到的,需要验证 "hashString" 的有效性
var configOfPasswordToVerify = new Argon2Config
{
Password = passwordBytes,
Threads = 1
};
SecureArray<byte>? hashB = null;
try
{
if (configOfPasswordToVerify.DecodeString(hashString, out hashB) && hashB != null)
{
var argon2ToVerify = new Argon2(configOfPasswordToVerify);
using (SecureArray<byte>? hashToVerify = argon2ToVerify.Hash())
{
if (Argon2.FixedTimeEquals(hashB.Value.Buffer, hashToVerify.Value.Buffer))
{
// 验证成功
}
}
}
}
finally
{
hashB?.Dispose();
}
// 或者,更简单地(设置 "Threads" 为 "5")
if (Argon2.Verify(hashString, passwordBytes, 5))
{
// 验证成功
}
应用案例和最佳实践
- 当存储用户密码时,使用 Argon2 散列函数可以提供更高级别的安全性。
- 在密钥派生场景中使用 Argon2,以确保密钥的安全性。
var password = "userPassword";
var derivedKey = Argon2.Hash(password, salt: new byte[16], keyLength: 32);
典型生态项目
- Isopoh.Cryptography.Blake2b - 用于 Argon2 的底层哈希算法的实现。
- SecureArray - 用于内存安全处理的库。
以上就是 .NET Core Argon2 加密实现的详细教程,希望对您有所帮助。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



