forked from SSLMate/go-pkcs12
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpkcs12.go
913 lines (793 loc) · 27.4 KB
/
pkcs12.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
// Copyright 2015, 2018, 2019 Opsmate, Inc. All rights reserved.
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package pkcs12 implements some of PKCS#12 (also known as P12 or PFX).
// It is intended for decoding DER-encoded P12/PFX files for use with the crypto/tls
// package, and for encoding P12/PFX files for use by legacy applications which
// do not support newer formats. Since PKCS#12 uses weak encryption
// primitives, it SHOULD NOT be used for new applications.
//
// Note that only DER-encoded PKCS#12 files are supported, even though PKCS#12
// allows BER encoding. This is because encoding/asn1 only supports DER.
//
// This package is forked from golang.org/x/crypto/pkcs12, which is frozen.
// The implementation is distilled from https://tools.ietf.org/html/rfc7292
// and referenced documents.
package pkcs12 // import "software.sslmate.com/src/go-pkcs12"
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"io"
"strings"
)
// DefaultPassword is the string "changeit", a commonly-used password for
// PKCS#12 files. Due to the weak encryption used by PKCS#12, it is
// RECOMMENDED that you use DefaultPassword when encoding PKCS#12 files,
// and protect the PKCS#12 files using other means.
const DefaultPassword = "changeit"
var (
oidDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 1})
oidEncryptedDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 6})
oidFriendlyName = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 20})
oidLocalKeyID = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 21})
oidMicrosoftCSPName = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 311, 17, 1})
oidJavaTrustStore = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 113894, 746875, 1, 1})
oidAnyExtendedKeyUsage = asn1.ObjectIdentifier([]int{2, 5, 29, 37, 0})
)
type pfxPdu struct {
Version int
AuthSafe contentInfo
MacData macData `asn1:"optional"`
}
type contentInfo struct {
ContentType asn1.ObjectIdentifier
Content asn1.RawValue `asn1:"tag:0,explicit,optional"`
}
type encryptedData struct {
Version int
EncryptedContentInfo encryptedContentInfo
}
type encryptedContentInfo struct {
ContentType asn1.ObjectIdentifier
ContentEncryptionAlgorithm pkix.AlgorithmIdentifier
EncryptedContent []byte `asn1:"tag:0,optional"`
}
func (i encryptedContentInfo) Algorithm() pkix.AlgorithmIdentifier {
return i.ContentEncryptionAlgorithm
}
func (i encryptedContentInfo) Data() []byte { return i.EncryptedContent }
func (i *encryptedContentInfo) SetData(data []byte) { i.EncryptedContent = data }
type safeBag struct {
Id asn1.ObjectIdentifier
Value asn1.RawValue `asn1:"tag:0,explicit"`
Attributes []pkcs12Attribute `asn1:"set,optional"`
}
func (bag *safeBag) hasAttribute(id asn1.ObjectIdentifier) bool {
for _, attr := range bag.Attributes {
if attr.Id.Equal(id) {
return true
}
}
return false
}
type pkcs12Attribute struct {
Id asn1.ObjectIdentifier
Value asn1.RawValue `asn1:"set"`
}
type encryptedPrivateKeyInfo struct {
AlgorithmIdentifier pkix.AlgorithmIdentifier
EncryptedData []byte
}
func (i encryptedPrivateKeyInfo) Algorithm() pkix.AlgorithmIdentifier {
return i.AlgorithmIdentifier
}
func (i encryptedPrivateKeyInfo) Data() []byte {
return i.EncryptedData
}
func (i *encryptedPrivateKeyInfo) SetData(data []byte) {
i.EncryptedData = data
}
// PEM block types
const (
certificateType = "CERTIFICATE"
privateKeyType = "PRIVATE KEY"
)
// unmarshal calls asn1.Unmarshal, but also returns an error if there is any
// trailing data after unmarshaling.
func unmarshal(in []byte, out interface{}) error {
trailing, err := asn1.Unmarshal(in, out)
if err != nil {
return err
}
if len(trailing) != 0 {
return errors.New("pkcs12: trailing data found")
}
return nil
}
// ToPEM converts all "safe bags" contained in pfxData to PEM blocks.
//
// Deprecated: ToPEM creates invalid PEM blocks (private keys
// are encoded as raw RSA or EC private keys rather than PKCS#8 despite being
// labeled "PRIVATE KEY"). To decode a PKCS#12 file, use [DecodeChain] instead,
// and use the [encoding/pem] package to convert to PEM if necessary.
func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) {
encodedPassword, err := bmpStringZeroTerminated(password)
if err != nil {
return nil, ErrIncorrectPassword
}
bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword, 2)
if err != nil {
return nil, err
}
blocks := make([]*pem.Block, 0, len(bags))
for _, bag := range bags {
block, err := convertBag(&bag, encodedPassword)
if err != nil {
return nil, err
}
blocks = append(blocks, block)
}
return blocks, nil
}
func convertBag(bag *safeBag, password []byte) (*pem.Block, error) {
block := &pem.Block{
Headers: make(map[string]string),
}
for _, attribute := range bag.Attributes {
k, v, err := convertAttribute(&attribute)
if err != nil {
return nil, err
}
block.Headers[k] = v
}
switch {
case bag.Id.Equal(oidCertBag):
block.Type = certificateType
certsData, err := decodeCertBag(bag.Value.Bytes)
if err != nil {
return nil, err
}
block.Bytes = certsData
case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
block.Type = privateKeyType
key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password)
if err != nil {
return nil, err
}
switch key := key.(type) {
case *rsa.PrivateKey:
block.Bytes = x509.MarshalPKCS1PrivateKey(key)
case *ecdsa.PrivateKey:
block.Bytes, err = x509.MarshalECPrivateKey(key)
if err != nil {
return nil, err
}
default:
return nil, errors.New("found unknown private key type in PKCS#8 wrapping")
}
default:
return nil, errors.New("don't know how to convert a safe bag of type " + bag.Id.String())
}
return block, nil
}
func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) {
isString := false
switch {
case attribute.Id.Equal(oidFriendlyName):
key = "friendlyName"
isString = true
case attribute.Id.Equal(oidLocalKeyID):
key = "localKeyId"
case attribute.Id.Equal(oidMicrosoftCSPName):
// This key is chosen to match OpenSSL.
key = "Microsoft CSP Name"
isString = true
default:
return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String())
}
if isString {
if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil {
return "", "", err
}
if value, err = decodeBMPString(attribute.Value.Bytes); err != nil {
return "", "", err
}
} else {
var id []byte
if err := unmarshal(attribute.Value.Bytes, &id); err != nil {
return "", "", err
}
value = hex.EncodeToString(id)
}
return key, value, nil
}
// Decode extracts a certificate and private key from pfxData, which must be a DER-encoded PKCS#12 file. This function
// assumes that there is only one certificate and only one private key in the
// pfxData. Since PKCS#12 files often contain more than one certificate, you
// probably want to use [DecodeChain] or [DecodeAll] instead.
func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) {
var caCerts []*x509.Certificate
privateKey, certificate, caCerts, err = DecodeChain(pfxData, password)
if len(caCerts) != 0 {
err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU")
}
return
}
// DecodeChain extracts a certificate, a CA certificate chain, and private key
// from pfxData, which must be a DER-encoded PKCS#12 file. This function assumes that there is at least one certificate
// and only one private key in the pfxData. The first certificate is assumed to
// be the leaf certificate, and subsequent certificates, if any, are assumed to
// comprise the CA certificate chain.
func DecodeChain(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, caCerts []*x509.Certificate, err error) {
encodedPassword, err := bmpStringZeroTerminated(password)
if err != nil {
return nil, nil, nil, err
}
bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword, 2)
if err != nil {
return nil, nil, nil, err
}
for _, bag := range bags {
switch {
case bag.Id.Equal(oidCertBag):
certsData, err := decodeCertBag(bag.Value.Bytes)
if err != nil {
return nil, nil, nil, err
}
certs, err := x509.ParseCertificates(certsData)
if err != nil {
return nil, nil, nil, err
}
if len(certs) != 1 {
err = errors.New("pkcs12: expected exactly one certificate in the certBag")
return nil, nil, nil, err
}
if certificate == nil {
certificate = certs[0]
} else {
caCerts = append(caCerts, certs[0])
}
case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
if privateKey != nil {
err = errors.New("pkcs12: expected exactly one key bag")
return nil, nil, nil, err
}
if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil {
return nil, nil, nil, err
}
}
}
if certificate == nil {
return nil, nil, nil, errors.New("pkcs12: certificate missing")
}
if privateKey == nil {
return nil, nil, nil, errors.New("pkcs12: private key missing")
}
return
}
// DecodeAll extracts all certificates and private keys from pfxData. This behaves the same as [Decode], but can be used with
// PKCS#12 files containing multiple (unrelated) certificates.
func DecodeAll(pfxData []byte, password string) (privateKeys []interface{}, certificates []*x509.Certificate, err error) {
encodedPassword, err := bmpStringZeroTerminated(password)
if err != nil {
return nil, nil, err
}
bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword, 2)
if err != nil {
return nil, nil, err
}
for _, bag := range bags {
switch {
case bag.Id.Equal(oidCertBag):
certsData, err := decodeCertBag(bag.Value.Bytes)
if err != nil {
return nil, nil, err
}
certs, err := x509.ParseCertificates(certsData)
if err != nil {
return nil, nil, err
}
if len(certs) != 1 {
err = errors.New("pkcs12: expected exactly one certificate in the certBag")
return nil, nil, err
}
certificates = append(certificates, certs[0])
case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
privateKey, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword)
if err != nil {
return nil, nil, err
}
privateKeys = append(privateKeys, privateKey)
}
}
return
}
// DecodeTrustStore extracts the certificates from pfxData, which must be a DER-encoded
// PKCS#12 file containing exclusively certificates with attribute 2.16.840.1.113894.746875.1.1,
// which is used by Java to designate a trust anchor.
func DecodeTrustStore(pfxData []byte, password string) (certs []*x509.Certificate, err error) {
encodedPassword, err := bmpStringZeroTerminated(password)
if err != nil {
return nil, err
}
bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword, 1)
if err != nil {
return nil, err
}
for _, bag := range bags {
switch {
case bag.Id.Equal(oidCertBag):
if !bag.hasAttribute(oidJavaTrustStore) {
return nil, errors.New("pkcs12: trust store contains a certificate that is not marked as trusted")
}
certsData, err := decodeCertBag(bag.Value.Bytes)
if err != nil {
return nil, err
}
parsedCerts, err := x509.ParseCertificates(certsData)
if err != nil {
return nil, err
}
if len(parsedCerts) != 1 {
err = errors.New("pkcs12: expected exactly one certificate in the certBag")
return nil, err
}
certs = append(certs, parsedCerts[0])
default:
return nil, errors.New("pkcs12: expected only certificate bags")
}
}
return
}
var IncorrectAliasError = errors.New("pkcs12: keypair not found with alias")
var IncorrectKeystorePasswordError = errors.New("pkcs12: incorrect keystore password")
var IncorrectKeyPasswordError = errors.New("pkcs12: incorrect key password")
func DecodeKeystore(pfxData []byte, storepass, alias, keypass string) (privateKey interface{}, certificate *x509.Certificate, err error) {
encodedPassword, err := bmpStringZeroTerminated(storepass)
if err != nil {
return nil, nil, err
}
encodedPrivateKeyPassword, err := bmpStringZeroTerminated(keypass)
if err != nil {
return nil, nil, err
}
bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword, -1)
if err != nil {
if errors.Is(err, ErrIncorrectPassword) {
return nil, nil, IncorrectKeystorePasswordError
}
return nil, nil, err
}
for _, bag := range bags {
switch {
case bag.Id.Equal(oidCertBag):
certAlias, err := getAlias(bag)
if err != nil {
return nil, nil, fmt.Errorf("pkcs12: failed to get alias for the cert bag: %s", err)
}
if strings.ToLower(certAlias) != strings.ToLower(alias) {
continue
}
certsData, err := decodeCertBag(bag.Value.Bytes)
if err != nil {
return nil, nil, err
}
cert, err := x509.ParseCertificate(certsData)
if err != nil {
return nil, nil, err
}
certificate = cert
case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
privateKeyAlias, err := getAlias(bag)
if err != nil {
return nil, nil, fmt.Errorf("pkcs12: failed to get alias for the key bag: %s", err)
}
if strings.ToLower(privateKeyAlias) != strings.ToLower(alias) {
continue
}
key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPrivateKeyPassword)
if err != nil {
if err.Error() == "pkcs12: error decrypting PKCS#8 shrouded key bag: pkcs12: decryption error, incorrect padding" {
return nil, nil, IncorrectKeyPasswordError
}
return nil, nil, err
}
privateKey = key
}
}
if certificate == nil && privateKey == nil {
return nil, nil, IncorrectAliasError
}
if certificate == nil {
return nil, nil, errors.New("pkcs12: certificate not found with alias")
}
if privateKey == nil {
return nil, nil, errors.New("pkcs12: private key not found with alias")
}
return
}
func getAlias(bag safeBag) (string, error) {
if len(bag.Attributes) == 0 {
return "", errors.New("no attributes")
}
var aliasAttribute *pkcs12Attribute
for _, attribute := range bag.Attributes {
if attribute.Id.Equal(oidFriendlyName) {
aliasAttribute = &attribute
break
}
}
if aliasAttribute == nil {
return "", errors.New("alias attribute not found")
}
if err := unmarshal(aliasAttribute.Value.Bytes, &aliasAttribute.Value); err != nil {
return "", err
}
alias, err := decodeBMPString(aliasAttribute.Value.Bytes)
if err != nil {
return "", err
}
if alias == "" {
return "", errors.New("empty alias")
}
return alias, nil
}
func getSafeContents(p12Data, password []byte, expectedItems int) (bags []safeBag, updatedPassword []byte, err error) {
pfx := new(pfxPdu)
if err := unmarshal(p12Data, pfx); err != nil {
return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error())
}
if pfx.Version != 3 {
return nil, nil, NotImplementedError("can only decode v3 PFX PDU's")
}
if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) {
return nil, nil, NotImplementedError("only password-protected PFX is implemented")
}
// unmarshal the explicit bytes in the content for type 'data'
if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil {
return nil, nil, err
}
if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 {
if !(len(password) == 2 && password[0] == 0 && password[1] == 0) {
return nil, nil, errors.New("pkcs12: no MAC in data")
}
} else if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil {
if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 {
// some implementations use an empty byte array
// for the empty string password try one more
// time with empty-empty password
password = nil
err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password)
}
if err != nil {
return nil, nil, err
}
}
var authenticatedSafe []contentInfo
if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil {
return nil, nil, err
}
if expectedItems > -1 && len(authenticatedSafe) != expectedItems {
return nil, nil, NotImplementedError(fmt.Sprintf("expected exactly %d items in the authenticated safe", expectedItems))
}
for _, ci := range authenticatedSafe {
var data []byte
switch {
case ci.ContentType.Equal(oidDataContentType):
if err := unmarshal(ci.Content.Bytes, &data); err != nil {
return nil, nil, err
}
case ci.ContentType.Equal(oidEncryptedDataContentType):
var encryptedData encryptedData
if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil {
return nil, nil, err
}
if encryptedData.Version != 0 {
return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported")
}
if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil {
return nil, nil, err
}
default:
return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe")
}
var safeContents []safeBag
if err := unmarshal(data, &safeContents); err != nil {
return nil, nil, err
}
bags = append(bags, safeContents...)
}
return bags, password, nil
}
// Encode produces pfxData containing one private key (privateKey), an
// end-entity certificate (certificate), and any number of CA certificates
// (caCerts).
//
// The private key is encrypted with the provided password, but due to the
// weak encryption primitives used by PKCS#12, it is RECOMMENDED that you
// specify a hard-coded password (such as [DefaultPassword]) and protect
// the resulting pfxData using other means.
//
// The rand argument is used to provide entropy for the encryption, and
// can be set to [crypto/rand.Reader].
//
// Encode emulates the behavior of OpenSSL's PKCS12_create: it creates two
// SafeContents: one that's encrypted with RC2 and contains the certificates,
// and another that is unencrypted and contains the private key shrouded with
// 3DES The private key bag and the end-entity certificate bag have the
// LocalKeyId attribute set to the SHA-1 fingerprint of the end-entity
// certificate.
func Encode(rand io.Reader, privateKey interface{}, certificate *x509.Certificate, caCerts []*x509.Certificate, password string) (pfxData []byte, err error) {
encodedPassword, err := bmpStringZeroTerminated(password)
if err != nil {
return nil, err
}
var pfx pfxPdu
pfx.Version = 3
var certFingerprint = sha1.Sum(certificate.Raw)
var localKeyIdAttr pkcs12Attribute
localKeyIdAttr.Id = oidLocalKeyID
localKeyIdAttr.Value.Class = 0
localKeyIdAttr.Value.Tag = 17
localKeyIdAttr.Value.IsCompound = true
if localKeyIdAttr.Value.Bytes, err = asn1.Marshal(certFingerprint[:]); err != nil {
return nil, err
}
var certBags []safeBag
var certBag *safeBag
if certBag, err = makeCertBag(certificate.Raw, []pkcs12Attribute{localKeyIdAttr}); err != nil {
return nil, err
}
certBags = append(certBags, *certBag)
for _, cert := range caCerts {
if certBag, err = makeCertBag(cert.Raw, []pkcs12Attribute{}); err != nil {
return nil, err
}
certBags = append(certBags, *certBag)
}
var keyBag safeBag
keyBag.Id = oidPKCS8ShroundedKeyBag
keyBag.Value.Class = 2
keyBag.Value.Tag = 0
keyBag.Value.IsCompound = true
if keyBag.Value.Bytes, err = encodePkcs8ShroudedKeyBag(rand, privateKey, encodedPassword); err != nil {
return nil, err
}
keyBag.Attributes = append(keyBag.Attributes, localKeyIdAttr)
// Construct an authenticated safe with two SafeContents.
// The first SafeContents is encrypted and contains the cert bags.
// The second SafeContents is unencrypted and contains the shrouded key bag.
var authenticatedSafe [2]contentInfo
if authenticatedSafe[0], err = makeSafeContents(rand, certBags, encodedPassword); err != nil {
return nil, err
}
if authenticatedSafe[1], err = makeSafeContents(rand, []safeBag{keyBag}, nil); err != nil {
return nil, err
}
var authenticatedSafeBytes []byte
if authenticatedSafeBytes, err = asn1.Marshal(authenticatedSafe[:]); err != nil {
return nil, err
}
// compute the MAC
pfx.MacData.Mac.Algorithm.Algorithm = oidSHA1
pfx.MacData.MacSalt = make([]byte, 8)
if _, err = rand.Read(pfx.MacData.MacSalt); err != nil {
return nil, err
}
pfx.MacData.Iterations = 1
if err = computeMac(&pfx.MacData, authenticatedSafeBytes, encodedPassword); err != nil {
return nil, err
}
pfx.AuthSafe.ContentType = oidDataContentType
pfx.AuthSafe.Content.Class = 2
pfx.AuthSafe.Content.Tag = 0
pfx.AuthSafe.Content.IsCompound = true
if pfx.AuthSafe.Content.Bytes, err = asn1.Marshal(authenticatedSafeBytes); err != nil {
return nil, err
}
if pfxData, err = asn1.Marshal(pfx); err != nil {
return nil, errors.New("pkcs12: error writing P12 data: " + err.Error())
}
return
}
// EncodeTrustStore produces pfxData containing any number of CA certificates
// (certs) to be trusted. The certificates will be marked with a special OID that
// allow it to be used as a Java TrustStore in Java 1.8 and newer.
//
// Due to the weak encryption primitives used by PKCS#12, it is RECOMMENDED that
// you specify a hard-coded password (such as [DefaultPassword]) and protect
// the resulting pfxData using other means.
//
// The rand argument is used to provide entropy for the encryption, and
// can be set to [crypto/rand.Reader].
//
// EncodeTrustStore creates a single SafeContents that's encrypted with RC2
// and contains the certificates.
//
// The Subject of the certificates are used as the Friendly Names (Aliases)
// within the resulting pfxData. If certificates share a Subject, then the
// resulting Friendly Names (Aliases) will be identical, which Java may treat as
// the same entry when used as a Java TrustStore, e.g. with `keytool`. To
// customize the Friendly Names, use [EncodeTrustStoreEntries].
func EncodeTrustStore(rand io.Reader, certs []*x509.Certificate, password string) (pfxData []byte, err error) {
var certsWithFriendlyNames []TrustStoreEntry
for _, cert := range certs {
certsWithFriendlyNames = append(certsWithFriendlyNames, TrustStoreEntry{
Cert: cert,
FriendlyName: cert.Subject.String(),
})
}
return EncodeTrustStoreEntries(rand, certsWithFriendlyNames, password)
}
// TrustStoreEntry represents an entry in a Java TrustStore.
type TrustStoreEntry struct {
Cert *x509.Certificate
FriendlyName string
}
// EncodeTrustStoreEntries produces pfxData containing any number of CA
// certificates (entries) to be trusted. The certificates will be marked with a
// special OID that allow it to be used as a Java TrustStore in Java 1.8 and newer.
//
// This is identical to [EncodeTrustStore], but also allows for setting specific
// Friendly Names (Aliases) to be used per certificate, by specifying a slice
// of TrustStoreEntry.
//
// If the same Friendly Name is used for more than one certificate, then the
// resulting Friendly Names (Aliases) in the pfxData will be identical, which Java
// may treat as the same entry when used as a Java TrustStore, e.g. with `keytool`.
//
// Due to the weak encryption primitives used by PKCS#12, it is RECOMMENDED that
// you specify a hard-coded password (such as [DefaultPassword]) and protect
// the resulting pfxData using other means.
//
// The rand argument is used to provide entropy for the encryption, and
// can be set to [crypto/rand.Reader].
//
// EncodeTrustStoreEntries creates a single SafeContents that's encrypted
// with RC2 and contains the certificates.
func EncodeTrustStoreEntries(rand io.Reader, entries []TrustStoreEntry, password string) (pfxData []byte, err error) {
encodedPassword, err := bmpStringZeroTerminated(password)
if err != nil {
return nil, err
}
var pfx pfxPdu
pfx.Version = 3
var certAttributes []pkcs12Attribute
extKeyUsageOidBytes, err := asn1.Marshal(oidAnyExtendedKeyUsage)
if err != nil {
return nil, err
}
// the oidJavaTrustStore attribute contains the EKUs for which
// this trust anchor will be valid
certAttributes = append(certAttributes, pkcs12Attribute{
Id: oidJavaTrustStore,
Value: asn1.RawValue{
Class: 0,
Tag: 17,
IsCompound: true,
Bytes: extKeyUsageOidBytes,
},
})
var certBags []safeBag
for _, entry := range entries {
bmpFriendlyName, err := bmpString(entry.FriendlyName)
if err != nil {
return nil, err
}
encodedFriendlyName, err := asn1.Marshal(asn1.RawValue{
Class: 0,
Tag: 30,
IsCompound: false,
Bytes: bmpFriendlyName,
})
if err != nil {
return nil, err
}
friendlyName := pkcs12Attribute{
Id: oidFriendlyName,
Value: asn1.RawValue{
Class: 0,
Tag: 17,
IsCompound: true,
Bytes: encodedFriendlyName,
},
}
certBag, err := makeCertBag(entry.Cert.Raw, append(certAttributes, friendlyName))
if err != nil {
return nil, err
}
certBags = append(certBags, *certBag)
}
// Construct an authenticated safe with one SafeContent.
// The SafeContents is encrypted and contains the cert bags.
var authenticatedSafe [1]contentInfo
if authenticatedSafe[0], err = makeSafeContents(rand, certBags, encodedPassword); err != nil {
return nil, err
}
var authenticatedSafeBytes []byte
if authenticatedSafeBytes, err = asn1.Marshal(authenticatedSafe[:]); err != nil {
return nil, err
}
// compute the MAC
pfx.MacData.Mac.Algorithm.Algorithm = oidSHA1
pfx.MacData.MacSalt = make([]byte, 8)
if _, err = rand.Read(pfx.MacData.MacSalt); err != nil {
return nil, err
}
pfx.MacData.Iterations = 1
if err = computeMac(&pfx.MacData, authenticatedSafeBytes, encodedPassword); err != nil {
return nil, err
}
pfx.AuthSafe.ContentType = oidDataContentType
pfx.AuthSafe.Content.Class = 2
pfx.AuthSafe.Content.Tag = 0
pfx.AuthSafe.Content.IsCompound = true
if pfx.AuthSafe.Content.Bytes, err = asn1.Marshal(authenticatedSafeBytes); err != nil {
return nil, err
}
if pfxData, err = asn1.Marshal(pfx); err != nil {
return nil, errors.New("pkcs12: error writing P12 data: " + err.Error())
}
return
}
func makeCertBag(certBytes []byte, attributes []pkcs12Attribute) (certBag *safeBag, err error) {
certBag = new(safeBag)
certBag.Id = oidCertBag
certBag.Value.Class = 2
certBag.Value.Tag = 0
certBag.Value.IsCompound = true
if certBag.Value.Bytes, err = encodeCertBag(certBytes); err != nil {
return nil, err
}
certBag.Attributes = attributes
return
}
func makeSafeContents(rand io.Reader, bags []safeBag, password []byte) (ci contentInfo, err error) {
var data []byte
if data, err = asn1.Marshal(bags); err != nil {
return
}
if password == nil {
ci.ContentType = oidDataContentType
ci.Content.Class = 2
ci.Content.Tag = 0
ci.Content.IsCompound = true
if ci.Content.Bytes, err = asn1.Marshal(data); err != nil {
return
}
} else {
randomSalt := make([]byte, 8)
if _, err = rand.Read(randomSalt); err != nil {
return
}
var algo pkix.AlgorithmIdentifier
algo.Algorithm = oidPBEWithSHAAnd40BitRC2CBC
if algo.Parameters.FullBytes, err = asn1.Marshal(pbeParams{Salt: randomSalt, Iterations: 2048}); err != nil {
return
}
var encryptedData encryptedData
encryptedData.Version = 0
encryptedData.EncryptedContentInfo.ContentType = oidDataContentType
encryptedData.EncryptedContentInfo.ContentEncryptionAlgorithm = algo
if err = pbEncrypt(&encryptedData.EncryptedContentInfo, data, password); err != nil {
return
}
ci.ContentType = oidEncryptedDataContentType
ci.Content.Class = 2
ci.Content.Tag = 0
ci.Content.IsCompound = true
if ci.Content.Bytes, err = asn1.Marshal(encryptedData); err != nil {
return
}
}
return
}