blob: 71ea6ad1f5ee320d1301637d10d0f972e5ef7bb6 [file] [log] [blame]
Zack Williamse940c7a2019-08-21 14:25:39 -07001// Copyright 2014 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package internal
6
7import (
8 "crypto/rsa"
9 "crypto/x509"
10 "encoding/pem"
11 "errors"
12 "fmt"
13)
14
15// ParseKey converts the binary contents of a private key file
balaji.nagarajan8a2a7ee2026-06-19 22:31:13 +053016// to an [*rsa.PrivateKey]. It detects whether the private key is in a
17// PEM container or not. If so, it extracts the private key
Zack Williamse940c7a2019-08-21 14:25:39 -070018// from PEM container before conversion. It only supports PEM
19// containers with no passphrase.
20func ParseKey(key []byte) (*rsa.PrivateKey, error) {
21 block, _ := pem.Decode(key)
22 if block != nil {
23 key = block.Bytes
24 }
25 parsedKey, err := x509.ParsePKCS8PrivateKey(key)
26 if err != nil {
27 parsedKey, err = x509.ParsePKCS1PrivateKey(key)
28 if err != nil {
29 return nil, fmt.Errorf("private key should be a PEM or plain PKCS1 or PKCS8; parse error: %v", err)
30 }
31 }
32 parsed, ok := parsedKey.(*rsa.PrivateKey)
33 if !ok {
34 return nil, errors.New("private key is invalid")
35 }
36 return parsed, nil
37}