forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
safebags.go
67 lines (53 loc) · 1.81 KB
/
safebags.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
package pkcs12
import (
"crypto/x509/pkix"
"encoding/asn1"
"errors"
)
//see https://tools.ietf.org/html/rfc7292#appendix-D
var (
oidPkcs8ShroudedKeyBagType = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 2}
oidCertBagType = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 3}
oidCertTypeX509Certificate = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 22, 1}
)
type certBag struct {
Id asn1.ObjectIdentifier
Data []byte `asn1:"tag:0,explicit"`
}
func getAlgorithmParams(salt []byte, iterations int) (asn1.RawValue, error) {
params := pbeParams{
Salt: salt,
Iterations: iterations,
}
return convertToRawVal(params)
}
func encodePkcs8ShroudedKeyBag(privateKey interface{}, password []byte) (bytes []byte, err error) {
privateKeyBytes, err := marshalPKCS8PrivateKey(privateKey)
if err != nil {
return nil, errors.New("pkcs12: error encoding PKCS#8 private key: " + err.Error())
}
salt, err := makeSalt(pbeSaltSizeBytes)
if err != nil {
return nil, errors.New("pkcs12: error creating PKCS#8 salt: " + err.Error())
}
pkData, err := pbEncrypt(privateKeyBytes, salt, password, pbeIterationCount)
if err != nil {
return nil, errors.New("pkcs12: error encoding PKCS#8 shrouded key bag when encrypting cert bag: " + err.Error())
}
params, err := getAlgorithmParams(salt, pbeIterationCount)
if err != nil {
return nil, errors.New("pkcs12: error encoding PKCS#8 shrouded key bag algorithm's parameters: " + err.Error())
}
pkinfo := encryptedPrivateKeyInfo{
AlgorithmIdentifier: pkix.AlgorithmIdentifier{
Algorithm: oidPbeWithSHAAnd3KeyTripleDESCBC,
Parameters: params,
},
EncryptedData: pkData,
}
bytes, err = asn1.Marshal(pkinfo)
if err != nil {
return nil, errors.New("pkcs12: error encoding PKCS#8 shrouded key bag: " + err.Error())
}
return bytes, err
}