Skip to content

Commit

Permalink
Truncating passwords that are longer than 72 bytes (#396)
Browse files Browse the repository at this point in the history
  • Loading branch information
bendbennett committed Apr 12, 2023
1 parent 800bbd5 commit d39f07a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
15 changes: 14 additions & 1 deletion internal/provider/resource_password.go
Original file line number Diff line number Diff line change
Expand Up @@ -535,8 +535,21 @@ func upgradePasswordStateV2toV3(ctx context.Context, req resource.UpgradeStateRe
resp.Diagnostics.Append(resp.State.Set(ctx, passwordDataV3)...)
}

// generateHash truncates strings that are longer than 72 bytes in
// order to avoid the error returned from bcrypt.GenerateFromPassword
// in versions v0.5.0 and above (refer to
// https://pkg.go.dev/golang.org/x/crypto/bcrypt?tab=versions).
// This is to preserve backwards compatibility and will be removed in
// a subsequent version of the provider.
func generateHash(toHash string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(toHash), bcrypt.DefaultCost)
bytesHash := []byte(toHash)
bytesToHash := bytesHash

if len(bytesHash) > 72 {
bytesToHash = bytesHash[:72]
}

hash, err := bcrypt.GenerateFromPassword(bytesToHash, bcrypt.DefaultCost)

return string(hash), err
}
Expand Down
4 changes: 2 additions & 2 deletions internal/provider/resource_password_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func TestGenerateHash(t *testing.T) {
}{
"defaults": {
input: random.StringParams{
Length: 32, // Required
Length: 73, // Required
Lower: true,
Numeric: true,
Special: true,
Expand Down Expand Up @@ -111,7 +111,7 @@ func TestAccResourcePassword_BcryptHash(t *testing.T) {
Steps: []resource.TestStep{
{
Config: `resource "random_password" "test" {
length = 12
length = 73
}`,
Check: resource.ComposeTestCheckFunc(
testExtractResourceAttr("random_password.test", "bcrypt_hash", &bcryptHash),
Expand Down

0 comments on commit d39f07a

Please sign in to comment.