github.com/mendersoftware/go-lib-micro@v0.0.0-20240304135804-e8e39c59b148/keys/key.go (about) 1 // Copyright 2023 Northern.tech AS 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package keys 15 16 import ( 17 "crypto/rsa" 18 "crypto/x509" 19 "encoding/pem" 20 "io/ioutil" 21 22 "github.com/pkg/errors" 23 ) 24 25 const ( 26 ErrMsgPrivKeyReadFailed = "failed to read server private key file" 27 ErrMsgPrivKeyNotPEMEncoded = "server private key not PEM-encoded" 28 ) 29 30 func LoadRSAPrivate(privKeyPath string) (*rsa.PrivateKey, error) { 31 // read key from file 32 pemData, err := ioutil.ReadFile(privKeyPath) 33 if err != nil { 34 return nil, errors.Wrap(err, ErrMsgPrivKeyReadFailed) 35 } 36 // decode pem key 37 block, _ := pem.Decode(pemData) 38 if block == nil { 39 return nil, errors.New(ErrMsgPrivKeyNotPEMEncoded) 40 } 41 // check if it is a RSA PRIVATE KEY 42 if got, want := block.Type, "RSA PRIVATE KEY"; got != want { 43 return nil, errors.Errorf( 44 "unknown server private key type; got: %s, want: %s", got, want) 45 } 46 // return parsed key 47 return x509.ParsePKCS1PrivateKey(block.Bytes) 48 }