.Net实现SCrypt Hash加密

方案1 (加密后存储"算法设置"、"盐(随机值)"、"Hash值",以"$"分隔):

//Nuget引入SCrypt.NET库

using Org.BouncyCastle.Crypto.Generators;

using Scrypt;

using System;

using System.Security.Cryptography;

namespace XXX.Common.Helpers;

public static class SCryptHelper

{

//该库的SCrypt加密会得到包含"算法设置、盐(是个随机数)、Hash"一起的值,并以"$"分隔

//由于每次盐是随机产生的,所以每次对同一明文加密得到的值并不相同,

//但由于加密后的信息存储了算法设置及盐信息,所以Compare方法中可以利用这些信息再次对明文进行运算而得到相同的Hash值进行匹配

public static string Encrypt(string password)

{

ScryptEncoder encoder = new ScryptEncoder();

return encoder.Encode(password); //得到包含"算法设置、盐(是个随机数)、Hash"一起的值,并以"$"分隔

}

public static bool Verify(string password, string hashedPassword)

{

ScryptEncoder encoder = new ScryptEncoder();

bool areEquals = encoder.Compare(password, hashedPassword);

return areEquals;

}

}

//该方案采用的即是以下存储方案(由于Salt是随机的,因此需要保存起来):

//以下来自:https://cryptobook.nakov.com/mac-and-key-derivation/scrypt


方案2 (加密后只存储"Hash值"):

//Nuget引入SCrypt库

using CryptSharp.Utility;

using System;

using System.Text;

namespace XXX.Common.Helpers;

public static class SCryptHelper

{

//该方案使用Scrypt库自己设置加密参数,

//由于使用固定的"算法设置"、并可以传入相同的参数值作为"盐",

//因此无需存储算法设置和盐信息,加密后只得到加密参数中指定长度的Hash值,

public static string Encrypt(string password, string salt)

{

byte\[\] saltArray = Encoding.UTF8.GetBytes(salt);

byte\[\] result = SCrypt.ComputeDerivedKey(Encoding.UTF8.GetBytes(password), saltArray, 256, 8, 1, 2, 32);

//参数: key,salt,cpuCost,memoryBlockSize,parallel,maxThreads,derivedKeyLength),

//详见以下SCrypt.ComputeDerivedKey方法说明截图

string hashResult = BitConverter.ToString(result).Replace("-", "").ToLower();

return hashResult; //返回hashResult长度为64(32*2,即以上参数指定的32字节并以每字节2位的16进制表示)

}

public static bool Verify(string password, string salt, string hashedPassword)

{

var hash = Encrypt(password, salt);

return hash.Equals(hashedPassword, StringComparison.OrdinalIgnoreCase);

}

}

//该方案加密后只返加Hash值,只需存储该Hash值,每次用相同的Salt计算后匹对

//以下来自:https://8gwifi.org/scrypt.jsp

SCrypt.ComputeDerivedKey方法说明:

参考:

相关知识(过往相关博文):

相关推荐
电科_银尘11 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴15 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David15 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
Pniubi18 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK18 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
上海潭龙东海科技有限公司19 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
阿庆_AI研发工程师21 小时前
Stanford CS336 Lecture 10:大语言模型推理与性能优化
算法
用户7341681035481 天前
基于MindSpore的深度残差收缩网络程序
算法
Pniubi1 天前
力扣239.滑动窗口最大值(优先队列)
算法·leetcode·职场和发展
青少儿编程课堂1 天前
第十八届蓝桥杯青少组图形化真题 + 全国青少年信息素养大赛 + 电子学会图形化考级:校园泡泡堂大挑战解析
c++·python·算法·bfs·信息学竞赛