pki.go 1.1 KB
Newer Older
S
stormgbs 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
package util

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"io/ioutil"
)

func ParseRsaPrivateKey(file string) (*rsa.PrivateKey, error) {
	priByte, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	b, _ := pem.Decode(priByte)
	if b == nil {
		return nil, errors.New("error decoding private key")
	}
	priKey, err := x509.ParsePKCS1PrivateKey(b.Bytes)
	if err != nil {
		return nil, err
	}
	return priKey, nil
}

func ParseX509Certificate(file string) (*x509.Certificate, error) {
	cerBytes, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	cer, err := x509.ParseCertificate(cerBytes)
	if err != nil {
		return nil, errors.New("error parsing certificate")
	}
	return cer, nil
}

func ParseRsaPublicKey(file string) (*rsa.PublicKey, error) {
	pubByte, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	b, _ := pem.Decode(pubByte)
	if b == nil {
		return nil, errors.New("error decoding public key")
	}
	pubKey, err := x509.ParsePKIXPublicKey(b.Bytes)
	if err != nil {
		return nil, err
	}
	return pubKey.(*rsa.PublicKey), nil
}