/
pkcs8.go
276 lines (223 loc) · 6.71 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package pbes2
import (
"io"
"fmt"
"errors"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"github.com/deatil/go-cryptobin/pkcs1"
)
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,
}
// 默认配置 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]
}
encrypted, encryptionAlgorithm, err := PBES2Encrypt(rand, data, password, opt)
if err != nil {
return nil, errors.New("pkcs8: " + err.Error())
}
// 生成 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())
}
algo := pki.EncryptionAlgorithm
encryptedKey := pki.EncryptedData
decryptedKey, err := PBES2Decrypt(encryptedKey, algo, password)
if err != nil {
return nil, errors.New("pkcs8: " + err.Error())
}
return decryptedKey, nil
}
// 解出 PEM 块
func DecryptPEMBlock(block *pem.Block, password []byte) ([]byte, error) {
if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
return pkcs1.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")
}
// PBES2 加密
func PBES2Encrypt(rand io.Reader, data []byte, password []byte, opt *Opts) (encrypted []byte, algo pkix.AlgorithmIdentifier, err error) {
cipher := opt.Cipher
if cipher == nil {
err = errors.New("unknown opts cipher")
return
}
kdfOpts := opt.KDFOpts
if kdfOpts == nil {
err = errors.New("unknown opts kdfOpts")
return
}
salt := make([]byte, kdfOpts.GetSaltSize())
if _, saltErr := io.ReadFull(rand, salt); saltErr != nil {
err = errors.New("failed to generate salt: " + err.Error())
return
}
if cipher.HasKeyLength() {
kdfOpts = kdfOpts.WithHasKeyLength(true)
}
key, kdfParams, err := kdfOpts.DeriveKey(password, salt, cipher.KeySize())
if err != nil {
return
}
encrypted, encryptedParams, err := cipher.Encrypt(rand, key, data)
if err != nil {
return
}
// 生成 asn1 数据开始
marshalledParams, err := asn1.Marshal(kdfParams)
if err != nil {
return
}
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
}
encryptionAlgorithm := pkix.AlgorithmIdentifier{
Algorithm: oidPBES2,
Parameters: asn1.RawValue{
FullBytes: marshalledEncryptionAlgorithmParams,
},
}
return encrypted, encryptionAlgorithm, nil
}
// PBES2 解密
func PBES2Decrypt(data []byte, algo pkix.AlgorithmIdentifier, password []byte) ([]byte, error) {
if !algo.Algorithm.Equal(oidPBES2) {
return nil, errors.New("only PBES2 is supported")
}
var params pbes2Params
if _, err := asn1.Unmarshal(algo.Parameters.FullBytes, ¶ms); err != nil {
return nil, errors.New("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
}
decrypted, err := cipher.Decrypt(symkey, cipherParams, data)
if err != nil {
return nil, err
}
return decrypted, nil
}
// 是否是 PBES2 加密
func IsPBES2(algo asn1.ObjectIdentifier) bool {
if algo.Equal(oidPBES2) {
return true
}
return false
}
func parseKeyDerivationFunc(keyDerivationFunc pkix.AlgorithmIdentifier) (KDFParameters, error) {
oid := keyDerivationFunc.Algorithm.String()
params, ok := kdfs[oid]
if !ok {
return nil, fmt.Errorf("unsupported KDF (OID: %s)", oid)
}
newParams := params()
_, err := asn1.Unmarshal(keyDerivationFunc.Parameters.FullBytes, newParams)
if err != nil {
return nil, errors.New("invalid KDF parameters")
}
return newParams, nil
}
func parseEncryptionScheme(encryptionScheme pkix.AlgorithmIdentifier) (Cipher, []byte, error) {
newCipher, err := GetCipher(encryptionScheme)
if err != nil {
oid := encryptionScheme.Algorithm.String()
return nil, nil, fmt.Errorf("unsupported cipher (OID: %s)", oid)
}
params := encryptionScheme.Parameters.FullBytes
return newCipher, params, nil
}