对密码的加密
翻阅一开源项目中,发现对密码的相关操作.
最开始 , 一般 用 密码->md5 存储. 后来发现md5可以撞库,后来就有听说腾讯的加密方式是md5 26次,然后反转序列再 md5 2次... (道听途说的)
也有用 密码+固定salt 进行md5的, 还有一种是 动态salt+密码->md5 ,这种就是要多存一个 sal 到数据库.
下面介绍另外一种类似的
1.生成随机salt
public static string GenerateSalt()
{
// Generate a 128-bit salt using a sequence of cryptographically strong random bytes.
byte[] salt = RandomNumberGenerator.GetBytes(128 / 8); // divide by 8 to convert bits to bytes
return Convert.ToBase64String(salt);
}
2.对密码进行加密
/*需要引入命名空间
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.AspNetCore.Http;*/
// https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/password-hashing?view=aspnetcore-6.0
// This is not secure, but better than nothing.
public static string HashPassword2(string clearPassword, string saltBase64)
{
var salt = Convert.FromBase64String(saltBase64);
// derive a 256-bit subkey (use HMACSHA256 with 100,000 iterations)
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: clearPassword!,
salt: salt,
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8));
return hashed;
}
3.调用示例
string pwd = "admin123.";
string salt = Helper.GenerateSalt();
var hash = Helper.HashPassword2(pwd , salt);
然后把 用户名,salt 和 hash 存在数据里面.
本文来自博客园,作者:兴想事成,转载请注明原文链接:https://www.cnblogs.com/mjxxsc/p/17624568.html