/
private-key.go
83 lines (75 loc) · 2.23 KB
/
private-key.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
© 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package parlca
import (
"crypto/x509"
"os"
"github.com/haraldrudell/parl"
"github.com/haraldrudell/parl/perrors"
"github.com/haraldrudell/parl/punix"
)
func NewPrivateKey(algo x509.PublicKeyAlgorithm) (privateKey parl.PrivateKey, err error) {
switch algo {
case x509.Ed25519:
privateKey, err = NewEd25519()
case x509.RSA:
privateKey, err = NewRsa()
case x509.ECDSA:
privateKey, err = NewEcdsa()
default:
err = x509.ErrUnsupportedAlgorithm
}
return
}
func NewPrivateKey2(algo x509.PublicKeyAlgorithm, privateKeyDer parl.PrivateKeyDer) (privateKey parl.PrivateKey, err error) {
switch algo {
case x509.Ed25519:
privateKey, err = NewEd25519()
case x509.RSA:
privateKey, err = NewRsa()
case x509.ECDSA:
privateKey, err = NewEcdsa()
default:
err = x509.ErrUnsupportedAlgorithm
}
return
}
func LoadPrivateKeyFromDer(filename string, algo x509.PublicKeyAlgorithm, allowNotFound ...bool) (privateKey parl.PrivateKey, err error) {
allowNotFound0 := len(allowNotFound) > 0 && allowNotFound[0]
var privateKeyDer parl.PrivateKeyDer
if privateKeyDer, err = ReadFile(filename, allowNotFound0); err != nil {
return // file read error return
} else if allowNotFound0 && privateKeyDer == nil {
return
}
if privateKey, err = NewPrivateKey2(algo, privateKeyDer); err != nil {
return
}
// TODO 220624 validate privateKey?
return
}
func LoadFromPem(filename string, allowNotFound ...bool) (
certificate parl.Certificate, privateKey parl.PrivateKey, publicKey parl.PublicKey,
err error) {
allowNotFound0 := len(allowNotFound) > 0 && allowNotFound[0]
var pemBytes parl.PemBytes
if pemBytes, err = ReadFile(filename, allowNotFound0); err != nil {
return // file read error return
} else if allowNotFound0 && pemBytes == nil {
return
}
// TODO 220624 validate privateKey?
return ParsePEM(pemBytes)
}
func ReadFile(filename string, allowNotFound bool) (byts []byte, err error) {
if byts, err = os.ReadFile(filename); err != nil {
if allowNotFound && punix.IsENOENT(err) {
err = nil
return // cert file does not exist: byts == nil, err == nil
}
perrors.IsPF(&err, "os.ReadFile %w", err)
}
return
}