github.com/lestrrat-go/jwx/v2@v2.0.21/jwa/jwa.go (about) 1 //go:generate ../tools/cmd/genjwa.sh 2 3 // Package jwa defines the various algorithm described in https://tools.ietf.org/html/rfc7518 4 package jwa 5 6 import "fmt" 7 8 // KeyAlgorithm is a workaround for jwk.Key being able to contain different 9 // types of algorithms in its `alg` field. 10 // 11 // Previously the storage for the `alg` field was represented as a string, 12 // but this caused some users to wonder why the field was not typed appropriately 13 // like other fields. 14 // 15 // Ideally we would like to keep track of Signature Algorithms and 16 // Content Encryption Algorithms separately, and force the APIs to 17 // type-check at compile time, but this allows users to pass a value from a 18 // jwk.Key directly 19 type KeyAlgorithm interface { 20 String() string 21 } 22 23 // InvalidKeyAlgorithm represents an algorithm that the library is not aware of. 24 type InvalidKeyAlgorithm string 25 26 func (s InvalidKeyAlgorithm) String() string { 27 return string(s) 28 } 29 30 func (InvalidKeyAlgorithm) Accept(_ interface{}) error { 31 return fmt.Errorf(`jwa.InvalidKeyAlgorithm does not support Accept() method calls`) 32 } 33 34 // KeyAlgorithmFrom takes either a string, `jwa.SignatureAlgorithm` or `jwa.KeyEncryptionAlgorithm` 35 // and returns a `jwa.KeyAlgorithm`. 36 // 37 // If the value cannot be handled, it returns an `jwa.InvalidKeyAlgorithm` 38 // object instead of returning an error. This design choice was made to allow 39 // users to directly pass the return value to functions such as `jws.Sign()` 40 func KeyAlgorithmFrom(v interface{}) KeyAlgorithm { 41 switch v := v.(type) { 42 case SignatureAlgorithm: 43 return v 44 case KeyEncryptionAlgorithm: 45 return v 46 case string: 47 var salg SignatureAlgorithm 48 if err := salg.Accept(v); err == nil { 49 return salg 50 } 51 52 var kealg KeyEncryptionAlgorithm 53 if err := kealg.Accept(v); err == nil { 54 return kealg 55 } 56 57 return InvalidKeyAlgorithm(v) 58 default: 59 return InvalidKeyAlgorithm(fmt.Sprintf("%s", v)) 60 } 61 }