github.com/Venafi/vcert/v5@v5.10.2/pkg/certificate/keyType.go (about) 1 package certificate 2 3 import ( 4 "crypto/x509" 5 "fmt" 6 "strings" 7 8 "gopkg.in/yaml.v3" 9 10 "github.com/Venafi/vcert/v5/pkg/verror" 11 ) 12 13 // KeyType represents the types of supported keys 14 type KeyType int 15 16 const ( 17 // KeyTypeRSA represents a key type of RSA 18 KeyTypeRSA KeyType = iota 19 // KeyTypeECDSA represents a key type of ECDSA 20 KeyTypeECDSA 21 // KeyTypeED25519 represents a key type of ED25519 22 KeyTypeED25519 23 24 // String representations of the KeyType types 25 strKeyTypeECDSA = "ECDSA" 26 strKeyTypeRSA = "RSA" 27 strKeyTypeED25519 = "ED25519" 28 ) 29 30 // String returns a string representation of this object 31 func (kt *KeyType) String() string { 32 switch *kt { 33 case KeyTypeRSA: 34 return strKeyTypeRSA 35 case KeyTypeECDSA: 36 return strKeyTypeECDSA 37 case KeyTypeED25519: 38 return strKeyTypeED25519 39 default: 40 return "" 41 } 42 } 43 44 func (kt *KeyType) X509Type() x509.PublicKeyAlgorithm { 45 switch *kt { 46 case KeyTypeRSA: 47 return x509.RSA 48 case KeyTypeECDSA: 49 return x509.ECDSA 50 case KeyTypeED25519: 51 return x509.Ed25519 52 } 53 return x509.UnknownPublicKeyAlgorithm 54 } 55 56 // Set the key type via a string 57 func (kt *KeyType) Set(value, curveValue string) error { 58 switch strings.ToUpper(value) { 59 case strKeyTypeRSA: 60 *kt = KeyTypeRSA 61 return nil 62 case strKeyTypeECDSA, "EC", "ECC": 63 curve := EllipticCurveNotSet 64 if err := curve.Set(curveValue); err != nil { 65 return err 66 } 67 if curve == EllipticCurveED25519 { 68 *kt = KeyTypeED25519 69 return nil 70 } 71 72 *kt = KeyTypeECDSA 73 return nil 74 } 75 return fmt.Errorf("%w: unknown key type: %s", verror.VcertError, value) //todo: check all calls 76 } 77 78 func parseKeyType(value string) (KeyType, error) { 79 switch strings.ToUpper(value) { 80 case strKeyTypeECDSA: 81 return KeyTypeECDSA, nil 82 case strKeyTypeRSA: 83 return KeyTypeRSA, nil 84 case strKeyTypeED25519: 85 return KeyTypeED25519, nil 86 default: 87 return -1, fmt.Errorf("%w: unknown key type: %s", verror.VcertError, value) 88 } 89 } 90 91 // MarshalYAML customizes the behavior of ChainOption when being marshaled into a YAML document. 92 // The returned value is marshaled in place of the original value implementing Marshaller 93 func (kt KeyType) MarshalYAML() (interface{}, error) { 94 return kt.String(), nil 95 } 96 97 // UnmarshalYAML customizes the behavior when being unmarshalled from a YAML document 98 func (kt *KeyType) UnmarshalYAML(value *yaml.Node) error { 99 var strValue string 100 err := value.Decode(&strValue) 101 if err != nil { 102 return err 103 } 104 *kt, err = parseKeyType(strValue) 105 if err != nil { 106 return err 107 } 108 return nil 109 }