-
Notifications
You must be signed in to change notification settings - Fork 24
/
pkcs8.go
243 lines (198 loc) · 6.11 KB
/
pkcs8.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package pkcs8
import (
"io"
"fmt"
"errors"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
)
var (
// key derivation functions
oidRSADSI = asn1.ObjectIdentifier{1, 2, 840, 113549}
oidPBES2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 13}
)
// 配置
type Opts struct {
Cipher Cipher
KDFOpts KDFOpts
}
// 默认配置 PBKDF2
var DefaultPBKDF2Opts = PBKDF2Opts{
SaltSize: 16,
IterationCount: 10000,
}
// 默认配置 PBKDF2,带 key 长度
var DefaultPBKDF2OptsWithKeyLength = PBKDF2OptsWithKeyLength{
SaltSize: 16,
IterationCount: 10000,
}
// 默认配置 Scrypt
var DefaultScryptOpts = ScryptOpts{
SaltSize: 16,
CostParameter: 1 << 2,
BlockSize: 8,
ParallelizationParameter: 1,
}
// 默认配置
var DefaultOpts = Opts{
Cipher: AES256CBC,
KDFOpts: DefaultPBKDF2Opts,
}
// 结构体数据可以查看以下文档
// RFC5208 at https://tools.ietf.org/html/rfc5208
// RFC5958 at https://tools.ietf.org/html/rfc5958
type encryptedPrivateKeyInfo struct {
EncryptionAlgorithm pkix.AlgorithmIdentifier
EncryptedData []byte
}
// pbes2 数据
type pbes2Params struct {
KeyDerivationFunc pkix.AlgorithmIdentifier
EncryptionScheme pkix.AlgorithmIdentifier
}
// 加密 PKCS8
func EncryptPKCS8PrivateKey(
rand io.Reader,
blockType string,
data []byte,
password []byte,
opts ...Opts,
) (*pem.Block, error) {
opt := &DefaultOpts
if len(opts) > 0 {
opt = &opts[0]
}
cipher := opt.Cipher
if cipher == nil {
return nil, errors.New("pkcs8: failed to encrypt PEM: unknown opts cipher")
}
kdfOpts := opt.KDFOpts
if kdfOpts == nil {
return nil, errors.New("pkcs8: failed to encrypt PEM: unknown opts kdfOpts")
}
salt := make([]byte, kdfOpts.GetSaltSize())
if _, err := io.ReadFull(rand, salt); err != nil {
return nil, errors.New("pkcs8: failed to generate salt." + err.Error())
}
key, kdfParams, err := kdfOpts.DeriveKey(password, salt, cipher.KeySize())
if err != nil {
return nil, err
}
encrypted, encryptedParams, err := cipher.Encrypt(key, data)
if err != nil {
return nil, err
}
// 生成 asn1 数据开始
marshalledParams, err := asn1.Marshal(kdfParams)
if err != nil {
return nil, errors.New("pkcs8: " + err.Error())
}
keyDerivationFunc := pkix.AlgorithmIdentifier{
Algorithm: kdfOpts.OID(),
Parameters: asn1.RawValue{
FullBytes: marshalledParams,
},
}
encryptionScheme := pkix.AlgorithmIdentifier{
Algorithm: cipher.OID(),
Parameters: asn1.RawValue{
FullBytes: encryptedParams,
},
}
encryptionAlgorithmParams := pbes2Params{
EncryptionScheme: encryptionScheme,
KeyDerivationFunc: keyDerivationFunc,
}
marshalledEncryptionAlgorithmParams, err := asn1.Marshal(encryptionAlgorithmParams)
if err != nil {
return nil, err
}
encryptionAlgorithm := pkix.AlgorithmIdentifier{
Algorithm: oidPBES2,
Parameters: asn1.RawValue{
FullBytes: marshalledEncryptionAlgorithmParams,
},
}
// 生成 ans1 数据
pki := encryptedPrivateKeyInfo{
EncryptionAlgorithm: encryptionAlgorithm,
EncryptedData: encrypted,
}
b, err := asn1.Marshal(pki)
if err != nil {
return nil, errors.New("pkcs8: error marshaling encrypted key." + err.Error())
}
return &pem.Block{
Type: blockType,
Bytes: b,
}, nil
}
// 解出 PKCS8 密钥
func DecryptPKCS8PrivateKey(data, password []byte) ([]byte, error) {
var pki encryptedPrivateKeyInfo
if _, err := asn1.Unmarshal(data, &pki); err != nil {
return nil, errors.New("pkcs8: failed to unmarshal private key." + err.Error())
}
if !pki.EncryptionAlgorithm.Algorithm.Equal(oidPBES2) {
return nil, errors.New("pkcs8: unsupported encrypted PEM: only PBES2 is supported")
}
var params pbes2Params
if _, err := asn1.Unmarshal(pki.EncryptionAlgorithm.Parameters.FullBytes, ¶ms); err != nil {
return nil, errors.New("pkcs8: invalid PBES2 parameters")
}
cipher, cipherParams, err := parseEncryptionScheme(params.EncryptionScheme)
if err != nil {
return nil, err
}
kdfParam, err := parseKeyDerivationFunc(params.KeyDerivationFunc)
if err != nil {
return nil, err
}
keySize := cipher.KeySize()
// 生成密钥
symkey, err := kdfParam.DeriveKey(password, keySize)
if err != nil {
return nil, err
}
encryptedKey := pki.EncryptedData
decryptedKey, err := cipher.Decrypt(symkey, cipherParams, encryptedKey)
if err != nil {
return nil, err
}
return decryptedKey, nil
}
// 解出 PEM 块
func DecryptPEMBlock(block *pem.Block, password []byte) ([]byte, error) {
if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
return x509.DecryptPEMBlock(block, password)
}
// PKCS#8 header defined in RFC7468 section 11
if block.Type == "ENCRYPTED PRIVATE KEY" {
return DecryptPKCS8PrivateKey(block.Bytes, password)
}
return nil, errors.New("pkcs8: unsupported encrypted PEM")
}
func parseKeyDerivationFunc(keyDerivationFunc pkix.AlgorithmIdentifier) (KDFParameters, error) {
oid := keyDerivationFunc.Algorithm.String()
params, ok := kdfs[oid]
if !ok {
return nil, fmt.Errorf("pkcs8: unsupported KDF (OID: %s)", oid)
}
newParams := params()
_, err := asn1.Unmarshal(keyDerivationFunc.Parameters.FullBytes, newParams)
if err != nil {
return nil, errors.New("pkcs8: invalid KDF parameters")
}
return newParams, nil
}
func parseEncryptionScheme(encryptionScheme pkix.AlgorithmIdentifier) (Cipher, []byte, error) {
oid := encryptionScheme.Algorithm.String()
newCipher, err := GetCipher(oid)
if err != nil {
return nil, nil, fmt.Errorf("pkcs8: unsupported cipher (OID: %s)", oid)
}
params := encryptionScheme.Parameters.FullBytes
return newCipher, params, nil
}