typenative 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/bin/node/assert.js +2 -2
  2. package/bin/node/child_process.js +66 -8
  3. package/bin/node/fs.js +1012 -4
  4. package/bin/node/histogram.js +1991 -0
  5. package/bin/node/process.js +14 -2
  6. package/bin/node/sqlite.js +1488 -5
  7. package/bin/node/stream.js +2 -1
  8. package/bin/node/system_extra.js +3 -270
  9. package/bin/node/test.js +39 -1
  10. package/bin/node/test_report.js +47 -1
  11. package/bin/node/test_run.js +57 -2
  12. package/bin/node/util.js +8 -5
  13. package/bin/node/webassembly.js +20 -5
  14. package/bin/node/webview.js +3257 -244
  15. package/bin/node/zlib.js +118 -14
  16. package/bin/node/zlib_iter.js +585 -0
  17. package/bin/transpiler.js +1370 -258
  18. package/bin/version.js +1 -1
  19. package/govendor/software.sslmate.com/src/go-pkcs12/.gitattributes +10 -0
  20. package/govendor/software.sslmate.com/src/go-pkcs12/LICENSE +28 -0
  21. package/govendor/software.sslmate.com/src/go-pkcs12/README.md +31 -0
  22. package/govendor/software.sslmate.com/src/go-pkcs12/bmp-string.go +63 -0
  23. package/govendor/software.sslmate.com/src/go-pkcs12/crypto.go +331 -0
  24. package/govendor/software.sslmate.com/src/go-pkcs12/errors.go +23 -0
  25. package/govendor/software.sslmate.com/src/go-pkcs12/go.mod +3 -0
  26. package/govendor/software.sslmate.com/src/go-pkcs12/internal/rc2/rc2.go +271 -0
  27. package/govendor/software.sslmate.com/src/go-pkcs12/mac.go +202 -0
  28. package/govendor/software.sslmate.com/src/go-pkcs12/pbkdf.go +184 -0
  29. package/govendor/software.sslmate.com/src/go-pkcs12/pkcs12.go +1000 -0
  30. package/govendor/software.sslmate.com/src/go-pkcs12/safebags.go +107 -0
  31. package/package.json +10 -1
  32. package/types/tsconfig.json +17 -0
  33. package/types/typenative-npm.d.ts +492 -12
  34. package/types/typenative.d.ts +88 -2
  35. package/.gitattributes +0 -1
  36. package/.github/workflows/ci.yml +0 -68
  37. package/.github/workflows/npm-publish-github-packages.yml +0 -88
  38. package/CHANGELOG.md +0 -1746
  39. package/CONTRIBUTION.md +0 -133
  40. package/conformance.md +0 -1497
  41. package/examples/README.md +0 -114
  42. package/examples/angular-templates/README.md +0 -141
  43. package/examples/angular-templates/bench.mjs +0 -173
  44. package/examples/angular-templates/dom-type-globals.d.ts +0 -21
  45. package/examples/angular-templates/dom-type-stubs.ts +0 -21
  46. package/examples/angular-templates/main.ts +0 -135
  47. package/examples/angular-templates/parity.mjs +0 -157
  48. package/examples/angular-templates/run-node.mjs +0 -69
  49. package/examples/angular-templates/vendor/angular/compiler/LICENSE +0 -21
  50. package/examples/desktop-notes/README.md +0 -106
  51. package/examples/desktop-notes/bench.mjs +0 -125
  52. package/examples/desktop-notes/main.ts +0 -131
  53. package/examples/desktop-notes/package-lock.json +0 -726
  54. package/examples/desktop-notes/package.json +0 -9
  55. package/examples/desktop-notes/ui.ts +0 -176
  56. package/examples/dupe-finder/README.md +0 -78
  57. package/examples/dupe-finder/bench.mjs +0 -120
  58. package/examples/dupe-finder/main.ts +0 -87
  59. package/examples/fibonacci/README.md +0 -89
  60. package/examples/fibonacci/bench.mjs +0 -87
  61. package/examples/fibonacci/main.ts +0 -21
  62. package/examples/hello-world/README.md +0 -62
  63. package/examples/hello-world/bench.mjs +0 -66
  64. package/examples/hello-world/main.ts +0 -7
  65. package/examples/json-server/README.md +0 -132
  66. package/examples/json-server/bench.mjs +0 -263
  67. package/examples/json-server/main.ts +0 -67
  68. package/examples/mandelbrot-png/README.md +0 -63
  69. package/examples/mandelbrot-png/bench.mjs +0 -95
  70. package/examples/mandelbrot-png/main.ts +0 -98
  71. package/examples/mandelbrot-png/preview.png +0 -0
  72. package/examples/marked-cli/README.md +0 -174
  73. package/examples/marked-cli/bench.mjs +0 -178
  74. package/examples/marked-cli/main.ts +0 -410
  75. package/examples/marked-cli/parity.mjs +0 -185
  76. package/examples/marked-cli/vendor/marked/LICENSE +0 -44
  77. package/examples/marked-cli/vendor/marked/VENDOR.md +0 -26
  78. package/examples/openai-chat/README.md +0 -148
  79. package/examples/openai-chat/bench.mjs +0 -175
  80. package/examples/openai-chat/main.ts +0 -488
  81. package/examples/react-compiler/README.md +0 -185
  82. package/examples/react-compiler/bench.mjs +0 -181
  83. package/examples/react-compiler/main.ts +0 -324
  84. package/examples/react-compiler/parity.mjs +0 -362
  85. package/examples/react-compiler/run-node.mjs +0 -90
  86. package/examples/react-compiler/vendor/babel/LICENSE +0 -22
  87. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +0 -15
  88. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +0 -51
  89. package/examples/react-compiler/vendor/charcodes/package.json +0 -25
  90. package/examples/react-compiler/vendor/invariant/LICENSE +0 -21
  91. package/examples/react-compiler/vendor/invariant/invariant.cjs +0 -51
  92. package/examples/react-compiler/vendor/invariant/invariant.d.cts +0 -11
  93. package/examples/react-compiler/vendor/invariant/types/LICENSE +0 -21
  94. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +0 -19
  95. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +0 -19
  96. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +0 -19
  97. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +0 -19
  98. package/examples/react-compiler/vendor/js-tokens/LICENSE +0 -21
  99. package/examples/react-compiler/vendor/js-tokens/index.cjs +0 -23
  100. package/examples/react-compiler/vendor/js-tokens/index.d.cts +0 -13
  101. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +0 -20
  102. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +0 -337
  103. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +0 -384
  104. package/examples/react-compiler/vendor/jsesc/types/LICENSE +0 -21
  105. package/examples/react-compiler/vendor/picocolors/LICENSE +0 -15
  106. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +0 -75
  107. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +0 -5
  108. package/examples/react-compiler/vendor/picocolors/types.d.ts +0 -51
  109. package/examples/react-compiler/vendor/react-compiler/LICENSE +0 -21
  110. package/examples/react-compiler/vendor/stubs/babel-core.ts +0 -31
  111. package/examples/react-compiler/vendor/stubs/debug.ts +0 -18
  112. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +0 -13
  113. package/examples/react-compiler/vendor/stubs/pretty-format.ts +0 -18
  114. package/examples/react-compiler/vendor/zod/LICENSE +0 -21
  115. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +0 -9
  116. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +0 -5
  117. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +0 -49
  118. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +0 -48
  119. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +0 -50
  120. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +0 -6
  121. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +0 -126
  122. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +0 -39
  123. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +0 -12
  124. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +0 -78
  125. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +0 -2
  126. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +0 -12
  127. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +0 -12
  128. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +0 -131
  129. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +0 -54
  130. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +0 -12
  131. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +0 -40
  132. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +0 -12
  133. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +0 -76
  134. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +0 -76
  135. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +0 -27
  136. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +0 -27
  137. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +0 -13
  138. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +0 -61
  139. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +0 -38
  140. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +0 -20
  141. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +0 -5
  142. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +0 -8
  143. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +0 -11
  144. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +0 -20
  145. package/examples/react-compiler/vendor.mjs +0 -688
  146. package/examples/todo-cli/README.md +0 -69
  147. package/examples/todo-cli/bench.mjs +0 -89
  148. package/examples/todo-cli/main.ts +0 -92
  149. package/examples/yaml-cli/README.md +0 -152
  150. package/examples/yaml-cli/bench.mjs +0 -265
  151. package/examples/yaml-cli/main.ts +0 -251
  152. package/examples/yaml-cli/parity.mjs +0 -156
  153. package/examples/yaml-cli/vendor/yaml/LICENSE +0 -13
  154. package/examples/yaml-cli/vendor/yaml/VENDOR.md +0 -25
  155. package/performance/README.md +0 -248
  156. package/performance/any-dynamic.ts +0 -21
  157. package/performance/any-record-view.ts +0 -20
  158. package/performance/arr-for-of.ts +0 -29
  159. package/performance/arr-hof.ts +0 -21
  160. package/performance/arr-push-index.ts +0 -15
  161. package/performance/arr-push-local.ts +0 -39
  162. package/performance/arr-slice-concat.ts +0 -24
  163. package/performance/arr-sort.ts +0 -21
  164. package/performance/async-await.ts +0 -24
  165. package/performance/async-promise-all.ts +0 -38
  166. package/performance/bigint-arith.ts +0 -36
  167. package/performance/buf-encode.ts +0 -29
  168. package/performance/class-accessors.ts +0 -48
  169. package/performance/class-dispatch.ts +0 -52
  170. package/performance/date-format.ts +0 -18
  171. package/performance/events-emit.ts +0 -27
  172. package/performance/exc-throw-rare.ts +0 -25
  173. package/performance/exc-try-catch.ts +0 -26
  174. package/performance/fn-closures.ts +0 -29
  175. package/performance/fn-recursion-tree.ts +0 -31
  176. package/performance/fn-rest-spread.ts +0 -43
  177. package/performance/gen-for-of.ts +0 -46
  178. package/performance/gen-next.ts +0 -32
  179. package/performance/iter-helpers.ts +0 -38
  180. package/performance/json-any.ts +0 -30
  181. package/performance/json-roundtrip.ts +0 -27
  182. package/performance/map-delete.ts +0 -24
  183. package/performance/map-iterate.ts +0 -26
  184. package/performance/map-number-keys.ts +0 -37
  185. package/performance/map-string-keys.ts +0 -22
  186. package/performance/num-arith-loop.ts +0 -14
  187. package/performance/num-bitwise.ts +0 -21
  188. package/performance/num-hash-imul.ts +0 -36
  189. package/performance/num-mod-int.ts +0 -16
  190. package/performance/num-to-string.ts +0 -16
  191. package/performance/obj-alloc.ts +0 -32
  192. package/performance/obj-keys-entries.ts +0 -44
  193. package/performance/obj-optional-chain.ts +0 -42
  194. package/performance/obj-record-dict.ts +0 -24
  195. package/performance/obj-spread-destructure.ts +0 -40
  196. package/performance/regex-exec.ts +0 -29
  197. package/performance/regex-replace-fn.ts +0 -24
  198. package/performance/regex-site.ts +0 -28
  199. package/performance/set-ops.ts +0 -20
  200. package/performance/str-char-scan.ts +0 -35
  201. package/performance/str-concat-plus.ts +0 -18
  202. package/performance/str-concat.ts +0 -24
  203. package/performance/str-methods.ts +0 -24
  204. package/performance/str-short-scan.ts +0 -26
  205. package/performance/str-split-join.ts +0 -23
  206. package/performance/str-switch-compare.ts +0 -50
  207. package/performance/str-template.ts +0 -16
  208. package/performance/str-unicode.ts +0 -25
  209. package/performance/typed-array.ts +0 -30
  210. package/performance/union-switch.ts +0 -57
  211. package/performance/union-typeof.ts +0 -40
  212. package/performance/wasm-call.ts +0 -63
  213. package/tsparser/check.go +0 -158
  214. package/tsparser/go.mod +0 -14
  215. package/tsparser/go.sum +0 -22
  216. package/tsparser/main.go +0 -363
  217. package/tsparser/tsparser.exe +0 -4
