Debian Codegraph @

pkg/crypto/hash.go

raw
1 package crypto
2
3 import (
4 "crypto/sha256"
5 "crypto/sha512"
6 "encoding/base64"
7 "errors"
8 "fmt"
9 "hash"
10
11 jose "github.com/go-jose/go-jose/v4"
12 )
13
14 var ErrUnsupportedAlgorithm = errors.New("unsupported signing algorithm")
15
16 func GetHashAlgorithm(sigAlgorithm jose.SignatureAlgorithm) (hash.Hash, error) {
17 switch sigAlgorithm {
18 case jose.RS256, jose.ES256, jose.PS256:
19 return sha256.New(), nil
20 case jose.RS384, jose.ES384, jose.PS384:
21 return sha512.New384(), nil
22 case jose.RS512, jose.ES512, jose.PS512:
23 return sha512.New(), nil
24
25 // There is no published spec for this yet, but we have confirmation it will get published.
26 // There is consensus here: https://bitbucket.org/openid/connect/issues/1125/_hash-algorithm-for-eddsa-id-tokens
27 // Currently Go and go-jose only supports the ed25519 curve key for EdDSA, so we can safely assume sha512 here.
28 // It is unlikely ed448 will ever be supported: https://github.com/golang/go/issues/29390
29 case jose.EdDSA:
30 return sha512.New(), nil
31
32 default:
33 return nil, fmt.Errorf("%w: %q", ErrUnsupportedAlgorithm, sigAlgorithm)
34 }
35 }
36
37 func HashString(hash hash.Hash, s string, firstHalf bool) string {
38 if hash == nil {
39 return s
40 }
41 //nolint:errcheck
42 hash.Write([]byte(s))
43 size := hash.Size()
44 if firstHalf {
45 size = size / 2
46 }
47 sum := hash.Sum(nil)[:size]
48 return base64.RawURLEncoding.EncodeToString(sum)
49 }