github.com/blend/go-sdk@v1.20220411.3/certutil/pem_utils.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package certutil 9 10 import ( 11 "crypto/rsa" 12 "crypto/x509" 13 "encoding/pem" 14 "os" 15 16 "github.com/blend/go-sdk/ex" 17 ) 18 19 // CommonNamesForCertPEM returns the common names from a cert pair. 20 func CommonNamesForCertPEM(certPEM []byte) ([]string, error) { 21 certs, err := ParseCertPEM(certPEM) 22 if err != nil { 23 return nil, err 24 } 25 output := make([]string, len(certs)) 26 for index, cert := range certs { 27 output[index] = cert.Subject.CommonName 28 } 29 return output, nil 30 } 31 32 // ParseCertPEM parses the cert portion of a cert pair. 33 func ParseCertPEM(certPem []byte) (output []*x509.Certificate, err error) { 34 for len(certPem) > 0 { 35 var block *pem.Block 36 block, certPem = pem.Decode(certPem) 37 if block == nil { 38 break 39 } 40 if block.Type != BlockTypeCertificate || len(block.Headers) != 0 { 41 continue 42 } 43 44 cert, certErr := x509.ParseCertificate(block.Bytes) 45 if certErr != nil { 46 err = ex.New(certErr) 47 return 48 } 49 output = append(output, cert) 50 } 51 52 return 53 } 54 55 // ReadPrivateKeyPEMFromPath reads a private key pem from a given path. 56 func ReadPrivateKeyPEMFromPath(keyPath string) (*rsa.PrivateKey, error) { 57 contents, err := os.ReadFile(keyPath) 58 if err != nil { 59 return nil, ex.New(err, ex.OptMessagef("key path: %s", keyPath)) 60 } 61 data, _ := pem.Decode(contents) 62 pk, err := x509.ParsePKCS1PrivateKey(data.Bytes) 63 if err != nil { 64 return nil, ex.New(err) 65 } 66 return pk, nil 67 }