Skip to content

Commit

Permalink
Merge pull request #43 from microsoft/pbkdf2panic
Browse files Browse the repository at this point in the history
Avoid panic with empty salt in PBKDF2
  • Loading branch information
qmuntal authored Sep 8, 2023
2 parents f1f4385 + e46dab1 commit 892faa6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
21 changes: 12 additions & 9 deletions cng/pbkdf2.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,25 @@ func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) ([]byte
}
defer bcrypt.DestroyKey(kh)
u16HashID := utf16FromString(hashID)
buffers := [...]bcrypt.Buffer{
{
buffers := make([]bcrypt.Buffer, 0, 3)
buffers = append(buffers,
bcrypt.Buffer{
Type: bcrypt.KDF_ITERATION_COUNT,
Data: uintptr(unsafe.Pointer(&iter)),
Length: 8,
},
{
Type: bcrypt.KDF_SALT,
Data: uintptr(unsafe.Pointer(&salt[0])),
Length: uint32(len(salt)),
},
{
bcrypt.Buffer{
Type: bcrypt.KDF_HASH_ALGORITHM,
Data: uintptr(unsafe.Pointer(&u16HashID[0])),
Length: uint32(len(u16HashID) * 2),
},
})
if len(salt) > 0 {
// The salt is optional.
buffers = append(buffers, bcrypt.Buffer{
Type: bcrypt.KDF_SALT,
Data: uintptr(unsafe.Pointer(&salt[0])),
Length: uint32(len(salt)),
})
}
params := &bcrypt.BufferDesc{
Count: uint32(len(buffers)),
Expand Down
15 changes: 15 additions & 0 deletions cng/pbkdf2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,21 @@ func TestWithHMACSHA256(t *testing.T) {
testHash(t, cng.NewSHA256, "SHA256", sha256TestVectors)
}

func TestPBKDF2NoSalt(t *testing.T) {
vectors := []testVector{
{
"pass\000word",
"",
4096,
[]byte{
0x65, 0x6b, 0xbf, 0xf8, 0xdb, 0x07, 0x95, 0x8b,
0x1c, 0xfe, 0x17, 0x80, 0x16, 0xa0, 0x4d, 0x62,
},
},
}
testHash(t, cng.NewSHA256, "SHA256", vectors)
}

var sink uint8

func benchmark(b *testing.B, h func() hash.Hash) {
Expand Down

0 comments on commit 892faa6

Please sign in to comment.