對密碼的加密

 

翻閱一開源項目中,發現對密碼的相關操作.

最開始 , 一般 用 密碼->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  存在數據裏面.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章