Skip to content

Commit

Permalink
Replace fmt.Sprintf with hex.EncodeToString (#21960)
Browse files Browse the repository at this point in the history
`hex.EncodeToString` has better performance than `fmt.Sprintf("%x",
[]byte)`, we should use it as much as possible.

I'm not an extreme fan of performance, so I think there are some
exceptions:

- `fmt.Sprintf("%x", func(...)[N]byte())`
- We can't slice the function return value directly, and it's not worth
adding lines.
    ```diff
    func A()[20]byte { ... }
    - a := fmt.Sprintf("%x", A())
    - a := hex.EncodeToString(A()[:]) // invalid
    + tmp := A()
    + a := hex.EncodeToString(tmp[:])
    ```
- `fmt.Sprintf("%X", []byte)`
- `strings.ToUpper(hex.EncodeToString(bytes))` has even worse
performance.
  • Loading branch information
wolfogre authored Nov 28, 2022
1 parent e81ccc4 commit 9607750
Show file tree
Hide file tree
Showing 9 changed files with 30 additions and 28 deletions.
3 changes: 2 additions & 1 deletion models/auth/twofactor.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"crypto/subtle"
"encoding/base32"
"encoding/base64"
"encoding/hex"
"fmt"

"code.gitea.io/gitea/models/db"
Expand Down Expand Up @@ -78,7 +79,7 @@ func (t *TwoFactor) GenerateScratchToken() (string, error) {
// HashToken return the hashable salt
func HashToken(token, salt string) string {
tempHash := pbkdf2.Key([]byte(token), []byte(salt), 10000, 50, sha256.New)
return fmt.Sprintf("%x", tempHash)
return hex.EncodeToString(tempHash)
}

// VerifyScratchToken verifies if the specified scratch token is valid.
Expand Down
4 changes: 2 additions & 2 deletions models/migrations/base/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ package base

import (
"crypto/sha256"
"fmt"
"encoding/hex"

"golang.org/x/crypto/pbkdf2"
)

func HashToken(token, salt string) string {
tempHash := pbkdf2.Key([]byte(token), []byte(salt), 10000, 50, sha256.New)
return fmt.Sprintf("%x", tempHash)
return hex.EncodeToString(tempHash)
}
4 changes: 2 additions & 2 deletions models/migrations/v1_14/v166.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package v1_14 //nolint

import (
"crypto/sha256"
"fmt"
"encoding/hex"

"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
Expand Down Expand Up @@ -53,7 +53,7 @@ func RecalculateUserEmptyPWD(x *xorm.Engine) (err error) {
tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
}

return fmt.Sprintf("%x", tempPasswd)
return hex.EncodeToString(tempPasswd)
}

// ValidatePassword checks if given password matches the one belongs to the user.
Expand Down
2 changes: 1 addition & 1 deletion models/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ func hashPassword(passwd, salt, algo string) (string, error) {
tempPasswd = pbkdf2.Key([]byte(passwd), saltBytes, 10000, 50, sha256.New)
}

return fmt.Sprintf("%x", tempPasswd), nil
return hex.EncodeToString(tempPasswd), nil
}

// SetPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO
Expand Down
10 changes: 5 additions & 5 deletions modules/packages/hashed_buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
package packages

import (
"fmt"
"encoding/hex"
"io"
"strings"
"testing"
Expand Down Expand Up @@ -36,10 +36,10 @@ func TestHashedBuffer(t *testing.T) {
assert.Equal(t, c.Data, string(data))

hashMD5, hashSHA1, hashSHA256, hashSHA512 := buf.Sums()
assert.Equal(t, c.HashMD5, fmt.Sprintf("%x", hashMD5))
assert.Equal(t, c.HashSHA1, fmt.Sprintf("%x", hashSHA1))
assert.Equal(t, c.HashSHA256, fmt.Sprintf("%x", hashSHA256))
assert.Equal(t, c.HashSHA512, fmt.Sprintf("%x", hashSHA512))
assert.Equal(t, c.HashMD5, hex.EncodeToString(hashMD5))
assert.Equal(t, c.HashSHA1, hex.EncodeToString(hashSHA1))
assert.Equal(t, c.HashSHA256, hex.EncodeToString(hashSHA256))
assert.Equal(t, c.HashSHA512, hex.EncodeToString(hashSHA512))

assert.NoError(t, buf.Close())
}
Expand Down
18 changes: 9 additions & 9 deletions modules/packages/multi_hasher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
package packages

import (
"fmt"
"encoding/hex"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -24,10 +24,10 @@ func TestMultiHasherSums(t *testing.T) {

hashMD5, hashSHA1, hashSHA256, hashSHA512 := h.Sums()

assert.Equal(t, expectedMD5, fmt.Sprintf("%x", hashMD5))
assert.Equal(t, expectedSHA1, fmt.Sprintf("%x", hashSHA1))
assert.Equal(t, expectedSHA256, fmt.Sprintf("%x", hashSHA256))
assert.Equal(t, expectedSHA512, fmt.Sprintf("%x", hashSHA512))
assert.Equal(t, expectedMD5, hex.EncodeToString(hashMD5))
assert.Equal(t, expectedSHA1, hex.EncodeToString(hashSHA1))
assert.Equal(t, expectedSHA256, hex.EncodeToString(hashSHA256))
assert.Equal(t, expectedSHA512, hex.EncodeToString(hashSHA512))
})

t.Run("State", func(t *testing.T) {
Expand All @@ -45,9 +45,9 @@ func TestMultiHasherSums(t *testing.T) {

hashMD5, hashSHA1, hashSHA256, hashSHA512 := h2.Sums()

assert.Equal(t, expectedMD5, fmt.Sprintf("%x", hashMD5))
assert.Equal(t, expectedSHA1, fmt.Sprintf("%x", hashSHA1))
assert.Equal(t, expectedSHA256, fmt.Sprintf("%x", hashSHA256))
assert.Equal(t, expectedSHA512, fmt.Sprintf("%x", hashSHA512))
assert.Equal(t, expectedMD5, hex.EncodeToString(hashMD5))
assert.Equal(t, expectedSHA1, hex.EncodeToString(hashSHA1))
assert.Equal(t, expectedSHA256, hex.EncodeToString(hashSHA256))
assert.Equal(t, expectedSHA512, hex.EncodeToString(hashSHA512))
})
}
4 changes: 2 additions & 2 deletions routers/api/packages/maven/maven.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import (
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"path/filepath"
Expand Down Expand Up @@ -128,7 +128,7 @@ func serveMavenMetadata(ctx *context.Context, params parameters) {
tmp := sha512.Sum512(xmlMetadataWithHeader)
hash = tmp[:]
}
ctx.PlainText(http.StatusOK, fmt.Sprintf("%x", hash))
ctx.PlainText(http.StatusOK, hex.EncodeToString(hash))
return
}

Expand Down
4 changes: 2 additions & 2 deletions routers/api/packages/pypi/pypi.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
package pypi

import (
"fmt"
"encoding/hex"
"io"
"net/http"
"regexp"
Expand Down Expand Up @@ -118,7 +118,7 @@ func UploadPackageFile(ctx *context.Context) {

_, _, hashSHA256, _ := buf.Sums()

if !strings.EqualFold(ctx.Req.FormValue("sha256_digest"), fmt.Sprintf("%x", hashSHA256)) {
if !strings.EqualFold(ctx.Req.FormValue("sha256_digest"), hex.EncodeToString(hashSHA256)) {
apiError(ctx, http.StatusBadRequest, "hash mismatch")
return
}
Expand Down
9 changes: 5 additions & 4 deletions services/packages/packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package packages

import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -229,10 +230,10 @@ func NewPackageBlob(hsr packages_module.HashedSizeReader) *packages_model.Packag

return &packages_model.PackageBlob{
Size: hsr.Size(),
HashMD5: fmt.Sprintf("%x", hashMD5),
HashSHA1: fmt.Sprintf("%x", hashSHA1),
HashSHA256: fmt.Sprintf("%x", hashSHA256),
HashSHA512: fmt.Sprintf("%x", hashSHA512),
HashMD5: hex.EncodeToString(hashMD5),
HashSHA1: hex.EncodeToString(hashSHA1),
HashSHA256: hex.EncodeToString(hashSHA256),
HashSHA512: hex.EncodeToString(hashSHA512),
}
}

Expand Down

0 comments on commit 9607750

Please sign in to comment.