Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add x509 parsing utilities #1

Merged
merged 3 commits into from
May 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/notaryproject/notation-core-go

go 1.17
32 changes: 32 additions & 0 deletions x509/cert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package cryptoutil

import (
"crypto/x509"
"encoding/pem"
"os"
)

// ReadCertificateFile reads a certificate PEM file.
func ReadCertificateFile(path string) ([]*x509.Certificate, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return ParseCertificatePEM(data)
}

// ParseCertificatePEM parses a certificate PEM,
// Does not perform any additional validations if the certs are a valid cert chain.
func ParseCertificatePEM(data []byte) ([]*x509.Certificate, error) {
var certs []*x509.Certificate
block, rest := pem.Decode(data)
for block != nil {
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
certs = append(certs, cert)
block, rest = pem.Decode(rest)
}
return certs, nil
}
36 changes: 36 additions & 0 deletions x509/key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package cryptoutil

import (
"crypto"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
)

// ReadPrivateKeyFile reads a key PEM file as a signing key.
func ReadPrivateKeyFile(path string) (crypto.PrivateKey, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return ParsePrivateKeyPEM(data)
}

// ParsePrivateKeyPEM parses a PEM as a signing key.
func ParsePrivateKeyPEM(data []byte) (crypto.PrivateKey, error) {
block, _ := pem.Decode(data)
if block == nil {
return nil, errors.New("no PEM data found")
}
switch block.Type {
case "PRIVATE KEY":
return x509.ParsePKCS8PrivateKey(block.Bytes)
case "EC PRIVATE KEY":
return x509.ParseECPrivateKey(block.Bytes)
case "RSA PRIVATE KEY":
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
return nil, fmt.Errorf("unsupported PEM block type: %s", block.Type)
}