Rfc2898 / PBKDF2 with SHA256 as digest in c#

前端 未结 8 2329
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 10:01

I want to use Rfc2898 in c# to derive a key. I also need to use SHA256 as Digest for Rfc2898. I found the class Rfc2898DeriveBytes, but it uses SHA-1 and I don\

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 10:52

    The BCL Rfc2898DeriveBytes is hardcoded to use sha-1.

    KeyDerivation.Pbkdf2 allows for exactly the same output, but it also allows HMAC SHA-256 and HMAC SHA-512. It's faster too; on my machine by around 5 times - and that's good for security, because it allows for more rounds, which makes life for crackers harder (incidentally sha-512 is a lot less gpu-friendly than sha-256 or sha1). And the api is simpler, to boot:

    byte[] salt = ...
    string password = ...
    var rounds = 50000;                       // pick something bearable
    var num_bytes_requested = 16;             // 128 bits is fine
    var prf = KeyDerivationPrf.HMACSHA512;    // or sha256, or sha1
    byte[] hashed = KeyDerivation.Pbkdf2(password, salt, prf, rounds, num_bytes_requested);
    

    It's from the nuget package Microsoft.AspNetCore.Cryptography.KeyDerivation which does not depend on asp.net core; it runs on .net 4.5.1 or .net standard 1.3 or higher.

提交回复
热议问题