How to determine number of characters that GetNonZeroBytes & Pbkdf2 will produce, so I can configure size of database field that will hold this value?

I am exploring cryptographic technique to create the salt and hash passwords.

Sample 1:

    // generate a 128-bit salt using a cryptographically strong random sequence of nonzero values
    byte[] pSalt = new byte[128 / 8];
    using (var rng = RandomNumberGenerator.Create())
    {
        rng.GetNonZeroBytes(pSalt);
    }                  
    
    string strSalt = Convert.ToBase64String(pSalt)

Sample 2:

    // derive a 256-bit subkey (use HMACSHA256 with 100,000 iterations)
    var pHash = KeyDerivation.Pbkdf2(
            password: password,
            salt: Convert.FromBase64String(pSalt),
            prf: KeyDerivationPrf.HMACSHA256,
            iterationCount: 100000,
            numBytesRequested: 256 / 8);

    string strHash = Convert.ToBase64String(pHash)

For both the strings (strSalt and strHash) from samples above, can we deterministically conclude the size (number of characters) in the final string?


Solution 1:

Base64 encodes 6 bits in one character, so to encode N bit, you need N/6 characters (round up if required).

The .NET method Convert.ToBase64String will append additional padding characters (=) to make the length a multiple of 4, so if you use this method, round up to the next multiple of 4.

Convert.ToBase64String(new byte[128/8]).Length will be 24.

Convert.ToBase64String(new byte[256/8]).Length will be 44.