ccruiの博客

ccruiの博客

C# Java Argon2加密工具类

10
2023-04-21

C# Argon2加密

NuGet包管理器

dotnet add package Konscious.Security.Cryptography.Argon2 --version 1.3.0

C#工具类

using System;
using System.Text;
using System.Security.Cryptography;
using Konscious.Security.Cryptography;

/// <summary>
/// Argon2加密
/// </summary>
public class Argon2Hasher
{
    /// <summary>
    /// 给密码加密
    /// </summary>
    /// <param name="password"></param>
    /// <param name="salt"></param>
    /// <returns></returns>
    public static string HashPassword(string password, string salt)
    {
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

        using (var hasher = new Argon2id(Encoding.UTF8.GetBytes(password)))
        {
            hasher.Salt = saltBytes;
            hasher.DegreeOfParallelism = 8; // 根据您的硬件设置
            hasher.MemorySize = 65536; // 64 MB
            hasher.Iterations = 4;

            byte[] hashBytes = hasher.GetBytes(32); // 获取32字节的哈希值

            return Convert.ToBase64String(hashBytes);
        }
    }

    /// <summary>
    /// 验证密码
    /// </summary>
    /// <param name="password"></param>
    /// <param name="storedHash"></param>
    /// <param name="salt"></param>
    /// <returns></returns>
    public static bool VerifyPassword(string password, string storedHash, string salt)
    {
        string hashToVerify = HashPassword(password, salt);
        return storedHash.Equals(hashToVerify);
    }
}

Java Argon2加密

Maven 管理器

<dependency>
  <groupId>de.mkammerer.argon2</groupId>
  <artifactId>argon2-jvm</artifactId>
</dependency>

Java工具类

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import de.mkammerer.argon2.Argon2;
import de.mkammerer.argon2.Argon2Factory;

public class Argon2Hasher {

    /**
     * 给密码加密
     *
     * @param password
     * @param salt
     * @return
     */
    public static String hashPassword(String password, String salt) {
        Argon2 argon2 = Argon2Factory.create(Argon2Factory.Argon2Types.ARGON2id);
        char[] passwordChars = password.toCharArray();
        byte[] saltBytes = salt.getBytes(StandardCharsets.UTF_8);

        try {
            byte[] hashBytes = argon2.hashRaw(4, 65536, 8, passwordChars, saltBytes);
            return Base64.getEncoder().encodeToString(hashBytes);
        } finally {
            argon2.wipeArray(passwordChars);
        }
    }

    /**
     * 验证密码
     *
     * @param password
     * @param storedHash
     * @param salt
     * @return
     */
    public static boolean verifyPassword(String password, String storedHash, String salt) {
        String hashToVerify = hashPassword(password, salt);
        return storedHash.equals(hashToVerify);
    }
}