Skip to content

Commit

Permalink
Merge pull request #35 from kloeckner-i/METAL-2104/colliding_hash
Browse files Browse the repository at this point in the history
METAL-2104 change hash call, to get only hash value for func return
  • Loading branch information
dabde authored Jul 24, 2020
2 parents aab4b87 + d5d72ad commit 095b4e9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
6 changes: 4 additions & 2 deletions pkg/utils/kci/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ func StringSanitize(s string, limit int) string {
return s
}

hash := fmt.Sprintf("%x", sha256.Sum256([]byte(s)))

if limit <= 9 {
return fmt.Sprintf("%x", sha256.New().Sum([]byte(s)))[:limit]
return hash[:limit]
}

return fmt.Sprintf("%s_%x", s[:limit-9], sha256.New().Sum([]byte(s))[:4])
return fmt.Sprintf("%s_%s", s[:limit-9], hash[:8])
}
9 changes: 7 additions & 2 deletions pkg/utils/kci/database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ func TestStringSanitize(t *testing.T) {
// Handles very short limits
src := "HelloWorld"
actual := StringSanitize(src, 6)
assert.Equal(t, "68656c", actual)
assert.Equal(t, "936a18", actual)

// Sanitizes successfully
src = "Hello**World$"
Expand All @@ -19,5 +19,10 @@ func TestStringSanitize(t *testing.T) {
// Truncates very long values
src = "The quick brown fox jumps over the lazy dog"
actual = StringSanitize(src, 32)
assert.Equal(t, "the_quick_brown_fox_jum_7468655f", actual)
assert.Equal(t, "the_quick_brown_fox_jum_19e1ae50", actual)

// Truncates very long values, avoid hash collision
src = "The quick brown fox jumps over the lazy cat"
actual = StringSanitize(src, 32)
assert.NotEqual(t, "the_quick_brown_fox_jum_19e1ae50", actual)
}

0 comments on commit 095b4e9

Please sign in to comment.