hash.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package libtrust
  2. import (
  3. "crypto"
  4. _ "crypto/sha256" // Registrer SHA224 and SHA256
  5. _ "crypto/sha512" // Registrer SHA384 and SHA512
  6. "fmt"
  7. )
  8. type signatureAlgorithm struct {
  9. algHeaderParam string
  10. hashID crypto.Hash
  11. }
  12. func (h *signatureAlgorithm) HeaderParam() string {
  13. return h.algHeaderParam
  14. }
  15. func (h *signatureAlgorithm) HashID() crypto.Hash {
  16. return h.hashID
  17. }
  18. var (
  19. rs256 = &signatureAlgorithm{"RS256", crypto.SHA256}
  20. rs384 = &signatureAlgorithm{"RS384", crypto.SHA384}
  21. rs512 = &signatureAlgorithm{"RS512", crypto.SHA512}
  22. es256 = &signatureAlgorithm{"ES256", crypto.SHA256}
  23. es384 = &signatureAlgorithm{"ES384", crypto.SHA384}
  24. es512 = &signatureAlgorithm{"ES512", crypto.SHA512}
  25. )
  26. func rsaSignatureAlgorithmByName(alg string) (*signatureAlgorithm, error) {
  27. switch {
  28. case alg == "RS256":
  29. return rs256, nil
  30. case alg == "RS384":
  31. return rs384, nil
  32. case alg == "RS512":
  33. return rs512, nil
  34. default:
  35. return nil, fmt.Errorf("RSA Digital Signature Algorithm %q not supported", alg)
  36. }
  37. }
  38. func rsaPKCS1v15SignatureAlgorithmForHashID(hashID crypto.Hash) *signatureAlgorithm {
  39. switch {
  40. case hashID == crypto.SHA512:
  41. return rs512
  42. case hashID == crypto.SHA384:
  43. return rs384
  44. case hashID == crypto.SHA256:
  45. fallthrough
  46. default:
  47. return rs256
  48. }
  49. }