@@ -0,0 +1,1000 @@
1
+ // Copyright 2015, 2018, 2019 Opsmate, Inc. All rights reserved.
2
+ // Copyright 2015 The Go Authors. All rights reserved.
3
+ // Use of this source code is governed by a BSD-style
4
+ // license that can be found in the LICENSE file.
5
+
6
+ // Package pkcs12 implements some of PKCS#12 (also known as P12 or PFX).
7
+ // It is intended for decoding DER-encoded P12/PFX files for use with the crypto/tls
8
+ // package, and for encoding P12/PFX files for use by legacy applications which
9
+ // do not support newer formats. Since PKCS#12 uses weak encryption
10
+ // primitives, it SHOULD NOT be used for new applications.
11
+ //
12
+ // Note that only DER-encoded PKCS#12 files are supported, even though PKCS#12
13
+ // allows BER encoding. This is because encoding/asn1 only supports DER.
14
+ //
15
+ // This package is forked from golang.org/x/crypto/pkcs12, which is frozen.
16
+ // The implementation is distilled from https://tools.ietf.org/html/rfc7292
17
+ // and referenced documents.
18
+ package pkcs12 // import "software.sslmate.com/src/go-pkcs12"
19
+
20
+ import (
21
+ "crypto/ecdsa"
22
+ "crypto/rand"
23
+ "crypto/rsa"
24
+ "crypto/sha1"
25
+ "crypto/x509"
26
+ "crypto/x509/pkix"
27
+ "encoding/asn1"
28
+ "encoding/hex"
29
+ "encoding/pem"
30
+ "errors"
31
+ "fmt"
32
+ "io"
33
+ )
34
+
35
+ // DefaultPassword is the string "changeit", a commonly-used password for
36
+ // PKCS#12 files.
37
+ const DefaultPassword = "changeit"
38
+
39
+ // An Encoder contains methods for encoding PKCS#12 files. This package
40
+ // defines several different Encoders with different parameters.
41
+ // An Encoder is safe for concurrent use by multiple goroutines.
42
+ type Encoder struct {
43
+ macAlgorithm asn1.ObjectIdentifier
44
+ certAlgorithm asn1.ObjectIdentifier
45
+ keyAlgorithm asn1.ObjectIdentifier
46
+ macIterations int
47
+ encryptionIterations int
48
+ saltLen int
49
+ rand io.Reader
50
+ }
51
+
52
+ // WithIterations creates a new Encoder identical to enc except that
53
+ // it will use the given number of KDF iterations for deriving the MAC
54
+ // and encryption keys.
55
+ //
56
+ // Note that even with a large number of iterations, a weak
57
+ // password can still be brute-forced in much less time than it would
58
+ // take to brute-force a high-entropy encrytion key. For the best
59
+ // security, don't worry about the number of iterations and just
60
+ // use a high-entropy password (e.g. one generated with `openssl rand -hex 16`).
61
+ // See https://neilmadden.blog/2023/01/09/on-pbkdf2-iterations/ for more detail.
62
+ //
63
+ // Panics if iterations is less than 1.
64
+ func (enc Encoder) WithIterations(iterations int) *Encoder {
65
+ if iterations < 1 {
66
+ panic("pkcs12: number of iterations is less than 1")
67
+ }
68
+ enc.macIterations = iterations
69
+ enc.encryptionIterations = iterations
70
+ return &enc
71
+ }
72
+
73
+ // WithRand creates a new Encoder identical to enc except that
74
+ // it will use the given io.Reader for its random number generator
75
+ // instead of [crypto/rand.Reader].
76
+ func (enc Encoder) WithRand(rand io.Reader) *Encoder {
77
+ enc.rand = rand
78
+ return &enc
79
+ }
80
+
81
+ // LegacyRC2 encodes PKCS#12 files using weak algorithms that were
82
+ // traditionally used in PKCS#12 files, including those produced
83
+ // by OpenSSL before 3.0.0, go-pkcs12 before 0.3.0, and Java when
84
+ // keystore.pkcs12.legacy is defined. Specifically, certificates
85
+ // are encrypted using PBE with RC2, and keys are encrypted using PBE
86
+ // with 3DES, using keys derived with 2048 iterations of HMAC-SHA-1.
87
+ // MACs use HMAC-SHA-1 with keys derived with 1 iteration of HMAC-SHA-1.
88
+ //
89
+ // Due to the weak encryption, it is STRONGLY RECOMMENDED that you use [DefaultPassword]
90
+ // when encoding PKCS#12 files using this encoder, and protect the PKCS#12 files
91
+ // using other means.
92
+ //
93
+ // By default, OpenSSL 3 can't decode PKCS#12 files created using this encoder.
94
+ // For better compatibility, use [LegacyDES]. For better security, use
95
+ // [Modern2023].
96
+ var LegacyRC2 = &Encoder{
97
+ macAlgorithm: oidSHA1,
98
+ certAlgorithm: oidPBEWithSHAAnd40BitRC2CBC,
99
+ keyAlgorithm: oidPBEWithSHAAnd3KeyTripleDESCBC,
100
+ macIterations: 1,
101
+ encryptionIterations: 2048,
102
+ saltLen: 8,
103
+ rand: rand.Reader,
104
+ }
105
+
106
+ // LegacyDES encodes PKCS#12 files using weak algorithms that are
107
+ // supported by a wide variety of software. Certificates and keys
108
+ // are encrypted using PBE with 3DES using keys derived with 2048
109
+ // iterations of HMAC-SHA-1. MACs use HMAC-SHA-1 with keys derived
110
+ // with 1 iteration of HMAC-SHA-1. These are the same parameters
111
+ // used by OpenSSL's -descert option. As of 2023, this encoder is
112
+ // likely to produce files that can be read by the most software.
113
+ //
114
+ // Due to the weak encryption, it is STRONGLY RECOMMENDED that you use [DefaultPassword]
115
+ // when encoding PKCS#12 files using this encoder, and protect the PKCS#12 files
116
+ // using other means. To create more secure PKCS#12 files, use [Modern2023].
117
+ var LegacyDES = &Encoder{
118
+ macAlgorithm: oidSHA1,
119
+ certAlgorithm: oidPBEWithSHAAnd3KeyTripleDESCBC,
120
+ keyAlgorithm: oidPBEWithSHAAnd3KeyTripleDESCBC,
121
+ macIterations: 1,
122
+ encryptionIterations: 2048,
123
+ saltLen: 8,
124
+ rand: rand.Reader,
125
+ }
126
+
127
+ // Passwordless encodes PKCS#12 files without any encryption or MACs.
128
+ // A lot of software has trouble reading such files, so it's probably only
129
+ // useful for creating Java trust stores using [Encoder.EncodeTrustStore]
130
+ // or [Encoder.EncodeTrustStoreEntries].
131
+ //
132
+ // When using this encoder, you MUST specify an empty password.
133
+ var Passwordless = &Encoder{
134
+ macAlgorithm: nil,
135
+ certAlgorithm: nil,
136
+ keyAlgorithm: nil,
137
+ rand: rand.Reader,
138
+ }
139
+
140
+ // Modern2023 encodes PKCS#12 files using algorithms that are considered modern
141
+ // as of 2023. Private keys and certificates are encrypted using PBES2 with
142
+ // PBKDF2-HMAC-SHA-256 and AES-256-CBC. The MAC algorithm is HMAC-SHA-2. These
143
+ // are the same algorithms used by OpenSSL 3 (by default), Java 20 (by default),
144
+ // and Windows Server 2019 (when "stronger" is used).
145
+ //
146
+ // Files produced with this encoder can be read by OpenSSL 1.1.1 and higher,
147
+ // Java 12 and higher, and Windows Server 2019 and higher.
148
+ //
149
+ // For passwords, it is RECOMMENDED that you do one of the following:
150
+ // 1) Use [DefaultPassword] and protect the file using other means, or
151
+ // 2) Use a high-entropy password, such as one generated with `openssl rand -hex 16`.
152
+ //
153
+ // You SHOULD NOT use a lower-entropy password with this encoder because the number of KDF
154
+ // iterations is only 2048 and doesn't provide meaningful protection against
155
+ // brute-forcing. You can increase the number of iterations using [Encoder.WithIterations],
156
+ // but as https://neilmadden.blog/2023/01/09/on-pbkdf2-iterations/ explains, this doesn't
157
+ // help as much as you think.
158
+ var Modern2023 = &Encoder{
159
+ macAlgorithm: oidSHA256,
160
+ certAlgorithm: oidPBES2,
161
+ keyAlgorithm: oidPBES2,
162
+ macIterations: 2048,
163
+ encryptionIterations: 2048,
164
+ saltLen: 16,
165
+ rand: rand.Reader,
166
+ }
167
+
168
+ // Modern2026 encodes PKCS#12 files using algorithms that are considered modern
169
+ // as of 2026. Private keys and certificates are encrypted using PBES2 with
170
+ // PBKDF2-HMAC-SHA-256 and AES-256-CBC. The MAC algorithm is PBMAC1 with
171
+ // PBKDF2-HMAC-SHA-256 and HMAC-SHA256.
172
+ //
173
+ // Files produced with this encoder can be read by OpenSSL 3.4.0 and higher and
174
+ // Java 26 and higher.
175
+ //
176
+ // For passwords, it is RECOMMENDED that you do one of the following:
177
+ // 1) Use [DefaultPassword] and protect the file using other means, or
178
+ // 2) Use a high-entropy password, such as one generated with `openssl rand -hex 16`.
179
+ //
180
+ // You SHOULD NOT use a lower-entropy password with this encoder because the number of KDF
181
+ // iterations is only 2048 and doesn't provide meaningful protection against
182
+ // brute-forcing. You can increase the number of iterations using [Encoder.WithIterations],
183
+ // but as https://neilmadden.blog/2023/01/09/on-pbkdf2-iterations/ explains, this doesn't
184
+ // help as much as you think.
185
+ var Modern2026 = &Encoder{
186
+ macAlgorithm: oidPBMAC1,
187
+ certAlgorithm: oidPBES2,
188
+ keyAlgorithm: oidPBES2,
189
+ macIterations: 2048,
190
+ encryptionIterations: 2048,
191
+ saltLen: 16,
192
+ rand: rand.Reader,
193
+ }
194
+
195
+ // Legacy encodes PKCS#12 files using weak, legacy parameters that work in
196
+ // a wide variety of software.
197
+ //
198
+ // Currently, this encoder is the same as [LegacyDES], but this
199
+ // may change in the future if another encoder is found to provide better
200
+ // compatibility.
201
+ //
202
+ // Due to the weak encryption, it is STRONGLY RECOMMENDED that you use [DefaultPassword]
203
+ // when encoding PKCS#12 files using this encoder, and protect the PKCS#12 files
204
+ // using other means.
205
+ var Legacy = LegacyDES
206
+
207
+ // Modern encodes PKCS#12 files using modern, robust parameters.
208
+ //
209
+ // Currently, this encoder is the same as [Modern2023], but this
210
+ // may change in the future to keep up with modern practices.
211
+ var Modern = Modern2023
212
+
213
+ var (
214
+ oidDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 1})
215
+ oidEncryptedDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 6})
216
+
217
+ oidFriendlyName = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 20})
218
+ oidLocalKeyID = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 21})
219
+ oidMicrosoftCSPName = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 311, 17, 1})
220
+
221
+ oidJavaTrustStore = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 113894, 746875, 1, 1})
222
+ oidAnyExtendedKeyUsage = asn1.ObjectIdentifier([]int{2, 5, 29, 37, 0})
223
+ )
224
+
225
+ type pfxPdu struct {
226
+ Version int
227
+ AuthSafe contentInfo
228
+ MacData macData `asn1:"optional"`
229
+ }
230
+
231
+ type contentInfo struct {
232
+ ContentType asn1.ObjectIdentifier
233
+ Content asn1.RawValue `asn1:"tag:0,explicit,optional"`
234
+ }
235
+
236
+ type encryptedData struct {
237
+ Version int
238
+ EncryptedContentInfo encryptedContentInfo
239
+ }
240
+
241
+ type encryptedContentInfo struct {
242
+ ContentType asn1.ObjectIdentifier
243
+ ContentEncryptionAlgorithm pkix.AlgorithmIdentifier
244
+ EncryptedContent []byte `asn1:"tag:0,optional"`
245
+ }
246
+
247
+ func (i encryptedContentInfo) Algorithm() pkix.AlgorithmIdentifier {
248
+ return i.ContentEncryptionAlgorithm
249
+ }
250
+
251
+ func (i encryptedContentInfo) Data() []byte { return i.EncryptedContent }
252
+
253
+ func (i *encryptedContentInfo) SetData(data []byte) { i.EncryptedContent = data }
254
+
255
+ type safeBag struct {
256
+ Id asn1.ObjectIdentifier
257
+ Value asn1.RawValue `asn1:"tag:0,explicit"`
258
+ Attributes []pkcs12Attribute `asn1:"set,optional"`
259
+ }
260
+
261
+ func (bag *safeBag) hasAttribute(id asn1.ObjectIdentifier) bool {
262
+ for _, attr := range bag.Attributes {
263
+ if attr.Id.Equal(id) {
264
+ return true
265
+ }
266
+ }
267
+ return false
268
+ }
269
+
270
+ type pkcs12Attribute struct {
271
+ Id asn1.ObjectIdentifier
272
+ Value asn1.RawValue `asn1:"set"`
273
+ }
274
+
275
+ type encryptedPrivateKeyInfo struct {
276
+ AlgorithmIdentifier pkix.AlgorithmIdentifier
277
+ EncryptedData []byte
278
+ }
279
+
280
+ func (i encryptedPrivateKeyInfo) Algorithm() pkix.AlgorithmIdentifier {
281
+ return i.AlgorithmIdentifier
282
+ }
283
+
284
+ func (i encryptedPrivateKeyInfo) Data() []byte {
285
+ return i.EncryptedData
286
+ }
287
+
288
+ func (i *encryptedPrivateKeyInfo) SetData(data []byte) {
289
+ i.EncryptedData = data
290
+ }
291
+
292
+ // PEM block types
293
+ const (
294
+ certificateType = "CERTIFICATE"
295
+ privateKeyType = "PRIVATE KEY"
296
+ )
297
+
298
+ // unmarshal calls asn1.Unmarshal, but also returns an error if there is any
299
+ // trailing data after unmarshaling.
300
+ func unmarshal(in []byte, out interface{}) error {
301
+ trailing, err := asn1.Unmarshal(in, out)
302
+ if err != nil {
303
+ return err
304
+ }
305
+ if len(trailing) != 0 {
306
+ return errors.New("pkcs12: trailing data found")
307
+ }
308
+ return nil
309
+ }
310
+
311
+ // ToPEM converts all "safe bags" contained in pfxData to PEM blocks.
312
+ //
313
+ // Deprecated: ToPEM creates invalid PEM blocks (private keys
314
+ // are encoded as raw RSA or EC private keys rather than PKCS#8 despite being
315
+ // labeled "PRIVATE KEY"). To decode a PKCS#12 file, use [DecodeChain] instead,
316
+ // and use the [encoding/pem] package to convert to PEM if necessary.
317
+ func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) {
318
+ encodedPassword, err := bmpStringZeroTerminated(password)
319
+ if err != nil {
320
+ return nil, ErrIncorrectPassword
321
+ }
322
+
323
+ bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword, 2, 2)
324
+
325
+ if err != nil {
326
+ return nil, err
327
+ }
328
+
329
+ blocks := make([]*pem.Block, 0, len(bags))
330
+ for _, bag := range bags {
331
+ block, err := convertBag(&bag, encodedPassword)
332
+ if err != nil {
333
+ return nil, err
334
+ }
335
+ blocks = append(blocks, block)
336
+ }
337
+
338
+ return blocks, nil
339
+ }
340
+
341
+ func convertBag(bag *safeBag, password []byte) (*pem.Block, error) {
342
+ block := &pem.Block{
343
+ Headers: make(map[string]string),
344
+ }
345
+
346
+ for _, attribute := range bag.Attributes {
347
+ k, v, err := convertAttribute(&attribute)
348
+ if err != nil {
349
+ return nil, err
350
+ }
351
+ block.Headers[k] = v
352
+ }
353
+
354
+ switch {
355
+ case bag.Id.Equal(oidCertBag):
356
+ block.Type = certificateType
357
+ certsData, err := decodeCertBag(bag.Value.Bytes)
358
+ if err != nil {
359
+ return nil, err
360
+ }
361
+ block.Bytes = certsData
362
+ case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
363
+ block.Type = privateKeyType
364
+
365
+ key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password)
366
+ if err != nil {
367
+ return nil, err
368
+ }
369
+
370
+ switch key := key.(type) {
371
+ case *rsa.PrivateKey:
372
+ block.Bytes = x509.MarshalPKCS1PrivateKey(key)
373
+ case *ecdsa.PrivateKey:
374
+ block.Bytes, err = x509.MarshalECPrivateKey(key)
375
+ if err != nil {
376
+ return nil, err
377
+ }
378
+ default:
379
+ return nil, errors.New("pkcs12: found unknown private key type in PKCS#8 wrapping")
380
+ }
381
+ default:
382
+ return nil, errors.New("pkcs12: don't know how to convert a safe bag of type " + bag.Id.String())
383
+ }
384
+ return block, nil
385
+ }
386
+
387
+ func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) {
388
+ isString := false
389
+
390
+ switch {
391
+ case attribute.Id.Equal(oidFriendlyName):
392
+ key = "friendlyName"
393
+ isString = true
394
+ case attribute.Id.Equal(oidLocalKeyID):
395
+ key = "localKeyId"
396
+ case attribute.Id.Equal(oidMicrosoftCSPName):
397
+ // This key is chosen to match OpenSSL.
398
+ key = "Microsoft CSP Name"
399
+ isString = true
400
+ default:
401
+ return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String())
402
+ }
403
+
404
+ if isString {
405
+ if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil {
406
+ return "", "", err
407
+ }
408
+ if value, err = decodeBMPString(attribute.Value.Bytes); err != nil {
409
+ return "", "", err
410
+ }
411
+ } else {
412
+ var id []byte
413
+ if err := unmarshal(attribute.Value.Bytes, &id); err != nil {
414
+ return "", "", err
415
+ }
416
+ value = hex.EncodeToString(id)
417
+ }
418
+
419
+ return key, value, nil
420
+ }
421
+
422
+ // Decode extracts a certificate and private key from pfxData, which must be a DER-encoded PKCS#12 file. This function
423
+ // assumes that there is only one certificate and only one private key in the
424
+ // pfxData. Since PKCS#12 files often contain more than one certificate, you
425
+ // probably want to use [DecodeChain] instead.
426
+ func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) {
427
+ var caCerts []*x509.Certificate
428
+ privateKey, certificate, caCerts, err = DecodeChain(pfxData, password)
429
+ if len(caCerts) != 0 {
430
+ err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU")
431
+ }
432
+ return
433
+ }
434
+
435
+ // DecodeChain extracts a certificate, a CA certificate chain, and private key
436
+ // from pfxData, which must be a DER-encoded PKCS#12 file. This function assumes that there is at least one certificate
437
+ // and only one private key in the pfxData. The first certificate is assumed to
438
+ // be the leaf certificate, and subsequent certificates, if any, are assumed to
439
+ // comprise the CA certificate chain.
440
+ func DecodeChain(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, caCerts []*x509.Certificate, err error) {
441
+ encodedPassword, err := bmpStringZeroTerminated(password)
442
+ if err != nil {
443
+ return nil, nil, nil, err
444
+ }
445
+
446
+ bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword, 1, 2)
447
+ if err != nil {
448
+ return nil, nil, nil, err
449
+ }
450
+
451
+ for _, bag := range bags {
452
+ switch {
453
+ case bag.Id.Equal(oidCertBag):
454
+ certsData, err := decodeCertBag(bag.Value.Bytes)
455
+ if err != nil {
456
+ return nil, nil, nil, err
457
+ }
458
+ certs, err := x509.ParseCertificates(certsData)
459
+ if err != nil {
460
+ return nil, nil, nil, err
461
+ }
462
+ if len(certs) != 1 {
463
+ err = errors.New("pkcs12: expected exactly one certificate in the certBag")
464
+ return nil, nil, nil, err
465
+ }
466
+ if certificate == nil {
467
+ certificate = certs[0]
468
+ } else {
469
+ caCerts = append(caCerts, certs[0])
470
+ }
471
+
472
+ case bag.Id.Equal(oidKeyBag):
473
+ if privateKey != nil {
474
+ err = errors.New("pkcs12: expected exactly one key bag")
475
+ return nil, nil, nil, err
476
+ }
477
+
478
+ if privateKey, err = x509.ParsePKCS8PrivateKey(bag.Value.Bytes); err != nil {
479
+ return nil, nil, nil, err
480
+ }
481
+ case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
482
+ if privateKey != nil {
483
+ err = errors.New("pkcs12: expected exactly one key bag")
484
+ return nil, nil, nil, err
485
+ }
486
+
487
+ if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil {
488
+ return nil, nil, nil, err
489
+ }
490
+ }
491
+ }
492
+
493
+ if certificate == nil {
494
+ return nil, nil, nil, errors.New("pkcs12: certificate missing")
495
+ }
496
+ if privateKey == nil {
497
+ return nil, nil, nil, errors.New("pkcs12: private key missing")
498
+ }
499
+
500
+ return
501
+ }
502
+
503
+ // DecodeTrustStore extracts the certificates from pfxData, which must be a DER-encoded
504
+ // PKCS#12 file containing exclusively certificates with attribute 2.16.840.1.113894.746875.1.1,
505
+ // which is used by Java to designate a trust anchor.
506
+ //
507
+ // If the password argument is empty, DecodeTrustStore will decode either password-less
508
+ // PKCS#12 files (i.e. those without encryption) or files with a literal empty password.
509
+ func DecodeTrustStore(pfxData []byte, password string) (certs []*x509.Certificate, err error) {
510
+ encodedPassword, err := bmpStringZeroTerminated(password)
511
+ if err != nil {
512
+ return nil, err
513
+ }
514
+
515
+ bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword, 1, 1)
516
+ if err != nil {
517
+ return nil, err
518
+ }
519
+
520
+ for _, bag := range bags {
521
+ switch {
522
+ case bag.Id.Equal(oidCertBag):
523
+ if !bag.hasAttribute(oidJavaTrustStore) {
524
+ return nil, errors.New("pkcs12: trust store contains a certificate that is not marked as trusted")
525
+ }
526
+ certsData, err := decodeCertBag(bag.Value.Bytes)
527
+ if err != nil {
528
+ return nil, err
529
+ }
530
+ parsedCerts, err := x509.ParseCertificates(certsData)
531
+ if err != nil {
532
+ return nil, err
533
+ }
534
+
535
+ if len(parsedCerts) != 1 {
536
+ err = errors.New("pkcs12: expected exactly one certificate in the certBag")
537
+ return nil, err
538
+ }
539
+
540
+ certs = append(certs, parsedCerts[0])
541
+
542
+ default:
543
+ return nil, errors.New("pkcs12: expected only certificate bags")
544
+ }
545
+ }
546
+
547
+ return
548
+ }
549
+
550
+ func getSafeContents(p12Data, password []byte, expectedItemsMin int, expectedItemsMax int) (bags []safeBag, updatedPassword []byte, err error) {
551
+ pfx := new(pfxPdu)
552
+ if err := unmarshal(p12Data, pfx); err != nil {
553
+ return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error())
554
+ }
555
+
556
+ if pfx.Version != 3 {
557
+ return nil, nil, NotImplementedError("can only decode v3 PFX PDU's")
558
+ }
559
+
560
+ if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) {
561
+ return nil, nil, NotImplementedError("only password-protected PFX is implemented")
562
+ }
563
+
564
+ // unmarshal the explicit bytes in the content for type 'data'
565
+ if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil {
566
+ return nil, nil, err
567
+ }
568
+
569
+ if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 {
570
+ if !(len(password) == 2 && password[0] == 0 && password[1] == 0) {
571
+ return nil, nil, errors.New("pkcs12: no MAC in data")
572
+ }
573
+ } else if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil {
574
+ if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 {
575
+ // some implementations use an empty byte array
576
+ // for the empty string password try one more
577
+ // time with empty-empty password
578
+ password = nil
579
+ err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password)
580
+ }
581
+ if err != nil {
582
+ return nil, nil, err
583
+ }
584
+ }
585
+
586
+ var authenticatedSafe []contentInfo
587
+ if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil {
588
+ return nil, nil, err
589
+ }
590
+
591
+ if len(authenticatedSafe) < expectedItemsMin || len(authenticatedSafe) > expectedItemsMax {
592
+ if expectedItemsMin == expectedItemsMax {
593
+ return nil, nil, NotImplementedError(fmt.Sprintf("expected exactly %d items in the authenticated safe, but this file has %d", expectedItemsMin, len(authenticatedSafe)))
594
+ }
595
+ return nil, nil, NotImplementedError(fmt.Sprintf("expected between %d and %d items in the authenticated safe, but this file has %d", expectedItemsMin, expectedItemsMax, len(authenticatedSafe)))
596
+ }
597
+
598
+ for _, ci := range authenticatedSafe {
599
+ var data []byte
600
+
601
+ switch {
602
+ case ci.ContentType.Equal(oidDataContentType):
603
+ if err := unmarshal(ci.Content.Bytes, &data); err != nil {
604
+ return nil, nil, err
605
+ }
606
+ case ci.ContentType.Equal(oidEncryptedDataContentType):
607
+ var encryptedData encryptedData
608
+ if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil {
609
+ return nil, nil, err
610
+ }
611
+ if encryptedData.Version != 0 {
612
+ return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported")
613
+ }
614
+ if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil {
615
+ return nil, nil, err
616
+ }
617
+ default:
618
+ return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe")
619
+ }
620
+
621
+ var safeContents []safeBag
622
+ if err := unmarshal(data, &safeContents); err != nil {
623
+ return nil, nil, err
624
+ }
625
+ bags = append(bags, safeContents...)
626
+ }
627
+
628
+ return bags, password, nil
629
+ }
630
+
631
+ // Encode is equivalent to LegacyRC2.WithRand(rand).Encode.
632
+ // See [Encoder.Encode] and [LegacyRC2] for details.
633
+ //
634
+ // Deprecated: for the same behavior, use LegacyRC2.Encode; for
635
+ // better compatibility, use Legacy.Encode; for better
636
+ // security, use Modern.Encode.
637
+ func Encode(rand io.Reader, privateKey interface{}, certificate *x509.Certificate, caCerts []*x509.Certificate, password string) (pfxData []byte, err error) {
638
+ return LegacyRC2.WithRand(rand).Encode(privateKey, certificate, caCerts, password)
639
+ }
640
+
641
+ // Encode produces pfxData containing one private key (privateKey), an
642
+ // end-entity certificate (certificate), and any number of CA certificates
643
+ // (caCerts).
644
+ //
645
+ // The pfxData is encrypted and authenticated with keys derived from
646
+ // the provided password.
647
+ //
648
+ // Encode emulates the behavior of OpenSSL's PKCS12_create: it creates two
649
+ // SafeContents: one that's encrypted with the certificate encryption algorithm
650
+ // and contains the certificates, and another that is unencrypted and contains the
651
+ // private key shrouded with the key encryption algorithm. The private key bag and
652
+ // the end-entity certificate bag have the LocalKeyId attribute set to the SHA-1
653
+ // fingerprint of the end-entity certificate.
654
+ func (enc *Encoder) Encode(privateKey interface{}, certificate *x509.Certificate, caCerts []*x509.Certificate, password string) (pfxData []byte, err error) {
655
+ if enc.macAlgorithm == nil && enc.certAlgorithm == nil && enc.keyAlgorithm == nil && password != "" {
656
+ return nil, errors.New("pkcs12: password must be empty")
657
+ }
658
+
659
+ encodedPassword, err := bmpStringZeroTerminated(password)
660
+ if err != nil {
661
+ return nil, err
662
+ }
663
+
664
+ var pfx pfxPdu
665
+ pfx.Version = 3
666
+
667
+ var certFingerprint = sha1.Sum(certificate.Raw)
668
+ var localKeyIdAttr pkcs12Attribute
669
+ localKeyIdAttr.Id = oidLocalKeyID
670
+ localKeyIdAttr.Value.Class = 0
671
+ localKeyIdAttr.Value.Tag = 17
672
+ localKeyIdAttr.Value.IsCompound = true
673
+ if localKeyIdAttr.Value.Bytes, err = asn1.Marshal(certFingerprint[:]); err != nil {
674
+ return nil, err
675
+ }
676
+
677
+ var certBags []safeBag
678
+ if certBag, err := makeCertBag(certificate.Raw, []pkcs12Attribute{localKeyIdAttr}); err != nil {
679
+ return nil, err
680
+ } else {
681
+ certBags = append(certBags, *certBag)
682
+ }
683
+
684
+ for _, cert := range caCerts {
685
+ if certBag, err := makeCertBag(cert.Raw, []pkcs12Attribute{}); err != nil {
686
+ return nil, err
687
+ } else {
688
+ certBags = append(certBags, *certBag)
689
+ }
690
+ }
691
+
692
+ var keyBag safeBag
693
+ if enc.keyAlgorithm == nil {
694
+ keyBag.Id = oidKeyBag
695
+ keyBag.Value.Class = 2
696
+ keyBag.Value.Tag = 0
697
+ keyBag.Value.IsCompound = true
698
+ if keyBag.Value.Bytes, err = x509.MarshalPKCS8PrivateKey(privateKey); err != nil {
699
+ return nil, err
700
+ }
701
+ } else {
702
+ keyBag.Id = oidPKCS8ShroundedKeyBag
703
+ keyBag.Value.Class = 2
704
+ keyBag.Value.Tag = 0
705
+ keyBag.Value.IsCompound = true
706
+ if keyBag.Value.Bytes, err = encodePkcs8ShroudedKeyBag(enc.rand, privateKey, enc.keyAlgorithm, encodedPassword, enc.encryptionIterations, enc.saltLen); err != nil {
707
+ return nil, err
708
+ }
709
+ }
710
+ keyBag.Attributes = append(keyBag.Attributes, localKeyIdAttr)
711
+
712
+ // Construct an authenticated safe with two SafeContents.
713
+ // The first SafeContents is encrypted and contains the cert bags.
714
+ // The second SafeContents is unencrypted and contains the shrouded key bag.
715
+ var authenticatedSafe [2]contentInfo
716
+ if authenticatedSafe[0], err = makeSafeContents(enc.rand, certBags, enc.certAlgorithm, encodedPassword, enc.encryptionIterations, enc.saltLen); err != nil {
717
+ return nil, err
718
+ }
719
+ if authenticatedSafe[1], err = makeSafeContents(enc.rand, []safeBag{keyBag}, nil, nil, 0, 0); err != nil {
720
+ return nil, err
721
+ }
722
+
723
+ var authenticatedSafeBytes []byte
724
+ if authenticatedSafeBytes, err = asn1.Marshal(authenticatedSafe[:]); err != nil {
725
+ return nil, err
726
+ }
727
+
728
+ if enc.macAlgorithm != nil {
729
+ macSalt := make([]byte, enc.saltLen)
730
+ if _, err = enc.rand.Read(macSalt); err != nil {
731
+ return nil, err
732
+ }
733
+ pfx.MacData.Mac.Algorithm.Algorithm = enc.macAlgorithm
734
+ if enc.macAlgorithm.Equal(oidPBMAC1) {
735
+ var err error
736
+ pfx.MacData.Mac.Algorithm.Parameters.FullBytes, err = makePBMAC1Parameters(macSalt, enc.macIterations)
737
+ if err != nil {
738
+ return nil, err
739
+ }
740
+ } else {
741
+ pfx.MacData.MacSalt = macSalt
742
+ pfx.MacData.Iterations = enc.macIterations
743
+ }
744
+ if err = computeMac(&pfx.MacData, authenticatedSafeBytes, encodedPassword); err != nil {
745
+ return nil, err
746
+ }
747
+ }
748
+
749
+ pfx.AuthSafe.ContentType = oidDataContentType
750
+ pfx.AuthSafe.Content.Class = 2
751
+ pfx.AuthSafe.Content.Tag = 0
752
+ pfx.AuthSafe.Content.IsCompound = true
753
+ if pfx.AuthSafe.Content.Bytes, err = asn1.Marshal(authenticatedSafeBytes); err != nil {
754
+ return nil, err
755
+ }
756
+
757
+ if pfxData, err = asn1.Marshal(pfx); err != nil {
758
+ return nil, errors.New("pkcs12: error writing P12 data: " + err.Error())
759
+ }
760
+ return
761
+ }
762
+
763
+ // EncodeTrustStore is equivalent to LegacyRC2.WithRand(rand).EncodeTrustStore.
764
+ // See [Encoder.EncodeTrustStore] and [LegacyRC2] for details.
765
+ //
766
+ // Deprecated: for the same behavior, use LegacyRC2.EncodeTrustStore; to generate passwordless trust stores,
767
+ // use Passwordless.EncodeTrustStore.
768
+ func EncodeTrustStore(rand io.Reader, certs []*x509.Certificate, password string) (pfxData []byte, err error) {
769
+ return LegacyRC2.WithRand(rand).EncodeTrustStore(certs, password)
770
+ }
771
+
772
+ // EncodeTrustStore produces pfxData containing any number of CA certificates
773
+ // (certs) to be trusted. The certificates will be marked with a special OID that
774
+ // allow it to be used as a Java TrustStore in Java 1.8 and newer.
775
+ //
776
+ // EncodeTrustStore creates a single SafeContents that's optionally encrypted
777
+ // and contains the certificates.
778
+ //
779
+ // The Subject of the certificates are used as the Friendly Names (Aliases)
780
+ // within the resulting pfxData. If certificates share a Subject, then the
781
+ // resulting Friendly Names (Aliases) will be identical, which Java may treat as
782
+ // the same entry when used as a Java TrustStore, e.g. with `keytool`. To
783
+ // customize the Friendly Names, use [EncodeTrustStoreEntries].
784
+ func (enc *Encoder) EncodeTrustStore(certs []*x509.Certificate, password string) (pfxData []byte, err error) {
785
+ var certsWithFriendlyNames []TrustStoreEntry
786
+ for _, cert := range certs {
787
+ certsWithFriendlyNames = append(certsWithFriendlyNames, TrustStoreEntry{
788
+ Cert: cert,
789
+ FriendlyName: cert.Subject.String(),
790
+ })
791
+ }
792
+ return enc.EncodeTrustStoreEntries(certsWithFriendlyNames, password)
793
+ }
794
+
795
+ // TrustStoreEntry represents an entry in a Java TrustStore.
796
+ type TrustStoreEntry struct {
797
+ Cert *x509.Certificate
798
+ FriendlyName string
799
+ }
800
+
801
+ // EncodeTrustStoreEntries is equivalent to LegacyRC2.WithRand(rand).EncodeTrustStoreEntries.
802
+ // See [Encoder.EncodeTrustStoreEntries] and [LegacyRC2] for details.
803
+ //
804
+ // Deprecated: for the same behavior, use LegacyRC2.EncodeTrustStoreEntries; to generate passwordless trust stores,
805
+ // use Passwordless.EncodeTrustStoreEntries.
806
+ func EncodeTrustStoreEntries(rand io.Reader, entries []TrustStoreEntry, password string) (pfxData []byte, err error) {
807
+ return LegacyRC2.WithRand(rand).EncodeTrustStoreEntries(entries, password)
808
+ }
809
+
810
+ // EncodeTrustStoreEntries produces pfxData containing any number of CA
811
+ // certificates (entries) to be trusted. The certificates will be marked with a
812
+ // special OID that allow it to be used as a Java TrustStore in Java 1.8 and newer.
813
+ //
814
+ // This is identical to [Encoder.EncodeTrustStore], but also allows for setting specific
815
+ // Friendly Names (Aliases) to be used per certificate, by specifying a slice
816
+ // of TrustStoreEntry.
817
+ //
818
+ // If the same Friendly Name is used for more than one certificate, then the
819
+ // resulting Friendly Names (Aliases) in the pfxData will be identical, which Java
820
+ // may treat as the same entry when used as a Java TrustStore, e.g. with `keytool`.
821
+ //
822
+ // EncodeTrustStoreEntries creates a single SafeContents that's optionally
823
+ // encrypted and contains the certificates.
824
+ func (enc *Encoder) EncodeTrustStoreEntries(entries []TrustStoreEntry, password string) (pfxData []byte, err error) {
825
+ if enc.macAlgorithm == nil && enc.certAlgorithm == nil && password != "" {
826
+ return nil, errors.New("pkcs12: password must be empty")
827
+ }
828
+
829
+ encodedPassword, err := bmpStringZeroTerminated(password)
830
+ if err != nil {
831
+ return nil, err
832
+ }
833
+
834
+ var pfx pfxPdu
835
+ pfx.Version = 3
836
+
837
+ var certAttributes []pkcs12Attribute
838
+
839
+ extKeyUsageOidBytes, err := asn1.Marshal(oidAnyExtendedKeyUsage)
840
+ if err != nil {
841
+ return nil, err
842
+ }
843
+
844
+ // the oidJavaTrustStore attribute contains the EKUs for which
845
+ // this trust anchor will be valid
846
+ certAttributes = append(certAttributes, pkcs12Attribute{
847
+ Id: oidJavaTrustStore,
848
+ Value: asn1.RawValue{
849
+ Class: 0,
850
+ Tag: 17,
851
+ IsCompound: true,
852
+ Bytes: extKeyUsageOidBytes,
853
+ },
854
+ })
855
+
856
+ var certBags []safeBag
857
+ for _, entry := range entries {
858
+
859
+ bmpFriendlyName, err := bmpString(entry.FriendlyName)
860
+ if err != nil {
861
+ return nil, err
862
+ }
863
+
864
+ encodedFriendlyName, err := asn1.Marshal(asn1.RawValue{
865
+ Class: 0,
866
+ Tag: 30,
867
+ IsCompound: false,
868
+ Bytes: bmpFriendlyName,
869
+ })
870
+ if err != nil {
871
+ return nil, err
872
+ }
873
+
874
+ friendlyName := pkcs12Attribute{
875
+ Id: oidFriendlyName,
876
+ Value: asn1.RawValue{
877
+ Class: 0,
878
+ Tag: 17,
879
+ IsCompound: true,
880
+ Bytes: encodedFriendlyName,
881
+ },
882
+ }
883
+
884
+ certBag, err := makeCertBag(entry.Cert.Raw, append(certAttributes, friendlyName))
885
+ if err != nil {
886
+ return nil, err
887
+ }
888
+ certBags = append(certBags, *certBag)
889
+ }
890
+
891
+ // Construct an authenticated safe with one SafeContent.
892
+ // The SafeContents is contains the cert bags.
893
+ var authenticatedSafe [1]contentInfo
894
+ if authenticatedSafe[0], err = makeSafeContents(enc.rand, certBags, enc.certAlgorithm, encodedPassword, enc.encryptionIterations, enc.saltLen); err != nil {
895
+ return nil, err
896
+ }
897
+
898
+ var authenticatedSafeBytes []byte
899
+ if authenticatedSafeBytes, err = asn1.Marshal(authenticatedSafe[:]); err != nil {
900
+ return nil, err
901
+ }
902
+
903
+ if enc.macAlgorithm != nil {
904
+ macSalt := make([]byte, enc.saltLen)
905
+ if _, err = enc.rand.Read(macSalt); err != nil {
906
+ return nil, err
907
+ }
908
+ pfx.MacData.Mac.Algorithm.Algorithm = enc.macAlgorithm
909
+ if enc.macAlgorithm.Equal(oidPBMAC1) {
910
+ var err error
911
+ pfx.MacData.Mac.Algorithm.Parameters.FullBytes, err = makePBMAC1Parameters(macSalt, enc.macIterations)
912
+ if err != nil {
913
+ return nil, err
914
+ }
915
+ } else {
916
+ pfx.MacData.MacSalt = macSalt
917
+ pfx.MacData.Iterations = enc.macIterations
918
+ }
919
+ if err = computeMac(&pfx.MacData, authenticatedSafeBytes, encodedPassword); err != nil {
920
+ return nil, err
921
+ }
922
+ }
923
+
924
+ pfx.AuthSafe.ContentType = oidDataContentType
925
+ pfx.AuthSafe.Content.Class = 2
926
+ pfx.AuthSafe.Content.Tag = 0
927
+ pfx.AuthSafe.Content.IsCompound = true
928
+ if pfx.AuthSafe.Content.Bytes, err = asn1.Marshal(authenticatedSafeBytes); err != nil {
929
+ return nil, err
930
+ }
931
+
932
+ if pfxData, err = asn1.Marshal(pfx); err != nil {
933
+ return nil, errors.New("pkcs12: error writing P12 data: " + err.Error())
934
+ }
935
+ return
936
+ }
937
+
938
+ func makeCertBag(certBytes []byte, attributes []pkcs12Attribute) (certBag *safeBag, err error) {
939
+ certBag = new(safeBag)
940
+ certBag.Id = oidCertBag
941
+ certBag.Value.Class = 2
942
+ certBag.Value.Tag = 0
943
+ certBag.Value.IsCompound = true
944
+ if certBag.Value.Bytes, err = encodeCertBag(certBytes); err != nil {
945
+ return nil, err
946
+ }
947
+ certBag.Attributes = attributes
948
+ return
949
+ }
950
+
951
+ func makeSafeContents(rand io.Reader, bags []safeBag, algoID asn1.ObjectIdentifier, password []byte, iterations int, saltLen int) (ci contentInfo, err error) {
952
+ var data []byte
953
+ if data, err = asn1.Marshal(bags); err != nil {
954
+ return
955
+ }
956
+
957
+ if algoID == nil {
958
+ ci.ContentType = oidDataContentType
959
+ ci.Content.Class = 2
960
+ ci.Content.Tag = 0
961
+ ci.Content.IsCompound = true
962
+ if ci.Content.Bytes, err = asn1.Marshal(data); err != nil {
963
+ return
964
+ }
965
+ } else {
966
+ randomSalt := make([]byte, saltLen)
967
+ if _, err = rand.Read(randomSalt); err != nil {
968
+ return
969
+ }
970
+
971
+ var algo pkix.AlgorithmIdentifier
972
+ algo.Algorithm = algoID
973
+ if algoID.Equal(oidPBES2) {
974
+ if algo.Parameters.FullBytes, err = makePBES2Parameters(rand, randomSalt, iterations); err != nil {
975
+ return
976
+ }
977
+ } else {
978
+ if algo.Parameters.FullBytes, err = asn1.Marshal(pbeParams{Salt: randomSalt, Iterations: iterations}); err != nil {
979
+ return
980
+ }
981
+ }
982
+
983
+ var encryptedData encryptedData
984
+ encryptedData.Version = 0
985
+ encryptedData.EncryptedContentInfo.ContentType = oidDataContentType
986
+ encryptedData.EncryptedContentInfo.ContentEncryptionAlgorithm = algo
987
+ if err = pbEncrypt(&encryptedData.EncryptedContentInfo, data, password); err != nil {
988
+ return
989
+ }
990
+
991
+ ci.ContentType = oidEncryptedDataContentType
992
+ ci.Content.Class = 2
993
+ ci.Content.Tag = 0
994
+ ci.Content.IsCompound = true
995
+ if ci.Content.Bytes, err = asn1.Marshal(encryptedData); err != nil {
996
+ return
997
+ }
998
+ }
999
+ return
1000
+ }