Files
attest/signerverifier/parse.go

59 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-10-17 13:40:17 -05:00
/*
Copyright Docker attest authors
2024-10-17 13:40:17 -05:00
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2024-04-19 09:08:31 -05:00
package signerverifier
import (
"crypto"
2024-04-19 09:08:31 -05:00
"crypto/ecdsa"
"crypto/x509"
"encoding/pem"
"fmt"
)
const pemType = "PUBLIC KEY"
func ParsePublicKey(pubkeyBytes []byte) (crypto.PublicKey, error) {
2024-04-19 09:08:31 -05:00
p, _ := pem.Decode(pubkeyBytes)
if p == nil {
return nil, fmt.Errorf("pubkey file does not contain any PEM data")
}
if p.Type != pemType {
return nil, fmt.Errorf("pubkey file does not contain a public key")
}
return x509.ParsePKIXPublicKey(p.Bytes)
}
func ParseECDSAPublicKey(pubkeyBytes []byte) (*ecdsa.PublicKey, error) {
pk, err := ParsePublicKey(pubkeyBytes)
2024-04-19 09:08:31 -05:00
if err != nil {
return nil, err
2024-04-19 09:08:31 -05:00
}
ecdsaPubKey, ok := pk.(*ecdsa.PublicKey)
2024-04-19 09:08:31 -05:00
if !ok {
return nil, fmt.Errorf("error public key is not an ecdsa key: %w", err)
}
return ecdsaPubKey, nil
}
func ConvertToPEM(ecdsaPubKey *ecdsa.PublicKey) ([]byte, error) {
2024-04-19 09:08:31 -05:00
pubKeyBytes, err := x509.MarshalPKIXPublicKey(ecdsaPubKey)
if err != nil {
return nil, fmt.Errorf("error failed to marshal public key: %w", err)
}
return pem.EncodeToMemory(&pem.Block{Type: pemType, Bytes: pubKeyBytes}), nil
}