summaryrefslogtreecommitdiff
path: root/vendor/github.com/mitchellh/packer/builder/azure/pkcs12/safebags.go
blob: 5d4793b3e35035b917b6739b98ff49cd27c04e28 (plain)
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
}