pixel-react 1.15.21 → 1.15.23

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 (208) hide show
  1. package/lib/_virtual/aesCipherSuites.js +4 -0
  2. package/lib/_virtual/aesCipherSuites.js.map +1 -0
  3. package/lib/_virtual/asn1-validator.js +4 -0
  4. package/lib/_virtual/asn1-validator.js.map +1 -0
  5. package/lib/_virtual/asn1.js +4 -0
  6. package/lib/_virtual/asn1.js.map +1 -0
  7. package/lib/_virtual/cipherModes.js +4 -0
  8. package/lib/_virtual/cipherModes.js.map +1 -0
  9. package/lib/_virtual/hmac.js +4 -0
  10. package/lib/_virtual/hmac.js.map +1 -0
  11. package/lib/_virtual/index11.js +2 -2
  12. package/lib/_virtual/index12.js +2 -2
  13. package/lib/_virtual/index13.js +2 -2
  14. package/lib/_virtual/index14.js +4 -0
  15. package/lib/_virtual/index14.js.map +1 -0
  16. package/lib/_virtual/index2.js +5 -3
  17. package/lib/_virtual/index2.js.map +1 -1
  18. package/lib/_virtual/index3.js +4 -2
  19. package/lib/_virtual/index3.js.map +1 -1
  20. package/lib/_virtual/index4.js +2 -4
  21. package/lib/_virtual/index4.js.map +1 -1
  22. package/lib/_virtual/index5.js +4 -2
  23. package/lib/_virtual/index5.js.map +1 -1
  24. package/lib/_virtual/index6.js +2 -2
  25. package/lib/_virtual/index7.js +2 -6
  26. package/lib/_virtual/index7.js.map +1 -1
  27. package/lib/_virtual/index8.js +6 -2
  28. package/lib/_virtual/index8.js.map +1 -1
  29. package/lib/_virtual/index9.js +2 -2
  30. package/lib/_virtual/md5.js +4 -0
  31. package/lib/_virtual/md5.js.map +1 -0
  32. package/lib/_virtual/mgf1.js +4 -0
  33. package/lib/_virtual/mgf1.js.map +1 -0
  34. package/lib/_virtual/oids.js +4 -0
  35. package/lib/_virtual/oids.js.map +1 -0
  36. package/lib/_virtual/pem.js +4 -0
  37. package/lib/_virtual/pem.js.map +1 -0
  38. package/lib/_virtual/pkcs1.js +4 -0
  39. package/lib/_virtual/pkcs1.js.map +1 -0
  40. package/lib/_virtual/pkcs12.js +4 -0
  41. package/lib/_virtual/pkcs12.js.map +1 -0
  42. package/lib/_virtual/pkcs7.js +4 -0
  43. package/lib/_virtual/pkcs7.js.map +1 -0
  44. package/lib/_virtual/pkcs7asn1.js +4 -0
  45. package/lib/_virtual/pkcs7asn1.js.map +1 -0
  46. package/lib/_virtual/pki.js +4 -0
  47. package/lib/_virtual/pki.js.map +1 -0
  48. package/lib/_virtual/prime.js +4 -0
  49. package/lib/_virtual/prime.js.map +1 -0
  50. package/lib/_virtual/prng.js +4 -0
  51. package/lib/_virtual/prng.js.map +1 -0
  52. package/lib/_virtual/pss.js +4 -0
  53. package/lib/_virtual/pss.js.map +1 -0
  54. package/lib/_virtual/random.js +4 -0
  55. package/lib/_virtual/random.js.map +1 -0
  56. package/lib/_virtual/sha1.js +4 -0
  57. package/lib/_virtual/sha1.js.map +1 -0
  58. package/lib/_virtual/sha256.js +4 -0
  59. package/lib/_virtual/sha256.js.map +1 -0
  60. package/lib/_virtual/sha512.js +4 -0
  61. package/lib/_virtual/sha512.js.map +1 -0
  62. package/lib/_virtual/ssh.js +4 -0
  63. package/lib/_virtual/ssh.js.map +1 -0
  64. package/lib/_virtual/util.js +4 -0
  65. package/lib/_virtual/util.js.map +1 -0
  66. package/lib/_virtual/x509.js +4 -0
  67. package/lib/_virtual/x509.js.map +1 -0
  68. package/lib/assets/icons/testify_icon.svg.js +6 -0
  69. package/lib/assets/icons/testify_icon.svg.js.map +1 -0
  70. package/lib/assets/icons/testify_loader.svg.js +6 -0
  71. package/lib/assets/icons/testify_loader.svg.js.map +1 -0
  72. package/lib/assets/icons/testify_logo_name.svg.js +6 -0
  73. package/lib/assets/icons/testify_logo_name.svg.js.map +1 -0
  74. package/lib/components/AllProjectsDropdown/AllProjectsDropdown.js +3 -1
  75. package/lib/components/AllProjectsDropdown/AllProjectsDropdown.js.map +1 -1
  76. package/lib/components/Charts/DashboardDonutChart/DashboardDonutChart.js +2 -9
  77. package/lib/components/Charts/DashboardDonutChart/DashboardDonutChart.js.map +1 -1
  78. package/lib/components/Charts/DashboardDonutChart/types.d.ts +1 -1
  79. package/lib/components/ConditionalDropdown/ConditionalDropdown.js +2 -9
  80. package/lib/components/ConditionalDropdown/ConditionalDropdown.js.map +1 -1
  81. package/lib/components/Editor/Editor.js +37 -17
  82. package/lib/components/Editor/Editor.js.map +1 -1
  83. package/lib/components/Icon/iconList.js +6 -0
  84. package/lib/components/Icon/iconList.js.map +1 -1
  85. package/lib/components/MultiSelect/MultiSelect.js +9 -10
  86. package/lib/components/MultiSelect/MultiSelect.js.map +1 -1
  87. package/lib/components/PhoneInput/PhoneInput.js +1 -0
  88. package/lib/components/PhoneInput/PhoneInput.js.map +1 -1
  89. package/lib/components/SessionDropdown/SessionDropdown.js +4 -2
  90. package/lib/components/SessionDropdown/SessionDropdown.js.map +1 -1
  91. package/lib/index.cjs +27423 -379
  92. package/lib/index.cjs.map +1 -1
  93. package/lib/index.d.ts +1 -1
  94. package/lib/node_modules/classnames/index.js +1 -1
  95. package/lib/node_modules/input-format/modules/react/Input.js +1 -1
  96. package/lib/node_modules/js-beautify/js/index.js +1 -1
  97. package/lib/node_modules/js-beautify/js/src/html/beautifier.js +1 -1
  98. package/lib/node_modules/js-beautify/js/src/html/index.js +1 -1
  99. package/lib/node_modules/js-beautify/js/src/html/options.js +1 -1
  100. package/lib/node_modules/js-beautify/js/src/html/tokenizer.js +1 -1
  101. package/lib/node_modules/js-beautify/js/src/index.js +1 -1
  102. package/lib/node_modules/js-beautify/js/src/javascript/beautifier.js +1 -1
  103. package/lib/node_modules/js-beautify/js/src/javascript/index.js +1 -1
  104. package/lib/node_modules/js-beautify/js/src/javascript/options.js +1 -1
  105. package/lib/node_modules/js-beautify/js/src/javascript/tokenizer.js +1 -1
  106. package/lib/node_modules/node-forge/lib/aes.js +1014 -0
  107. package/lib/node_modules/node-forge/lib/aes.js.map +1 -0
  108. package/lib/node_modules/node-forge/lib/aesCipherSuites.js +286 -0
  109. package/lib/node_modules/node-forge/lib/aesCipherSuites.js.map +1 -0
  110. package/lib/node_modules/node-forge/lib/asn1-validator.js +100 -0
  111. package/lib/node_modules/node-forge/lib/asn1-validator.js.map +1 -0
  112. package/lib/node_modules/node-forge/lib/asn1.js +1379 -0
  113. package/lib/node_modules/node-forge/lib/asn1.js.map +1 -0
  114. package/lib/node_modules/node-forge/lib/baseN.js +181 -0
  115. package/lib/node_modules/node-forge/lib/baseN.js.map +1 -0
  116. package/lib/node_modules/node-forge/lib/cipher.js +236 -0
  117. package/lib/node_modules/node-forge/lib/cipher.js.map +1 -0
  118. package/lib/node_modules/node-forge/lib/cipherModes.js +936 -0
  119. package/lib/node_modules/node-forge/lib/cipherModes.js.map +1 -0
  120. package/lib/node_modules/node-forge/lib/des.js +467 -0
  121. package/lib/node_modules/node-forge/lib/des.js.map +1 -0
  122. package/lib/node_modules/node-forge/lib/ed25519.js +1108 -0
  123. package/lib/node_modules/node-forge/lib/ed25519.js.map +1 -0
  124. package/lib/node_modules/node-forge/lib/forge.js +23 -0
  125. package/lib/node_modules/node-forge/lib/forge.js.map +1 -0
  126. package/lib/node_modules/node-forge/lib/hmac.js +158 -0
  127. package/lib/node_modules/node-forge/lib/hmac.js.map +1 -0
  128. package/lib/node_modules/node-forge/lib/index.js +70 -0
  129. package/lib/node_modules/node-forge/lib/index.js.map +1 -0
  130. package/lib/node_modules/node-forge/lib/jsbn.js +1481 -0
  131. package/lib/node_modules/node-forge/lib/jsbn.js.map +1 -0
  132. package/lib/node_modules/node-forge/lib/kem.js +178 -0
  133. package/lib/node_modules/node-forge/lib/kem.js.map +1 -0
  134. package/lib/node_modules/node-forge/lib/log.js +325 -0
  135. package/lib/node_modules/node-forge/lib/log.js.map +1 -0
  136. package/lib/node_modules/node-forge/lib/md.all.js +28 -0
  137. package/lib/node_modules/node-forge/lib/md.all.js.map +1 -0
  138. package/lib/node_modules/node-forge/lib/md.js +22 -0
  139. package/lib/node_modules/node-forge/lib/md.js.map +1 -0
  140. package/lib/node_modules/node-forge/lib/md5.js +288 -0
  141. package/lib/node_modules/node-forge/lib/md5.js.map +1 -0
  142. package/lib/node_modules/node-forge/lib/mgf.js +24 -0
  143. package/lib/node_modules/node-forge/lib/mgf.js.map +1 -0
  144. package/lib/node_modules/node-forge/lib/mgf1.js +68 -0
  145. package/lib/node_modules/node-forge/lib/mgf1.js.map +1 -0
  146. package/lib/node_modules/node-forge/lib/oids.js +185 -0
  147. package/lib/node_modules/node-forge/lib/oids.js.map +1 -0
  148. package/lib/node_modules/node-forge/lib/pbe.js +966 -0
  149. package/lib/node_modules/node-forge/lib/pbe.js.map +1 -0
  150. package/lib/node_modules/node-forge/lib/pbkdf2.js +209 -0
  151. package/lib/node_modules/node-forge/lib/pbkdf2.js.map +1 -0
  152. package/lib/node_modules/node-forge/lib/pem.js +250 -0
  153. package/lib/node_modules/node-forge/lib/pem.js.map +1 -0
  154. package/lib/node_modules/node-forge/lib/pkcs1.js +273 -0
  155. package/lib/node_modules/node-forge/lib/pkcs1.js.map +1 -0
  156. package/lib/node_modules/node-forge/lib/pkcs12.js +980 -0
  157. package/lib/node_modules/node-forge/lib/pkcs12.js.map +1 -0
  158. package/lib/node_modules/node-forge/lib/pkcs7.js +1073 -0
  159. package/lib/node_modules/node-forge/lib/pkcs7.js.map +1 -0
  160. package/lib/node_modules/node-forge/lib/pkcs7asn1.js +415 -0
  161. package/lib/node_modules/node-forge/lib/pkcs7asn1.js.map +1 -0
  162. package/lib/node_modules/node-forge/lib/pki.js +125 -0
  163. package/lib/node_modules/node-forge/lib/pki.js.map +1 -0
  164. package/lib/node_modules/node-forge/lib/prime.js +297 -0
  165. package/lib/node_modules/node-forge/lib/prime.js.map +1 -0
  166. package/lib/node_modules/node-forge/lib/prng.js +433 -0
  167. package/lib/node_modules/node-forge/lib/prng.js.map +1 -0
  168. package/lib/node_modules/node-forge/lib/pss.js +246 -0
  169. package/lib/node_modules/node-forge/lib/pss.js.map +1 -0
  170. package/lib/node_modules/node-forge/lib/random.js +191 -0
  171. package/lib/node_modules/node-forge/lib/random.js.map +1 -0
  172. package/lib/node_modules/node-forge/lib/rc2.js +382 -0
  173. package/lib/node_modules/node-forge/lib/rc2.js.map +1 -0
  174. package/lib/node_modules/node-forge/lib/rsa.js +1815 -0
  175. package/lib/node_modules/node-forge/lib/rsa.js.map +1 -0
  176. package/lib/node_modules/node-forge/lib/sha1.js +325 -0
  177. package/lib/node_modules/node-forge/lib/sha1.js.map +1 -0
  178. package/lib/node_modules/node-forge/lib/sha256.js +306 -0
  179. package/lib/node_modules/node-forge/lib/sha256.js.map +1 -0
  180. package/lib/node_modules/node-forge/lib/sha512.js +479 -0
  181. package/lib/node_modules/node-forge/lib/sha512.js.map +1 -0
  182. package/lib/node_modules/node-forge/lib/ssh.js +244 -0
  183. package/lib/node_modules/node-forge/lib/ssh.js.map +1 -0
  184. package/lib/node_modules/node-forge/lib/tls.js +4207 -0
  185. package/lib/node_modules/node-forge/lib/tls.js.map +1 -0
  186. package/lib/node_modules/node-forge/lib/util.js +2565 -0
  187. package/lib/node_modules/node-forge/lib/util.js.map +1 -0
  188. package/lib/node_modules/node-forge/lib/x509.js +2986 -0
  189. package/lib/node_modules/node-forge/lib/x509.js.map +1 -0
  190. package/lib/node_modules/prop-types/index.js +1 -1
  191. package/lib/node_modules/react-async-script/lib/esm/async-script-loader.js +1 -1
  192. package/lib/node_modules/react-google-recaptcha/lib/esm/recaptcha.js +1 -1
  193. package/lib/node_modules/react-is/index.js +1 -1
  194. package/lib/node_modules/react-phone-number-input/modules/CountryIcon.js +1 -1
  195. package/lib/node_modules/react-phone-number-input/modules/CountrySelect.js +1 -1
  196. package/lib/node_modules/react-phone-number-input/modules/Flag.js +1 -1
  197. package/lib/node_modules/react-phone-number-input/modules/InputBasic.js +1 -1
  198. package/lib/node_modules/react-phone-number-input/modules/InputSmart.js +1 -1
  199. package/lib/node_modules/react-phone-number-input/modules/InternationalIcon.js +1 -1
  200. package/lib/node_modules/react-phone-number-input/modules/PhoneInputWithCountry.js +1 -1
  201. package/lib/node_modules/react-phone-number-input/modules/PropTypes.js +1 -1
  202. package/lib/node_modules/scheduler/index.js +1 -1
  203. package/lib/node_modules/use-context-selector/dist/index.js +1 -1
  204. package/lib/styles.css +1 -1
  205. package/lib/styles.css.map +1 -1
  206. package/lib/utils/getEncryptedData/getEncryptedData.js +10 -13
  207. package/lib/utils/getEncryptedData/getEncryptedData.js.map +1 -1
  208. package/package.json +3 -1
@@ -0,0 +1,2986 @@
1
+ import { __module as x509 } from '../../../_virtual/x509.js';
2
+ import { __require as requireForge } from './forge.js';
3
+ import { __require as requireAes } from './aes.js';
4
+ import { __require as requireAsn1 } from './asn1.js';
5
+ import { __require as requireDes } from './des.js';
6
+ import { __require as requireMd } from './md.js';
7
+ import { __require as requireMgf } from './mgf.js';
8
+ import { __require as requireOids } from './oids.js';
9
+ import { __require as requirePem } from './pem.js';
10
+ import { __require as requirePss } from './pss.js';
11
+ import { __require as requireRsa } from './rsa.js';
12
+ import { __require as requireUtil } from './util.js';
13
+
14
+ /**
15
+ * Javascript implementation of X.509 and related components (such as
16
+ * Certification Signing Requests) of a Public Key Infrastructure.
17
+ *
18
+ * @author Dave Longley
19
+ *
20
+ * Copyright (c) 2010-2014 Digital Bazaar, Inc.
21
+ *
22
+ * The ASN.1 representation of an X.509v3 certificate is as follows
23
+ * (see RFC 2459):
24
+ *
25
+ * Certificate ::= SEQUENCE {
26
+ * tbsCertificate TBSCertificate,
27
+ * signatureAlgorithm AlgorithmIdentifier,
28
+ * signatureValue BIT STRING
29
+ * }
30
+ *
31
+ * TBSCertificate ::= SEQUENCE {
32
+ * version [0] EXPLICIT Version DEFAULT v1,
33
+ * serialNumber CertificateSerialNumber,
34
+ * signature AlgorithmIdentifier,
35
+ * issuer Name,
36
+ * validity Validity,
37
+ * subject Name,
38
+ * subjectPublicKeyInfo SubjectPublicKeyInfo,
39
+ * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
40
+ * -- If present, version shall be v2 or v3
41
+ * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
42
+ * -- If present, version shall be v2 or v3
43
+ * extensions [3] EXPLICIT Extensions OPTIONAL
44
+ * -- If present, version shall be v3
45
+ * }
46
+ *
47
+ * Version ::= INTEGER { v1(0), v2(1), v3(2) }
48
+ *
49
+ * CertificateSerialNumber ::= INTEGER
50
+ *
51
+ * Name ::= CHOICE {
52
+ * // only one possible choice for now
53
+ * RDNSequence
54
+ * }
55
+ *
56
+ * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
57
+ *
58
+ * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
59
+ *
60
+ * AttributeTypeAndValue ::= SEQUENCE {
61
+ * type AttributeType,
62
+ * value AttributeValue
63
+ * }
64
+ * AttributeType ::= OBJECT IDENTIFIER
65
+ * AttributeValue ::= ANY DEFINED BY AttributeType
66
+ *
67
+ * Validity ::= SEQUENCE {
68
+ * notBefore Time,
69
+ * notAfter Time
70
+ * }
71
+ *
72
+ * Time ::= CHOICE {
73
+ * utcTime UTCTime,
74
+ * generalTime GeneralizedTime
75
+ * }
76
+ *
77
+ * UniqueIdentifier ::= BIT STRING
78
+ *
79
+ * SubjectPublicKeyInfo ::= SEQUENCE {
80
+ * algorithm AlgorithmIdentifier,
81
+ * subjectPublicKey BIT STRING
82
+ * }
83
+ *
84
+ * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
85
+ *
86
+ * Extension ::= SEQUENCE {
87
+ * extnID OBJECT IDENTIFIER,
88
+ * critical BOOLEAN DEFAULT FALSE,
89
+ * extnValue OCTET STRING
90
+ * }
91
+ *
92
+ * The only key algorithm currently supported for PKI is RSA.
93
+ *
94
+ * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.
95
+ *
96
+ * PKCS#10 v1.7 describes certificate signing requests:
97
+ *
98
+ * CertificationRequestInfo:
99
+ *
100
+ * CertificationRequestInfo ::= SEQUENCE {
101
+ * version INTEGER { v1(0) } (v1,...),
102
+ * subject Name,
103
+ * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
104
+ * attributes [0] Attributes{{ CRIAttributes }}
105
+ * }
106
+ *
107
+ * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
108
+ *
109
+ * CRIAttributes ATTRIBUTE ::= {
110
+ * ... -- add any locally defined attributes here -- }
111
+ *
112
+ * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
113
+ * type ATTRIBUTE.&id({IOSet}),
114
+ * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
115
+ * }
116
+ *
117
+ * CertificationRequest ::= SEQUENCE {
118
+ * certificationRequestInfo CertificationRequestInfo,
119
+ * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
120
+ * signature BIT STRING
121
+ * }
122
+ */
123
+ var hasRequiredX509;
124
+ function requireX509() {
125
+ if (hasRequiredX509) return x509.exports;
126
+ hasRequiredX509 = 1;
127
+ var forge = requireForge();
128
+ requireAes();
129
+ requireAsn1();
130
+ requireDes();
131
+ requireMd();
132
+ requireMgf();
133
+ requireOids();
134
+ requirePem();
135
+ requirePss();
136
+ requireRsa();
137
+ requireUtil();
138
+
139
+ // shortcut for asn.1 API
140
+ var asn1 = forge.asn1;
141
+
142
+ /* Public Key Infrastructure (PKI) implementation. */
143
+ var pki = x509.exports = forge.pki = forge.pki || {};
144
+ var oids = pki.oids;
145
+
146
+ // short name OID mappings
147
+ var _shortNames = {};
148
+ _shortNames['CN'] = oids['commonName'];
149
+ _shortNames['commonName'] = 'CN';
150
+ _shortNames['C'] = oids['countryName'];
151
+ _shortNames['countryName'] = 'C';
152
+ _shortNames['L'] = oids['localityName'];
153
+ _shortNames['localityName'] = 'L';
154
+ _shortNames['ST'] = oids['stateOrProvinceName'];
155
+ _shortNames['stateOrProvinceName'] = 'ST';
156
+ _shortNames['O'] = oids['organizationName'];
157
+ _shortNames['organizationName'] = 'O';
158
+ _shortNames['OU'] = oids['organizationalUnitName'];
159
+ _shortNames['organizationalUnitName'] = 'OU';
160
+ _shortNames['E'] = oids['emailAddress'];
161
+ _shortNames['emailAddress'] = 'E';
162
+
163
+ // validator for an SubjectPublicKeyInfo structure
164
+ // Note: Currently only works with an RSA public key
165
+ var publicKeyValidator = forge.pki.rsa.publicKeyValidator;
166
+
167
+ // validator for an X.509v3 certificate
168
+ var x509CertificateValidator = {
169
+ name: 'Certificate',
170
+ tagClass: asn1.Class.UNIVERSAL,
171
+ type: asn1.Type.SEQUENCE,
172
+ constructed: true,
173
+ value: [{
174
+ name: 'Certificate.TBSCertificate',
175
+ tagClass: asn1.Class.UNIVERSAL,
176
+ type: asn1.Type.SEQUENCE,
177
+ constructed: true,
178
+ captureAsn1: 'tbsCertificate',
179
+ value: [{
180
+ name: 'Certificate.TBSCertificate.version',
181
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
182
+ type: 0,
183
+ constructed: true,
184
+ optional: true,
185
+ value: [{
186
+ name: 'Certificate.TBSCertificate.version.integer',
187
+ tagClass: asn1.Class.UNIVERSAL,
188
+ type: asn1.Type.INTEGER,
189
+ constructed: false,
190
+ capture: 'certVersion'
191
+ }]
192
+ }, {
193
+ name: 'Certificate.TBSCertificate.serialNumber',
194
+ tagClass: asn1.Class.UNIVERSAL,
195
+ type: asn1.Type.INTEGER,
196
+ constructed: false,
197
+ capture: 'certSerialNumber'
198
+ }, {
199
+ name: 'Certificate.TBSCertificate.signature',
200
+ tagClass: asn1.Class.UNIVERSAL,
201
+ type: asn1.Type.SEQUENCE,
202
+ constructed: true,
203
+ value: [{
204
+ name: 'Certificate.TBSCertificate.signature.algorithm',
205
+ tagClass: asn1.Class.UNIVERSAL,
206
+ type: asn1.Type.OID,
207
+ constructed: false,
208
+ capture: 'certinfoSignatureOid'
209
+ }, {
210
+ name: 'Certificate.TBSCertificate.signature.parameters',
211
+ tagClass: asn1.Class.UNIVERSAL,
212
+ optional: true,
213
+ captureAsn1: 'certinfoSignatureParams'
214
+ }]
215
+ }, {
216
+ name: 'Certificate.TBSCertificate.issuer',
217
+ tagClass: asn1.Class.UNIVERSAL,
218
+ type: asn1.Type.SEQUENCE,
219
+ constructed: true,
220
+ captureAsn1: 'certIssuer'
221
+ }, {
222
+ name: 'Certificate.TBSCertificate.validity',
223
+ tagClass: asn1.Class.UNIVERSAL,
224
+ type: asn1.Type.SEQUENCE,
225
+ constructed: true,
226
+ // Note: UTC and generalized times may both appear so the capture
227
+ // names are based on their detected order, the names used below
228
+ // are only for the common case, which validity time really means
229
+ // "notBefore" and which means "notAfter" will be determined by order
230
+ value: [{
231
+ // notBefore (Time) (UTC time case)
232
+ name: 'Certificate.TBSCertificate.validity.notBefore (utc)',
233
+ tagClass: asn1.Class.UNIVERSAL,
234
+ type: asn1.Type.UTCTIME,
235
+ constructed: false,
236
+ optional: true,
237
+ capture: 'certValidity1UTCTime'
238
+ }, {
239
+ // notBefore (Time) (generalized time case)
240
+ name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',
241
+ tagClass: asn1.Class.UNIVERSAL,
242
+ type: asn1.Type.GENERALIZEDTIME,
243
+ constructed: false,
244
+ optional: true,
245
+ capture: 'certValidity2GeneralizedTime'
246
+ }, {
247
+ // notAfter (Time) (only UTC time is supported)
248
+ name: 'Certificate.TBSCertificate.validity.notAfter (utc)',
249
+ tagClass: asn1.Class.UNIVERSAL,
250
+ type: asn1.Type.UTCTIME,
251
+ constructed: false,
252
+ optional: true,
253
+ capture: 'certValidity3UTCTime'
254
+ }, {
255
+ // notAfter (Time) (only UTC time is supported)
256
+ name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',
257
+ tagClass: asn1.Class.UNIVERSAL,
258
+ type: asn1.Type.GENERALIZEDTIME,
259
+ constructed: false,
260
+ optional: true,
261
+ capture: 'certValidity4GeneralizedTime'
262
+ }]
263
+ }, {
264
+ // Name (subject) (RDNSequence)
265
+ name: 'Certificate.TBSCertificate.subject',
266
+ tagClass: asn1.Class.UNIVERSAL,
267
+ type: asn1.Type.SEQUENCE,
268
+ constructed: true,
269
+ captureAsn1: 'certSubject'
270
+ },
271
+ // SubjectPublicKeyInfo
272
+ publicKeyValidator, {
273
+ // issuerUniqueID (optional)
274
+ name: 'Certificate.TBSCertificate.issuerUniqueID',
275
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
276
+ type: 1,
277
+ constructed: true,
278
+ optional: true,
279
+ value: [{
280
+ name: 'Certificate.TBSCertificate.issuerUniqueID.id',
281
+ tagClass: asn1.Class.UNIVERSAL,
282
+ type: asn1.Type.BITSTRING,
283
+ constructed: false,
284
+ // TODO: support arbitrary bit length ids
285
+ captureBitStringValue: 'certIssuerUniqueId'
286
+ }]
287
+ }, {
288
+ // subjectUniqueID (optional)
289
+ name: 'Certificate.TBSCertificate.subjectUniqueID',
290
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
291
+ type: 2,
292
+ constructed: true,
293
+ optional: true,
294
+ value: [{
295
+ name: 'Certificate.TBSCertificate.subjectUniqueID.id',
296
+ tagClass: asn1.Class.UNIVERSAL,
297
+ type: asn1.Type.BITSTRING,
298
+ constructed: false,
299
+ // TODO: support arbitrary bit length ids
300
+ captureBitStringValue: 'certSubjectUniqueId'
301
+ }]
302
+ }, {
303
+ // Extensions (optional)
304
+ name: 'Certificate.TBSCertificate.extensions',
305
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
306
+ type: 3,
307
+ constructed: true,
308
+ captureAsn1: 'certExtensions',
309
+ optional: true
310
+ }]
311
+ }, {
312
+ // AlgorithmIdentifier (signature algorithm)
313
+ name: 'Certificate.signatureAlgorithm',
314
+ tagClass: asn1.Class.UNIVERSAL,
315
+ type: asn1.Type.SEQUENCE,
316
+ constructed: true,
317
+ value: [{
318
+ // algorithm
319
+ name: 'Certificate.signatureAlgorithm.algorithm',
320
+ tagClass: asn1.Class.UNIVERSAL,
321
+ type: asn1.Type.OID,
322
+ constructed: false,
323
+ capture: 'certSignatureOid'
324
+ }, {
325
+ name: 'Certificate.TBSCertificate.signature.parameters',
326
+ tagClass: asn1.Class.UNIVERSAL,
327
+ optional: true,
328
+ captureAsn1: 'certSignatureParams'
329
+ }]
330
+ }, {
331
+ // SignatureValue
332
+ name: 'Certificate.signatureValue',
333
+ tagClass: asn1.Class.UNIVERSAL,
334
+ type: asn1.Type.BITSTRING,
335
+ constructed: false,
336
+ captureBitStringValue: 'certSignature'
337
+ }]
338
+ };
339
+ var rsassaPssParameterValidator = {
340
+ name: 'rsapss',
341
+ tagClass: asn1.Class.UNIVERSAL,
342
+ type: asn1.Type.SEQUENCE,
343
+ constructed: true,
344
+ value: [{
345
+ name: 'rsapss.hashAlgorithm',
346
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
347
+ type: 0,
348
+ constructed: true,
349
+ value: [{
350
+ name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',
351
+ tagClass: asn1.Class.UNIVERSAL,
352
+ type: asn1.Class.SEQUENCE,
353
+ constructed: true,
354
+ optional: true,
355
+ value: [{
356
+ name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',
357
+ tagClass: asn1.Class.UNIVERSAL,
358
+ type: asn1.Type.OID,
359
+ constructed: false,
360
+ capture: 'hashOid'
361
+ /* parameter block omitted, for SHA1 NULL anyhow. */
362
+ }]
363
+ }]
364
+ }, {
365
+ name: 'rsapss.maskGenAlgorithm',
366
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
367
+ type: 1,
368
+ constructed: true,
369
+ value: [{
370
+ name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',
371
+ tagClass: asn1.Class.UNIVERSAL,
372
+ type: asn1.Class.SEQUENCE,
373
+ constructed: true,
374
+ optional: true,
375
+ value: [{
376
+ name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',
377
+ tagClass: asn1.Class.UNIVERSAL,
378
+ type: asn1.Type.OID,
379
+ constructed: false,
380
+ capture: 'maskGenOid'
381
+ }, {
382
+ name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',
383
+ tagClass: asn1.Class.UNIVERSAL,
384
+ type: asn1.Type.SEQUENCE,
385
+ constructed: true,
386
+ value: [{
387
+ name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',
388
+ tagClass: asn1.Class.UNIVERSAL,
389
+ type: asn1.Type.OID,
390
+ constructed: false,
391
+ capture: 'maskGenHashOid'
392
+ /* parameter block omitted, for SHA1 NULL anyhow. */
393
+ }]
394
+ }]
395
+ }]
396
+ }, {
397
+ name: 'rsapss.saltLength',
398
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
399
+ type: 2,
400
+ optional: true,
401
+ value: [{
402
+ name: 'rsapss.saltLength.saltLength',
403
+ tagClass: asn1.Class.UNIVERSAL,
404
+ type: asn1.Class.INTEGER,
405
+ constructed: false,
406
+ capture: 'saltLength'
407
+ }]
408
+ }, {
409
+ name: 'rsapss.trailerField',
410
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
411
+ type: 3,
412
+ optional: true,
413
+ value: [{
414
+ name: 'rsapss.trailer.trailer',
415
+ tagClass: asn1.Class.UNIVERSAL,
416
+ type: asn1.Class.INTEGER,
417
+ constructed: false,
418
+ capture: 'trailer'
419
+ }]
420
+ }]
421
+ };
422
+
423
+ // validator for a CertificationRequestInfo structure
424
+ var certificationRequestInfoValidator = {
425
+ name: 'CertificationRequestInfo',
426
+ tagClass: asn1.Class.UNIVERSAL,
427
+ type: asn1.Type.SEQUENCE,
428
+ constructed: true,
429
+ captureAsn1: 'certificationRequestInfo',
430
+ value: [{
431
+ name: 'CertificationRequestInfo.integer',
432
+ tagClass: asn1.Class.UNIVERSAL,
433
+ type: asn1.Type.INTEGER,
434
+ constructed: false,
435
+ capture: 'certificationRequestInfoVersion'
436
+ }, {
437
+ // Name (subject) (RDNSequence)
438
+ name: 'CertificationRequestInfo.subject',
439
+ tagClass: asn1.Class.UNIVERSAL,
440
+ type: asn1.Type.SEQUENCE,
441
+ constructed: true,
442
+ captureAsn1: 'certificationRequestInfoSubject'
443
+ },
444
+ // SubjectPublicKeyInfo
445
+ publicKeyValidator, {
446
+ name: 'CertificationRequestInfo.attributes',
447
+ tagClass: asn1.Class.CONTEXT_SPECIFIC,
448
+ type: 0,
449
+ constructed: true,
450
+ optional: true,
451
+ capture: 'certificationRequestInfoAttributes',
452
+ value: [{
453
+ name: 'CertificationRequestInfo.attributes',
454
+ tagClass: asn1.Class.UNIVERSAL,
455
+ type: asn1.Type.SEQUENCE,
456
+ constructed: true,
457
+ value: [{
458
+ name: 'CertificationRequestInfo.attributes.type',
459
+ tagClass: asn1.Class.UNIVERSAL,
460
+ type: asn1.Type.OID,
461
+ constructed: false
462
+ }, {
463
+ name: 'CertificationRequestInfo.attributes.value',
464
+ tagClass: asn1.Class.UNIVERSAL,
465
+ type: asn1.Type.SET,
466
+ constructed: true
467
+ }]
468
+ }]
469
+ }]
470
+ };
471
+
472
+ // validator for a CertificationRequest structure
473
+ var certificationRequestValidator = {
474
+ name: 'CertificationRequest',
475
+ tagClass: asn1.Class.UNIVERSAL,
476
+ type: asn1.Type.SEQUENCE,
477
+ constructed: true,
478
+ captureAsn1: 'csr',
479
+ value: [certificationRequestInfoValidator, {
480
+ // AlgorithmIdentifier (signature algorithm)
481
+ name: 'CertificationRequest.signatureAlgorithm',
482
+ tagClass: asn1.Class.UNIVERSAL,
483
+ type: asn1.Type.SEQUENCE,
484
+ constructed: true,
485
+ value: [{
486
+ // algorithm
487
+ name: 'CertificationRequest.signatureAlgorithm.algorithm',
488
+ tagClass: asn1.Class.UNIVERSAL,
489
+ type: asn1.Type.OID,
490
+ constructed: false,
491
+ capture: 'csrSignatureOid'
492
+ }, {
493
+ name: 'CertificationRequest.signatureAlgorithm.parameters',
494
+ tagClass: asn1.Class.UNIVERSAL,
495
+ optional: true,
496
+ captureAsn1: 'csrSignatureParams'
497
+ }]
498
+ }, {
499
+ // signature
500
+ name: 'CertificationRequest.signature',
501
+ tagClass: asn1.Class.UNIVERSAL,
502
+ type: asn1.Type.BITSTRING,
503
+ constructed: false,
504
+ captureBitStringValue: 'csrSignature'
505
+ }]
506
+ };
507
+
508
+ /**
509
+ * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName
510
+ * sets into an array with objects that have type and value properties.
511
+ *
512
+ * @param rdn the RDNSequence to convert.
513
+ * @param md a message digest to append type and value to if provided.
514
+ */
515
+ pki.RDNAttributesAsArray = function (rdn, md) {
516
+ var rval = [];
517
+
518
+ // each value in 'rdn' in is a SET of RelativeDistinguishedName
519
+ var set, attr, obj;
520
+ for (var si = 0; si < rdn.value.length; ++si) {
521
+ // get the RelativeDistinguishedName set
522
+ set = rdn.value[si];
523
+
524
+ // each value in the SET is an AttributeTypeAndValue sequence
525
+ // containing first a type (an OID) and second a value (defined by
526
+ // the OID)
527
+ for (var i = 0; i < set.value.length; ++i) {
528
+ obj = {};
529
+ attr = set.value[i];
530
+ obj.type = asn1.derToOid(attr.value[0].value);
531
+ obj.value = attr.value[1].value;
532
+ obj.valueTagClass = attr.value[1].type;
533
+ // if the OID is known, get its name and short name
534
+ if (obj.type in oids) {
535
+ obj.name = oids[obj.type];
536
+ if (obj.name in _shortNames) {
537
+ obj.shortName = _shortNames[obj.name];
538
+ }
539
+ }
540
+ if (md) {
541
+ md.update(obj.type);
542
+ md.update(obj.value);
543
+ }
544
+ rval.push(obj);
545
+ }
546
+ }
547
+ return rval;
548
+ };
549
+
550
+ /**
551
+ * Converts ASN.1 CRIAttributes into an array with objects that have type and
552
+ * value properties.
553
+ *
554
+ * @param attributes the CRIAttributes to convert.
555
+ */
556
+ pki.CRIAttributesAsArray = function (attributes) {
557
+ var rval = [];
558
+
559
+ // each value in 'attributes' in is a SEQUENCE with an OID and a SET
560
+ for (var si = 0; si < attributes.length; ++si) {
561
+ // get the attribute sequence
562
+ var seq = attributes[si];
563
+
564
+ // each value in the SEQUENCE containing first a type (an OID) and
565
+ // second a set of values (defined by the OID)
566
+ var type = asn1.derToOid(seq.value[0].value);
567
+ var values = seq.value[1].value;
568
+ for (var vi = 0; vi < values.length; ++vi) {
569
+ var obj = {};
570
+ obj.type = type;
571
+ obj.value = values[vi].value;
572
+ obj.valueTagClass = values[vi].type;
573
+ // if the OID is known, get its name and short name
574
+ if (obj.type in oids) {
575
+ obj.name = oids[obj.type];
576
+ if (obj.name in _shortNames) {
577
+ obj.shortName = _shortNames[obj.name];
578
+ }
579
+ }
580
+ // parse extensions
581
+ if (obj.type === oids.extensionRequest) {
582
+ obj.extensions = [];
583
+ for (var ei = 0; ei < obj.value.length; ++ei) {
584
+ obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));
585
+ }
586
+ }
587
+ rval.push(obj);
588
+ }
589
+ }
590
+ return rval;
591
+ };
592
+
593
+ /**
594
+ * Gets an issuer or subject attribute from its name, type, or short name.
595
+ *
596
+ * @param obj the issuer or subject object.
597
+ * @param options a short name string or an object with:
598
+ * shortName the short name for the attribute.
599
+ * name the name for the attribute.
600
+ * type the type for the attribute.
601
+ *
602
+ * @return the attribute.
603
+ */
604
+ function _getAttribute(obj, options) {
605
+ if (typeof options === 'string') {
606
+ options = {
607
+ shortName: options
608
+ };
609
+ }
610
+ var rval = null;
611
+ var attr;
612
+ for (var i = 0; rval === null && i < obj.attributes.length; ++i) {
613
+ attr = obj.attributes[i];
614
+ if (options.type && options.type === attr.type) {
615
+ rval = attr;
616
+ } else if (options.name && options.name === attr.name) {
617
+ rval = attr;
618
+ } else if (options.shortName && options.shortName === attr.shortName) {
619
+ rval = attr;
620
+ }
621
+ }
622
+ return rval;
623
+ }
624
+
625
+ /**
626
+ * Converts signature parameters from ASN.1 structure.
627
+ *
628
+ * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had
629
+ * no parameters.
630
+ *
631
+ * RSASSA-PSS-params ::= SEQUENCE {
632
+ * hashAlgorithm [0] HashAlgorithm DEFAULT
633
+ * sha1Identifier,
634
+ * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT
635
+ * mgf1SHA1Identifier,
636
+ * saltLength [2] INTEGER DEFAULT 20,
637
+ * trailerField [3] INTEGER DEFAULT 1
638
+ * }
639
+ *
640
+ * HashAlgorithm ::= AlgorithmIdentifier
641
+ *
642
+ * MaskGenAlgorithm ::= AlgorithmIdentifier
643
+ *
644
+ * AlgorithmIdentifer ::= SEQUENCE {
645
+ * algorithm OBJECT IDENTIFIER,
646
+ * parameters ANY DEFINED BY algorithm OPTIONAL
647
+ * }
648
+ *
649
+ * @param oid The OID specifying the signature algorithm
650
+ * @param obj The ASN.1 structure holding the parameters
651
+ * @param fillDefaults Whether to use return default values where omitted
652
+ * @return signature parameter object
653
+ */
654
+ var _readSignatureParameters = function (oid, obj, fillDefaults) {
655
+ var params = {};
656
+ if (oid !== oids['RSASSA-PSS']) {
657
+ return params;
658
+ }
659
+ if (fillDefaults) {
660
+ params = {
661
+ hash: {
662
+ algorithmOid: oids['sha1']
663
+ },
664
+ mgf: {
665
+ algorithmOid: oids['mgf1'],
666
+ hash: {
667
+ algorithmOid: oids['sha1']
668
+ }
669
+ },
670
+ saltLength: 20
671
+ };
672
+ }
673
+ var capture = {};
674
+ var errors = [];
675
+ if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {
676
+ var error = new Error('Cannot read RSASSA-PSS parameter block.');
677
+ error.errors = errors;
678
+ throw error;
679
+ }
680
+ if (capture.hashOid !== undefined) {
681
+ params.hash = params.hash || {};
682
+ params.hash.algorithmOid = asn1.derToOid(capture.hashOid);
683
+ }
684
+ if (capture.maskGenOid !== undefined) {
685
+ params.mgf = params.mgf || {};
686
+ params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);
687
+ params.mgf.hash = params.mgf.hash || {};
688
+ params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);
689
+ }
690
+ if (capture.saltLength !== undefined) {
691
+ params.saltLength = capture.saltLength.charCodeAt(0);
692
+ }
693
+ return params;
694
+ };
695
+
696
+ /**
697
+ * Create signature digest for OID.
698
+ *
699
+ * @param options
700
+ * signatureOid: the OID specifying the signature algorithm.
701
+ * type: a human readable type for error messages
702
+ * @return a created md instance. throws if unknown oid.
703
+ */
704
+ var _createSignatureDigest = function (options) {
705
+ switch (oids[options.signatureOid]) {
706
+ case 'sha1WithRSAEncryption':
707
+ // deprecated alias
708
+ case 'sha1WithRSASignature':
709
+ return forge.md.sha1.create();
710
+ case 'md5WithRSAEncryption':
711
+ return forge.md.md5.create();
712
+ case 'sha256WithRSAEncryption':
713
+ return forge.md.sha256.create();
714
+ case 'sha384WithRSAEncryption':
715
+ return forge.md.sha384.create();
716
+ case 'sha512WithRSAEncryption':
717
+ return forge.md.sha512.create();
718
+ case 'RSASSA-PSS':
719
+ return forge.md.sha256.create();
720
+ default:
721
+ var error = new Error('Could not compute ' + options.type + ' digest. ' + 'Unknown signature OID.');
722
+ error.signatureOid = options.signatureOid;
723
+ throw error;
724
+ }
725
+ };
726
+
727
+ /**
728
+ * Verify signature on certificate or CSR.
729
+ *
730
+ * @param options:
731
+ * certificate the certificate or CSR to verify.
732
+ * md the signature digest.
733
+ * signature the signature
734
+ * @return a created md instance. throws if unknown oid.
735
+ */
736
+ var _verifySignature = function (options) {
737
+ var cert = options.certificate;
738
+ var scheme;
739
+ switch (cert.signatureOid) {
740
+ case oids.sha1WithRSAEncryption:
741
+ // deprecated alias
742
+ case oids.sha1WithRSASignature:
743
+ /* use PKCS#1 v1.5 padding scheme */
744
+ break;
745
+ case oids['RSASSA-PSS']:
746
+ var hash, mgf;
747
+
748
+ /* initialize mgf */
749
+ hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];
750
+ if (hash === undefined || forge.md[hash] === undefined) {
751
+ var error = new Error('Unsupported MGF hash function.');
752
+ error.oid = cert.signatureParameters.mgf.hash.algorithmOid;
753
+ error.name = hash;
754
+ throw error;
755
+ }
756
+ mgf = oids[cert.signatureParameters.mgf.algorithmOid];
757
+ if (mgf === undefined || forge.mgf[mgf] === undefined) {
758
+ var error = new Error('Unsupported MGF function.');
759
+ error.oid = cert.signatureParameters.mgf.algorithmOid;
760
+ error.name = mgf;
761
+ throw error;
762
+ }
763
+ mgf = forge.mgf[mgf].create(forge.md[hash].create());
764
+
765
+ /* initialize hash function */
766
+ hash = oids[cert.signatureParameters.hash.algorithmOid];
767
+ if (hash === undefined || forge.md[hash] === undefined) {
768
+ var error = new Error('Unsupported RSASSA-PSS hash function.');
769
+ error.oid = cert.signatureParameters.hash.algorithmOid;
770
+ error.name = hash;
771
+ throw error;
772
+ }
773
+ scheme = forge.pss.create(forge.md[hash].create(), mgf, cert.signatureParameters.saltLength);
774
+ break;
775
+ }
776
+
777
+ // verify signature on cert using public key
778
+ return cert.publicKey.verify(options.md.digest().getBytes(), options.signature, scheme);
779
+ };
780
+
781
+ /**
782
+ * Converts an X.509 certificate from PEM format.
783
+ *
784
+ * Note: If the certificate is to be verified then compute hash should
785
+ * be set to true. This will scan the TBSCertificate part of the ASN.1
786
+ * object while it is converted so it doesn't need to be converted back
787
+ * to ASN.1-DER-encoding later.
788
+ *
789
+ * @param pem the PEM-formatted certificate.
790
+ * @param computeHash true to compute the hash for verification.
791
+ * @param strict true to be strict when checking ASN.1 value lengths, false to
792
+ * allow truncated values (default: true).
793
+ *
794
+ * @return the certificate.
795
+ */
796
+ pki.certificateFromPem = function (pem, computeHash, strict) {
797
+ var msg = forge.pem.decode(pem)[0];
798
+ if (msg.type !== 'CERTIFICATE' && msg.type !== 'X509 CERTIFICATE' && msg.type !== 'TRUSTED CERTIFICATE') {
799
+ var error = new Error('Could not convert certificate from PEM; PEM header type ' + 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');
800
+ error.headerType = msg.type;
801
+ throw error;
802
+ }
803
+ if (msg.procType && msg.procType.type === 'ENCRYPTED') {
804
+ throw new Error('Could not convert certificate from PEM; PEM is encrypted.');
805
+ }
806
+
807
+ // convert DER to ASN.1 object
808
+ var obj = asn1.fromDer(msg.body, strict);
809
+ return pki.certificateFromAsn1(obj, computeHash);
810
+ };
811
+
812
+ /**
813
+ * Converts an X.509 certificate to PEM format.
814
+ *
815
+ * @param cert the certificate.
816
+ * @param maxline the maximum characters per line, defaults to 64.
817
+ *
818
+ * @return the PEM-formatted certificate.
819
+ */
820
+ pki.certificateToPem = function (cert, maxline) {
821
+ // convert to ASN.1, then DER, then PEM-encode
822
+ var msg = {
823
+ type: 'CERTIFICATE',
824
+ body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()
825
+ };
826
+ return forge.pem.encode(msg, {
827
+ maxline: maxline
828
+ });
829
+ };
830
+
831
+ /**
832
+ * Converts an RSA public key from PEM format.
833
+ *
834
+ * @param pem the PEM-formatted public key.
835
+ *
836
+ * @return the public key.
837
+ */
838
+ pki.publicKeyFromPem = function (pem) {
839
+ var msg = forge.pem.decode(pem)[0];
840
+ if (msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {
841
+ var error = new Error('Could not convert public key from PEM; PEM header ' + 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');
842
+ error.headerType = msg.type;
843
+ throw error;
844
+ }
845
+ if (msg.procType && msg.procType.type === 'ENCRYPTED') {
846
+ throw new Error('Could not convert public key from PEM; PEM is encrypted.');
847
+ }
848
+
849
+ // convert DER to ASN.1 object
850
+ var obj = asn1.fromDer(msg.body);
851
+ return pki.publicKeyFromAsn1(obj);
852
+ };
853
+
854
+ /**
855
+ * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).
856
+ *
857
+ * @param key the public key.
858
+ * @param maxline the maximum characters per line, defaults to 64.
859
+ *
860
+ * @return the PEM-formatted public key.
861
+ */
862
+ pki.publicKeyToPem = function (key, maxline) {
863
+ // convert to ASN.1, then DER, then PEM-encode
864
+ var msg = {
865
+ type: 'PUBLIC KEY',
866
+ body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()
867
+ };
868
+ return forge.pem.encode(msg, {
869
+ maxline: maxline
870
+ });
871
+ };
872
+
873
+ /**
874
+ * Converts an RSA public key to PEM format (using an RSAPublicKey).
875
+ *
876
+ * @param key the public key.
877
+ * @param maxline the maximum characters per line, defaults to 64.
878
+ *
879
+ * @return the PEM-formatted public key.
880
+ */
881
+ pki.publicKeyToRSAPublicKeyPem = function (key, maxline) {
882
+ // convert to ASN.1, then DER, then PEM-encode
883
+ var msg = {
884
+ type: 'RSA PUBLIC KEY',
885
+ body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()
886
+ };
887
+ return forge.pem.encode(msg, {
888
+ maxline: maxline
889
+ });
890
+ };
891
+
892
+ /**
893
+ * Gets a fingerprint for the given public key.
894
+ *
895
+ * @param options the options to use.
896
+ * [md] the message digest object to use (defaults to forge.md.sha1).
897
+ * [type] the type of fingerprint, such as 'RSAPublicKey',
898
+ * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').
899
+ * [encoding] an alternative output encoding, such as 'hex'
900
+ * (defaults to none, outputs a byte buffer).
901
+ * [delimiter] the delimiter to use between bytes for 'hex' encoded
902
+ * output, eg: ':' (defaults to none).
903
+ *
904
+ * @return the fingerprint as a byte buffer or other encoding based on options.
905
+ */
906
+ pki.getPublicKeyFingerprint = function (key, options) {
907
+ options = options || {};
908
+ var md = options.md || forge.md.sha1.create();
909
+ var type = options.type || 'RSAPublicKey';
910
+ var bytes;
911
+ switch (type) {
912
+ case 'RSAPublicKey':
913
+ bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();
914
+ break;
915
+ case 'SubjectPublicKeyInfo':
916
+ bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();
917
+ break;
918
+ default:
919
+ throw new Error('Unknown fingerprint type "' + options.type + '".');
920
+ }
921
+
922
+ // hash public key bytes
923
+ md.start();
924
+ md.update(bytes);
925
+ var digest = md.digest();
926
+ if (options.encoding === 'hex') {
927
+ var hex = digest.toHex();
928
+ if (options.delimiter) {
929
+ return hex.match(/.{2}/g).join(options.delimiter);
930
+ }
931
+ return hex;
932
+ } else if (options.encoding === 'binary') {
933
+ return digest.getBytes();
934
+ } else if (options.encoding) {
935
+ throw new Error('Unknown encoding "' + options.encoding + '".');
936
+ }
937
+ return digest;
938
+ };
939
+
940
+ /**
941
+ * Converts a PKCS#10 certification request (CSR) from PEM format.
942
+ *
943
+ * Note: If the certification request is to be verified then compute hash
944
+ * should be set to true. This will scan the CertificationRequestInfo part of
945
+ * the ASN.1 object while it is converted so it doesn't need to be converted
946
+ * back to ASN.1-DER-encoding later.
947
+ *
948
+ * @param pem the PEM-formatted certificate.
949
+ * @param computeHash true to compute the hash for verification.
950
+ * @param strict true to be strict when checking ASN.1 value lengths, false to
951
+ * allow truncated values (default: true).
952
+ *
953
+ * @return the certification request (CSR).
954
+ */
955
+ pki.certificationRequestFromPem = function (pem, computeHash, strict) {
956
+ var msg = forge.pem.decode(pem)[0];
957
+ if (msg.type !== 'CERTIFICATE REQUEST') {
958
+ var error = new Error('Could not convert certification request from PEM; ' + 'PEM header type is not "CERTIFICATE REQUEST".');
959
+ error.headerType = msg.type;
960
+ throw error;
961
+ }
962
+ if (msg.procType && msg.procType.type === 'ENCRYPTED') {
963
+ throw new Error('Could not convert certification request from PEM; ' + 'PEM is encrypted.');
964
+ }
965
+
966
+ // convert DER to ASN.1 object
967
+ var obj = asn1.fromDer(msg.body, strict);
968
+ return pki.certificationRequestFromAsn1(obj, computeHash);
969
+ };
970
+
971
+ /**
972
+ * Converts a PKCS#10 certification request (CSR) to PEM format.
973
+ *
974
+ * @param csr the certification request.
975
+ * @param maxline the maximum characters per line, defaults to 64.
976
+ *
977
+ * @return the PEM-formatted certification request.
978
+ */
979
+ pki.certificationRequestToPem = function (csr, maxline) {
980
+ // convert to ASN.1, then DER, then PEM-encode
981
+ var msg = {
982
+ type: 'CERTIFICATE REQUEST',
983
+ body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()
984
+ };
985
+ return forge.pem.encode(msg, {
986
+ maxline: maxline
987
+ });
988
+ };
989
+
990
+ /**
991
+ * Creates an empty X.509v3 RSA certificate.
992
+ *
993
+ * @return the certificate.
994
+ */
995
+ pki.createCertificate = function () {
996
+ var cert = {};
997
+ cert.version = 0x02;
998
+ cert.serialNumber = '00';
999
+ cert.signatureOid = null;
1000
+ cert.signature = null;
1001
+ cert.siginfo = {};
1002
+ cert.siginfo.algorithmOid = null;
1003
+ cert.validity = {};
1004
+ cert.validity.notBefore = new Date();
1005
+ cert.validity.notAfter = new Date();
1006
+ cert.issuer = {};
1007
+ cert.issuer.getField = function (sn) {
1008
+ return _getAttribute(cert.issuer, sn);
1009
+ };
1010
+ cert.issuer.addField = function (attr) {
1011
+ _fillMissingFields([attr]);
1012
+ cert.issuer.attributes.push(attr);
1013
+ };
1014
+ cert.issuer.attributes = [];
1015
+ cert.issuer.hash = null;
1016
+ cert.subject = {};
1017
+ cert.subject.getField = function (sn) {
1018
+ return _getAttribute(cert.subject, sn);
1019
+ };
1020
+ cert.subject.addField = function (attr) {
1021
+ _fillMissingFields([attr]);
1022
+ cert.subject.attributes.push(attr);
1023
+ };
1024
+ cert.subject.attributes = [];
1025
+ cert.subject.hash = null;
1026
+ cert.extensions = [];
1027
+ cert.publicKey = null;
1028
+ cert.md = null;
1029
+
1030
+ /**
1031
+ * Sets the subject of this certificate.
1032
+ *
1033
+ * @param attrs the array of subject attributes to use.
1034
+ * @param uniqueId an optional a unique ID to use.
1035
+ */
1036
+ cert.setSubject = function (attrs, uniqueId) {
1037
+ // set new attributes, clear hash
1038
+ _fillMissingFields(attrs);
1039
+ cert.subject.attributes = attrs;
1040
+ delete cert.subject.uniqueId;
1041
+ if (uniqueId) {
1042
+ // TODO: support arbitrary bit length ids
1043
+ cert.subject.uniqueId = uniqueId;
1044
+ }
1045
+ cert.subject.hash = null;
1046
+ };
1047
+
1048
+ /**
1049
+ * Sets the issuer of this certificate.
1050
+ *
1051
+ * @param attrs the array of issuer attributes to use.
1052
+ * @param uniqueId an optional a unique ID to use.
1053
+ */
1054
+ cert.setIssuer = function (attrs, uniqueId) {
1055
+ // set new attributes, clear hash
1056
+ _fillMissingFields(attrs);
1057
+ cert.issuer.attributes = attrs;
1058
+ delete cert.issuer.uniqueId;
1059
+ if (uniqueId) {
1060
+ // TODO: support arbitrary bit length ids
1061
+ cert.issuer.uniqueId = uniqueId;
1062
+ }
1063
+ cert.issuer.hash = null;
1064
+ };
1065
+
1066
+ /**
1067
+ * Sets the extensions of this certificate.
1068
+ *
1069
+ * @param exts the array of extensions to use.
1070
+ */
1071
+ cert.setExtensions = function (exts) {
1072
+ for (var i = 0; i < exts.length; ++i) {
1073
+ _fillMissingExtensionFields(exts[i], {
1074
+ cert: cert
1075
+ });
1076
+ }
1077
+ // set new extensions
1078
+ cert.extensions = exts;
1079
+ };
1080
+
1081
+ /**
1082
+ * Gets an extension by its name or id.
1083
+ *
1084
+ * @param options the name to use or an object with:
1085
+ * name the name to use.
1086
+ * id the id to use.
1087
+ *
1088
+ * @return the extension or null if not found.
1089
+ */
1090
+ cert.getExtension = function (options) {
1091
+ if (typeof options === 'string') {
1092
+ options = {
1093
+ name: options
1094
+ };
1095
+ }
1096
+ var rval = null;
1097
+ var ext;
1098
+ for (var i = 0; rval === null && i < cert.extensions.length; ++i) {
1099
+ ext = cert.extensions[i];
1100
+ if (options.id && ext.id === options.id) {
1101
+ rval = ext;
1102
+ } else if (options.name && ext.name === options.name) {
1103
+ rval = ext;
1104
+ }
1105
+ }
1106
+ return rval;
1107
+ };
1108
+
1109
+ /**
1110
+ * Signs this certificate using the given private key.
1111
+ *
1112
+ * @param key the private key to sign with.
1113
+ * @param md the message digest object to use (defaults to forge.md.sha1).
1114
+ */
1115
+ cert.sign = function (key, md) {
1116
+ // TODO: get signature OID from private key
1117
+ cert.md = md || forge.md.sha1.create();
1118
+ var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];
1119
+ if (!algorithmOid) {
1120
+ var error = new Error('Could not compute certificate digest. ' + 'Unknown message digest algorithm OID.');
1121
+ error.algorithm = cert.md.algorithm;
1122
+ throw error;
1123
+ }
1124
+ cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;
1125
+
1126
+ // get TBSCertificate, convert to DER
1127
+ cert.tbsCertificate = pki.getTBSCertificate(cert);
1128
+ var bytes = asn1.toDer(cert.tbsCertificate);
1129
+
1130
+ // digest and sign
1131
+ cert.md.update(bytes.getBytes());
1132
+ cert.signature = key.sign(cert.md);
1133
+ };
1134
+
1135
+ /**
1136
+ * Attempts verify the signature on the passed certificate using this
1137
+ * certificate's public key.
1138
+ *
1139
+ * @param child the certificate to verify.
1140
+ *
1141
+ * @return true if verified, false if not.
1142
+ */
1143
+ cert.verify = function (child) {
1144
+ var rval = false;
1145
+ if (!cert.issued(child)) {
1146
+ var issuer = child.issuer;
1147
+ var subject = cert.subject;
1148
+ var error = new Error('The parent certificate did not issue the given child ' + 'certificate; the child certificate\'s issuer does not match the ' + 'parent\'s subject.');
1149
+ error.expectedIssuer = subject.attributes;
1150
+ error.actualIssuer = issuer.attributes;
1151
+ throw error;
1152
+ }
1153
+ var md = child.md;
1154
+ if (md === null) {
1155
+ // create digest for OID signature types
1156
+ md = _createSignatureDigest({
1157
+ signatureOid: child.signatureOid,
1158
+ type: 'certificate'
1159
+ });
1160
+
1161
+ // produce DER formatted TBSCertificate and digest it
1162
+ var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);
1163
+ var bytes = asn1.toDer(tbsCertificate);
1164
+ md.update(bytes.getBytes());
1165
+ }
1166
+ if (md !== null) {
1167
+ rval = _verifySignature({
1168
+ certificate: cert,
1169
+ md: md,
1170
+ signature: child.signature
1171
+ });
1172
+ }
1173
+ return rval;
1174
+ };
1175
+
1176
+ /**
1177
+ * Returns true if this certificate's issuer matches the passed
1178
+ * certificate's subject. Note that no signature check is performed.
1179
+ *
1180
+ * @param parent the certificate to check.
1181
+ *
1182
+ * @return true if this certificate's issuer matches the passed certificate's
1183
+ * subject.
1184
+ */
1185
+ cert.isIssuer = function (parent) {
1186
+ var rval = false;
1187
+ var i = cert.issuer;
1188
+ var s = parent.subject;
1189
+
1190
+ // compare hashes if present
1191
+ if (i.hash && s.hash) {
1192
+ rval = i.hash === s.hash;
1193
+ } else if (i.attributes.length === s.attributes.length) {
1194
+ // all attributes are the same so issuer matches subject
1195
+ rval = true;
1196
+ var iattr, sattr;
1197
+ for (var n = 0; rval && n < i.attributes.length; ++n) {
1198
+ iattr = i.attributes[n];
1199
+ sattr = s.attributes[n];
1200
+ if (iattr.type !== sattr.type || iattr.value !== sattr.value) {
1201
+ // attribute mismatch
1202
+ rval = false;
1203
+ }
1204
+ }
1205
+ }
1206
+ return rval;
1207
+ };
1208
+
1209
+ /**
1210
+ * Returns true if this certificate's subject matches the issuer of the
1211
+ * given certificate). Note that not signature check is performed.
1212
+ *
1213
+ * @param child the certificate to check.
1214
+ *
1215
+ * @return true if this certificate's subject matches the passed
1216
+ * certificate's issuer.
1217
+ */
1218
+ cert.issued = function (child) {
1219
+ return child.isIssuer(cert);
1220
+ };
1221
+
1222
+ /**
1223
+ * Generates the subjectKeyIdentifier for this certificate as byte buffer.
1224
+ *
1225
+ * @return the subjectKeyIdentifier for this certificate as byte buffer.
1226
+ */
1227
+ cert.generateSubjectKeyIdentifier = function () {
1228
+ /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:
1229
+ (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
1230
+ value of the BIT STRING subjectPublicKey (excluding the tag,
1231
+ length, and number of unused bits).
1232
+ (2) The keyIdentifier is composed of a four bit type field with
1233
+ the value 0100 followed by the least significant 60 bits of the
1234
+ SHA-1 hash of the value of the BIT STRING subjectPublicKey
1235
+ (excluding the tag, length, and number of unused bit string bits).
1236
+ */
1237
+
1238
+ // skipping the tag, length, and number of unused bits is the same
1239
+ // as just using the RSAPublicKey (for RSA keys, which are the
1240
+ // only ones supported)
1241
+ return pki.getPublicKeyFingerprint(cert.publicKey, {
1242
+ type: 'RSAPublicKey'
1243
+ });
1244
+ };
1245
+
1246
+ /**
1247
+ * Verifies the subjectKeyIdentifier extension value for this certificate
1248
+ * against its public key. If no extension is found, false will be
1249
+ * returned.
1250
+ *
1251
+ * @return true if verified, false if not.
1252
+ */
1253
+ cert.verifySubjectKeyIdentifier = function () {
1254
+ var oid = oids['subjectKeyIdentifier'];
1255
+ for (var i = 0; i < cert.extensions.length; ++i) {
1256
+ var ext = cert.extensions[i];
1257
+ if (ext.id === oid) {
1258
+ var ski = cert.generateSubjectKeyIdentifier().getBytes();
1259
+ return forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski;
1260
+ }
1261
+ }
1262
+ return false;
1263
+ };
1264
+ return cert;
1265
+ };
1266
+
1267
+ /**
1268
+ * Converts an X.509v3 RSA certificate from an ASN.1 object.
1269
+ *
1270
+ * Note: If the certificate is to be verified then compute hash should
1271
+ * be set to true. There is currently no implementation for converting
1272
+ * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1
1273
+ * object needs to be scanned before the cert object is created.
1274
+ *
1275
+ * @param obj the asn1 representation of an X.509v3 RSA certificate.
1276
+ * @param computeHash true to compute the hash for verification.
1277
+ *
1278
+ * @return the certificate.
1279
+ */
1280
+ pki.certificateFromAsn1 = function (obj, computeHash) {
1281
+ // validate certificate and capture data
1282
+ var capture = {};
1283
+ var errors = [];
1284
+ if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) {
1285
+ var error = new Error('Cannot read X.509 certificate. ' + 'ASN.1 object is not an X509v3 Certificate.');
1286
+ error.errors = errors;
1287
+ throw error;
1288
+ }
1289
+
1290
+ // get oid
1291
+ var oid = asn1.derToOid(capture.publicKeyOid);
1292
+ if (oid !== pki.oids.rsaEncryption) {
1293
+ throw new Error('Cannot read public key. OID is not RSA.');
1294
+ }
1295
+
1296
+ // create certificate
1297
+ var cert = pki.createCertificate();
1298
+ cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0;
1299
+ var serial = forge.util.createBuffer(capture.certSerialNumber);
1300
+ cert.serialNumber = serial.toHex();
1301
+ cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);
1302
+ cert.signatureParameters = _readSignatureParameters(cert.signatureOid, capture.certSignatureParams, true);
1303
+ cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);
1304
+ cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, capture.certinfoSignatureParams, false);
1305
+ cert.signature = capture.certSignature;
1306
+ var validity = [];
1307
+ if (capture.certValidity1UTCTime !== undefined) {
1308
+ validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));
1309
+ }
1310
+ if (capture.certValidity2GeneralizedTime !== undefined) {
1311
+ validity.push(asn1.generalizedTimeToDate(capture.certValidity2GeneralizedTime));
1312
+ }
1313
+ if (capture.certValidity3UTCTime !== undefined) {
1314
+ validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));
1315
+ }
1316
+ if (capture.certValidity4GeneralizedTime !== undefined) {
1317
+ validity.push(asn1.generalizedTimeToDate(capture.certValidity4GeneralizedTime));
1318
+ }
1319
+ if (validity.length > 2) {
1320
+ throw new Error('Cannot read notBefore/notAfter validity times; more ' + 'than two times were provided in the certificate.');
1321
+ }
1322
+ if (validity.length < 2) {
1323
+ throw new Error('Cannot read notBefore/notAfter validity times; they ' + 'were not provided as either UTCTime or GeneralizedTime.');
1324
+ }
1325
+ cert.validity.notBefore = validity[0];
1326
+ cert.validity.notAfter = validity[1];
1327
+
1328
+ // keep TBSCertificate to preserve signature when exporting
1329
+ cert.tbsCertificate = capture.tbsCertificate;
1330
+ if (computeHash) {
1331
+ // create digest for OID signature type
1332
+ cert.md = _createSignatureDigest({
1333
+ signatureOid: cert.signatureOid,
1334
+ type: 'certificate'
1335
+ });
1336
+
1337
+ // produce DER formatted TBSCertificate and digest it
1338
+ var bytes = asn1.toDer(cert.tbsCertificate);
1339
+ cert.md.update(bytes.getBytes());
1340
+ }
1341
+
1342
+ // handle issuer, build issuer message digest
1343
+ var imd = forge.md.sha1.create();
1344
+ var ibytes = asn1.toDer(capture.certIssuer);
1345
+ imd.update(ibytes.getBytes());
1346
+ cert.issuer.getField = function (sn) {
1347
+ return _getAttribute(cert.issuer, sn);
1348
+ };
1349
+ cert.issuer.addField = function (attr) {
1350
+ _fillMissingFields([attr]);
1351
+ cert.issuer.attributes.push(attr);
1352
+ };
1353
+ cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);
1354
+ if (capture.certIssuerUniqueId) {
1355
+ cert.issuer.uniqueId = capture.certIssuerUniqueId;
1356
+ }
1357
+ cert.issuer.hash = imd.digest().toHex();
1358
+
1359
+ // handle subject, build subject message digest
1360
+ var smd = forge.md.sha1.create();
1361
+ var sbytes = asn1.toDer(capture.certSubject);
1362
+ smd.update(sbytes.getBytes());
1363
+ cert.subject.getField = function (sn) {
1364
+ return _getAttribute(cert.subject, sn);
1365
+ };
1366
+ cert.subject.addField = function (attr) {
1367
+ _fillMissingFields([attr]);
1368
+ cert.subject.attributes.push(attr);
1369
+ };
1370
+ cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);
1371
+ if (capture.certSubjectUniqueId) {
1372
+ cert.subject.uniqueId = capture.certSubjectUniqueId;
1373
+ }
1374
+ cert.subject.hash = smd.digest().toHex();
1375
+
1376
+ // handle extensions
1377
+ if (capture.certExtensions) {
1378
+ cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);
1379
+ } else {
1380
+ cert.extensions = [];
1381
+ }
1382
+
1383
+ // convert RSA public key from ASN.1
1384
+ cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
1385
+ return cert;
1386
+ };
1387
+
1388
+ /**
1389
+ * Converts an ASN.1 extensions object (with extension sequences as its
1390
+ * values) into an array of extension objects with types and values.
1391
+ *
1392
+ * Supported extensions:
1393
+ *
1394
+ * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
1395
+ * KeyUsage ::= BIT STRING {
1396
+ * digitalSignature (0),
1397
+ * nonRepudiation (1),
1398
+ * keyEncipherment (2),
1399
+ * dataEncipherment (3),
1400
+ * keyAgreement (4),
1401
+ * keyCertSign (5),
1402
+ * cRLSign (6),
1403
+ * encipherOnly (7),
1404
+ * decipherOnly (8)
1405
+ * }
1406
+ *
1407
+ * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }
1408
+ * BasicConstraints ::= SEQUENCE {
1409
+ * cA BOOLEAN DEFAULT FALSE,
1410
+ * pathLenConstraint INTEGER (0..MAX) OPTIONAL
1411
+ * }
1412
+ *
1413
+ * subjectAltName EXTENSION ::= {
1414
+ * SYNTAX GeneralNames
1415
+ * IDENTIFIED BY id-ce-subjectAltName
1416
+ * }
1417
+ *
1418
+ * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1419
+ *
1420
+ * GeneralName ::= CHOICE {
1421
+ * otherName [0] INSTANCE OF OTHER-NAME,
1422
+ * rfc822Name [1] IA5String,
1423
+ * dNSName [2] IA5String,
1424
+ * x400Address [3] ORAddress,
1425
+ * directoryName [4] Name,
1426
+ * ediPartyName [5] EDIPartyName,
1427
+ * uniformResourceIdentifier [6] IA5String,
1428
+ * IPAddress [7] OCTET STRING,
1429
+ * registeredID [8] OBJECT IDENTIFIER
1430
+ * }
1431
+ *
1432
+ * OTHER-NAME ::= TYPE-IDENTIFIER
1433
+ *
1434
+ * EDIPartyName ::= SEQUENCE {
1435
+ * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,
1436
+ * partyName [1] DirectoryString {ub-name}
1437
+ * }
1438
+ *
1439
+ * @param exts the extensions ASN.1 with extension sequences to parse.
1440
+ *
1441
+ * @return the array.
1442
+ */
1443
+ pki.certificateExtensionsFromAsn1 = function (exts) {
1444
+ var rval = [];
1445
+ for (var i = 0; i < exts.value.length; ++i) {
1446
+ // get extension sequence
1447
+ var extseq = exts.value[i];
1448
+ for (var ei = 0; ei < extseq.value.length; ++ei) {
1449
+ rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));
1450
+ }
1451
+ }
1452
+ return rval;
1453
+ };
1454
+
1455
+ /**
1456
+ * Parses a single certificate extension from ASN.1.
1457
+ *
1458
+ * @param ext the extension in ASN.1 format.
1459
+ *
1460
+ * @return the parsed extension as an object.
1461
+ */
1462
+ pki.certificateExtensionFromAsn1 = function (ext) {
1463
+ // an extension has:
1464
+ // [0] extnID OBJECT IDENTIFIER
1465
+ // [1] critical BOOLEAN DEFAULT FALSE
1466
+ // [2] extnValue OCTET STRING
1467
+ var e = {};
1468
+ e.id = asn1.derToOid(ext.value[0].value);
1469
+ e.critical = false;
1470
+ if (ext.value[1].type === asn1.Type.BOOLEAN) {
1471
+ e.critical = ext.value[1].value.charCodeAt(0) !== 0x00;
1472
+ e.value = ext.value[2].value;
1473
+ } else {
1474
+ e.value = ext.value[1].value;
1475
+ }
1476
+ // if the oid is known, get its name
1477
+ if (e.id in oids) {
1478
+ e.name = oids[e.id];
1479
+
1480
+ // handle key usage
1481
+ if (e.name === 'keyUsage') {
1482
+ // get value as BIT STRING
1483
+ var ev = asn1.fromDer(e.value);
1484
+ var b2 = 0x00;
1485
+ var b3 = 0x00;
1486
+ if (ev.value.length > 1) {
1487
+ // skip first byte, just indicates unused bits which
1488
+ // will be padded with 0s anyway
1489
+ // get bytes with flag bits
1490
+ b2 = ev.value.charCodeAt(1);
1491
+ b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;
1492
+ }
1493
+ // set flags
1494
+ e.digitalSignature = (b2 & 0x80) === 0x80;
1495
+ e.nonRepudiation = (b2 & 0x40) === 0x40;
1496
+ e.keyEncipherment = (b2 & 0x20) === 0x20;
1497
+ e.dataEncipherment = (b2 & 0x10) === 0x10;
1498
+ e.keyAgreement = (b2 & 0x08) === 0x08;
1499
+ e.keyCertSign = (b2 & 0x04) === 0x04;
1500
+ e.cRLSign = (b2 & 0x02) === 0x02;
1501
+ e.encipherOnly = (b2 & 0x01) === 0x01;
1502
+ e.decipherOnly = (b3 & 0x80) === 0x80;
1503
+ } else if (e.name === 'basicConstraints') {
1504
+ // handle basic constraints
1505
+ // get value as SEQUENCE
1506
+ var ev = asn1.fromDer(e.value);
1507
+ // get cA BOOLEAN flag (defaults to false)
1508
+ if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {
1509
+ e.cA = ev.value[0].value.charCodeAt(0) !== 0x00;
1510
+ } else {
1511
+ e.cA = false;
1512
+ }
1513
+ // get path length constraint
1514
+ var value = null;
1515
+ if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {
1516
+ value = ev.value[0].value;
1517
+ } else if (ev.value.length > 1) {
1518
+ value = ev.value[1].value;
1519
+ }
1520
+ if (value !== null) {
1521
+ e.pathLenConstraint = asn1.derToInteger(value);
1522
+ }
1523
+ } else if (e.name === 'extKeyUsage') {
1524
+ // handle extKeyUsage
1525
+ // value is a SEQUENCE of OIDs
1526
+ var ev = asn1.fromDer(e.value);
1527
+ for (var vi = 0; vi < ev.value.length; ++vi) {
1528
+ var oid = asn1.derToOid(ev.value[vi].value);
1529
+ if (oid in oids) {
1530
+ e[oids[oid]] = true;
1531
+ } else {
1532
+ e[oid] = true;
1533
+ }
1534
+ }
1535
+ } else if (e.name === 'nsCertType') {
1536
+ // handle nsCertType
1537
+ // get value as BIT STRING
1538
+ var ev = asn1.fromDer(e.value);
1539
+ var b2 = 0x00;
1540
+ if (ev.value.length > 1) {
1541
+ // skip first byte, just indicates unused bits which
1542
+ // will be padded with 0s anyway
1543
+ // get bytes with flag bits
1544
+ b2 = ev.value.charCodeAt(1);
1545
+ }
1546
+ // set flags
1547
+ e.client = (b2 & 0x80) === 0x80;
1548
+ e.server = (b2 & 0x40) === 0x40;
1549
+ e.email = (b2 & 0x20) === 0x20;
1550
+ e.objsign = (b2 & 0x10) === 0x10;
1551
+ e.reserved = (b2 & 0x08) === 0x08;
1552
+ e.sslCA = (b2 & 0x04) === 0x04;
1553
+ e.emailCA = (b2 & 0x02) === 0x02;
1554
+ e.objCA = (b2 & 0x01) === 0x01;
1555
+ } else if (e.name === 'subjectAltName' || e.name === 'issuerAltName') {
1556
+ // handle subjectAltName/issuerAltName
1557
+ e.altNames = [];
1558
+
1559
+ // ev is a SYNTAX SEQUENCE
1560
+ var gn;
1561
+ var ev = asn1.fromDer(e.value);
1562
+ for (var n = 0; n < ev.value.length; ++n) {
1563
+ // get GeneralName
1564
+ gn = ev.value[n];
1565
+ var altName = {
1566
+ type: gn.type,
1567
+ value: gn.value
1568
+ };
1569
+ e.altNames.push(altName);
1570
+
1571
+ // Note: Support for types 1,2,6,7,8
1572
+ switch (gn.type) {
1573
+ // rfc822Name
1574
+ case 1:
1575
+ // dNSName
1576
+ case 2:
1577
+ // uniformResourceIdentifier (URI)
1578
+ case 6:
1579
+ break;
1580
+ // IPAddress
1581
+ case 7:
1582
+ // convert to IPv4/IPv6 string representation
1583
+ altName.ip = forge.util.bytesToIP(gn.value);
1584
+ break;
1585
+ // registeredID
1586
+ case 8:
1587
+ altName.oid = asn1.derToOid(gn.value);
1588
+ break;
1589
+ // unsupported
1590
+ }
1591
+ }
1592
+ } else if (e.name === 'subjectKeyIdentifier') {
1593
+ // value is an OCTETSTRING w/the hash of the key-type specific
1594
+ // public key structure (eg: RSAPublicKey)
1595
+ var ev = asn1.fromDer(e.value);
1596
+ e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);
1597
+ }
1598
+ }
1599
+ return e;
1600
+ };
1601
+
1602
+ /**
1603
+ * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.
1604
+ *
1605
+ * Note: If the certification request is to be verified then compute hash
1606
+ * should be set to true. There is currently no implementation for converting
1607
+ * a certificate back to ASN.1 so the CertificationRequestInfo part of the
1608
+ * ASN.1 object needs to be scanned before the csr object is created.
1609
+ *
1610
+ * @param obj the asn1 representation of a PKCS#10 certification request (CSR).
1611
+ * @param computeHash true to compute the hash for verification.
1612
+ *
1613
+ * @return the certification request (CSR).
1614
+ */
1615
+ pki.certificationRequestFromAsn1 = function (obj, computeHash) {
1616
+ // validate certification request and capture data
1617
+ var capture = {};
1618
+ var errors = [];
1619
+ if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) {
1620
+ var error = new Error('Cannot read PKCS#10 certificate request. ' + 'ASN.1 object is not a PKCS#10 CertificationRequest.');
1621
+ error.errors = errors;
1622
+ throw error;
1623
+ }
1624
+
1625
+ // get oid
1626
+ var oid = asn1.derToOid(capture.publicKeyOid);
1627
+ if (oid !== pki.oids.rsaEncryption) {
1628
+ throw new Error('Cannot read public key. OID is not RSA.');
1629
+ }
1630
+
1631
+ // create certification request
1632
+ var csr = pki.createCertificationRequest();
1633
+ csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;
1634
+ csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);
1635
+ csr.signatureParameters = _readSignatureParameters(csr.signatureOid, capture.csrSignatureParams, true);
1636
+ csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);
1637
+ csr.siginfo.parameters = _readSignatureParameters(csr.siginfo.algorithmOid, capture.csrSignatureParams, false);
1638
+ csr.signature = capture.csrSignature;
1639
+
1640
+ // keep CertificationRequestInfo to preserve signature when exporting
1641
+ csr.certificationRequestInfo = capture.certificationRequestInfo;
1642
+ if (computeHash) {
1643
+ // create digest for OID signature type
1644
+ csr.md = _createSignatureDigest({
1645
+ signatureOid: csr.signatureOid,
1646
+ type: 'certification request'
1647
+ });
1648
+
1649
+ // produce DER formatted CertificationRequestInfo and digest it
1650
+ var bytes = asn1.toDer(csr.certificationRequestInfo);
1651
+ csr.md.update(bytes.getBytes());
1652
+ }
1653
+
1654
+ // handle subject, build subject message digest
1655
+ var smd = forge.md.sha1.create();
1656
+ csr.subject.getField = function (sn) {
1657
+ return _getAttribute(csr.subject, sn);
1658
+ };
1659
+ csr.subject.addField = function (attr) {
1660
+ _fillMissingFields([attr]);
1661
+ csr.subject.attributes.push(attr);
1662
+ };
1663
+ csr.subject.attributes = pki.RDNAttributesAsArray(capture.certificationRequestInfoSubject, smd);
1664
+ csr.subject.hash = smd.digest().toHex();
1665
+
1666
+ // convert RSA public key from ASN.1
1667
+ csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
1668
+
1669
+ // convert attributes from ASN.1
1670
+ csr.getAttribute = function (sn) {
1671
+ return _getAttribute(csr, sn);
1672
+ };
1673
+ csr.addAttribute = function (attr) {
1674
+ _fillMissingFields([attr]);
1675
+ csr.attributes.push(attr);
1676
+ };
1677
+ csr.attributes = pki.CRIAttributesAsArray(capture.certificationRequestInfoAttributes || []);
1678
+ return csr;
1679
+ };
1680
+
1681
+ /**
1682
+ * Creates an empty certification request (a CSR or certificate signing
1683
+ * request). Once created, its public key and attributes can be set and then
1684
+ * it can be signed.
1685
+ *
1686
+ * @return the empty certification request.
1687
+ */
1688
+ pki.createCertificationRequest = function () {
1689
+ var csr = {};
1690
+ csr.version = 0x00;
1691
+ csr.signatureOid = null;
1692
+ csr.signature = null;
1693
+ csr.siginfo = {};
1694
+ csr.siginfo.algorithmOid = null;
1695
+ csr.subject = {};
1696
+ csr.subject.getField = function (sn) {
1697
+ return _getAttribute(csr.subject, sn);
1698
+ };
1699
+ csr.subject.addField = function (attr) {
1700
+ _fillMissingFields([attr]);
1701
+ csr.subject.attributes.push(attr);
1702
+ };
1703
+ csr.subject.attributes = [];
1704
+ csr.subject.hash = null;
1705
+ csr.publicKey = null;
1706
+ csr.attributes = [];
1707
+ csr.getAttribute = function (sn) {
1708
+ return _getAttribute(csr, sn);
1709
+ };
1710
+ csr.addAttribute = function (attr) {
1711
+ _fillMissingFields([attr]);
1712
+ csr.attributes.push(attr);
1713
+ };
1714
+ csr.md = null;
1715
+
1716
+ /**
1717
+ * Sets the subject of this certification request.
1718
+ *
1719
+ * @param attrs the array of subject attributes to use.
1720
+ */
1721
+ csr.setSubject = function (attrs) {
1722
+ // set new attributes
1723
+ _fillMissingFields(attrs);
1724
+ csr.subject.attributes = attrs;
1725
+ csr.subject.hash = null;
1726
+ };
1727
+
1728
+ /**
1729
+ * Sets the attributes of this certification request.
1730
+ *
1731
+ * @param attrs the array of attributes to use.
1732
+ */
1733
+ csr.setAttributes = function (attrs) {
1734
+ // set new attributes
1735
+ _fillMissingFields(attrs);
1736
+ csr.attributes = attrs;
1737
+ };
1738
+
1739
+ /**
1740
+ * Signs this certification request using the given private key.
1741
+ *
1742
+ * @param key the private key to sign with.
1743
+ * @param md the message digest object to use (defaults to forge.md.sha1).
1744
+ */
1745
+ csr.sign = function (key, md) {
1746
+ // TODO: get signature OID from private key
1747
+ csr.md = md || forge.md.sha1.create();
1748
+ var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];
1749
+ if (!algorithmOid) {
1750
+ var error = new Error('Could not compute certification request digest. ' + 'Unknown message digest algorithm OID.');
1751
+ error.algorithm = csr.md.algorithm;
1752
+ throw error;
1753
+ }
1754
+ csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;
1755
+
1756
+ // get CertificationRequestInfo, convert to DER
1757
+ csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);
1758
+ var bytes = asn1.toDer(csr.certificationRequestInfo);
1759
+
1760
+ // digest and sign
1761
+ csr.md.update(bytes.getBytes());
1762
+ csr.signature = key.sign(csr.md);
1763
+ };
1764
+
1765
+ /**
1766
+ * Attempts verify the signature on the passed certification request using
1767
+ * its public key.
1768
+ *
1769
+ * A CSR that has been exported to a file in PEM format can be verified using
1770
+ * OpenSSL using this command:
1771
+ *
1772
+ * openssl req -in <the-csr-pem-file> -verify -noout -text
1773
+ *
1774
+ * @return true if verified, false if not.
1775
+ */
1776
+ csr.verify = function () {
1777
+ var rval = false;
1778
+ var md = csr.md;
1779
+ if (md === null) {
1780
+ md = _createSignatureDigest({
1781
+ signatureOid: csr.signatureOid,
1782
+ type: 'certification request'
1783
+ });
1784
+
1785
+ // produce DER formatted CertificationRequestInfo and digest it
1786
+ var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr);
1787
+ var bytes = asn1.toDer(cri);
1788
+ md.update(bytes.getBytes());
1789
+ }
1790
+ if (md !== null) {
1791
+ rval = _verifySignature({
1792
+ certificate: csr,
1793
+ md: md,
1794
+ signature: csr.signature
1795
+ });
1796
+ }
1797
+ return rval;
1798
+ };
1799
+ return csr;
1800
+ };
1801
+
1802
+ /**
1803
+ * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.
1804
+ *
1805
+ * @param obj the subject or issuer (distinguished name).
1806
+ *
1807
+ * @return the ASN.1 RDNSequence.
1808
+ */
1809
+ function _dnToAsn1(obj) {
1810
+ // create an empty RDNSequence
1811
+ var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
1812
+
1813
+ // iterate over attributes
1814
+ var attr, set;
1815
+ var attrs = obj.attributes;
1816
+ for (var i = 0; i < attrs.length; ++i) {
1817
+ attr = attrs[i];
1818
+ var value = attr.value;
1819
+
1820
+ // reuse tag class for attribute value if available
1821
+ var valueTagClass = asn1.Type.PRINTABLESTRING;
1822
+ if ('valueTagClass' in attr) {
1823
+ valueTagClass = attr.valueTagClass;
1824
+ if (valueTagClass === asn1.Type.UTF8) {
1825
+ value = forge.util.encodeUtf8(value);
1826
+ }
1827
+ // FIXME: handle more encodings
1828
+ }
1829
+
1830
+ // create a RelativeDistinguishedName set
1831
+ // each value in the set is an AttributeTypeAndValue first
1832
+ // containing the type (an OID) and second the value
1833
+ set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
1834
+ // AttributeType
1835
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()),
1836
+ // AttributeValue
1837
+ asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)])]);
1838
+ rval.value.push(set);
1839
+ }
1840
+ return rval;
1841
+ }
1842
+
1843
+ /**
1844
+ * Fills in missing fields in attributes.
1845
+ *
1846
+ * @param attrs the attributes to fill missing fields in.
1847
+ */
1848
+ function _fillMissingFields(attrs) {
1849
+ var attr;
1850
+ for (var i = 0; i < attrs.length; ++i) {
1851
+ attr = attrs[i];
1852
+
1853
+ // populate missing name
1854
+ if (typeof attr.name === 'undefined') {
1855
+ if (attr.type && attr.type in pki.oids) {
1856
+ attr.name = pki.oids[attr.type];
1857
+ } else if (attr.shortName && attr.shortName in _shortNames) {
1858
+ attr.name = pki.oids[_shortNames[attr.shortName]];
1859
+ }
1860
+ }
1861
+
1862
+ // populate missing type (OID)
1863
+ if (typeof attr.type === 'undefined') {
1864
+ if (attr.name && attr.name in pki.oids) {
1865
+ attr.type = pki.oids[attr.name];
1866
+ } else {
1867
+ var error = new Error('Attribute type not specified.');
1868
+ error.attribute = attr;
1869
+ throw error;
1870
+ }
1871
+ }
1872
+
1873
+ // populate missing shortname
1874
+ if (typeof attr.shortName === 'undefined') {
1875
+ if (attr.name && attr.name in _shortNames) {
1876
+ attr.shortName = _shortNames[attr.name];
1877
+ }
1878
+ }
1879
+
1880
+ // convert extensions to value
1881
+ if (attr.type === oids.extensionRequest) {
1882
+ attr.valueConstructed = true;
1883
+ attr.valueTagClass = asn1.Type.SEQUENCE;
1884
+ if (!attr.value && attr.extensions) {
1885
+ attr.value = [];
1886
+ for (var ei = 0; ei < attr.extensions.length; ++ei) {
1887
+ attr.value.push(pki.certificateExtensionToAsn1(_fillMissingExtensionFields(attr.extensions[ei])));
1888
+ }
1889
+ }
1890
+ }
1891
+ if (typeof attr.value === 'undefined') {
1892
+ var error = new Error('Attribute value not specified.');
1893
+ error.attribute = attr;
1894
+ throw error;
1895
+ }
1896
+ }
1897
+ }
1898
+
1899
+ /**
1900
+ * Fills in missing fields in certificate extensions.
1901
+ *
1902
+ * @param e the extension.
1903
+ * @param [options] the options to use.
1904
+ * [cert] the certificate the extensions are for.
1905
+ *
1906
+ * @return the extension.
1907
+ */
1908
+ function _fillMissingExtensionFields(e, options) {
1909
+ options = options || {};
1910
+
1911
+ // populate missing name
1912
+ if (typeof e.name === 'undefined') {
1913
+ if (e.id && e.id in pki.oids) {
1914
+ e.name = pki.oids[e.id];
1915
+ }
1916
+ }
1917
+
1918
+ // populate missing id
1919
+ if (typeof e.id === 'undefined') {
1920
+ if (e.name && e.name in pki.oids) {
1921
+ e.id = pki.oids[e.name];
1922
+ } else {
1923
+ var error = new Error('Extension ID not specified.');
1924
+ error.extension = e;
1925
+ throw error;
1926
+ }
1927
+ }
1928
+ if (typeof e.value !== 'undefined') {
1929
+ return e;
1930
+ }
1931
+
1932
+ // handle missing value:
1933
+
1934
+ // value is a BIT STRING
1935
+ if (e.name === 'keyUsage') {
1936
+ // build flags
1937
+ var unused = 0;
1938
+ var b2 = 0x00;
1939
+ var b3 = 0x00;
1940
+ if (e.digitalSignature) {
1941
+ b2 |= 0x80;
1942
+ unused = 7;
1943
+ }
1944
+ if (e.nonRepudiation) {
1945
+ b2 |= 0x40;
1946
+ unused = 6;
1947
+ }
1948
+ if (e.keyEncipherment) {
1949
+ b2 |= 0x20;
1950
+ unused = 5;
1951
+ }
1952
+ if (e.dataEncipherment) {
1953
+ b2 |= 0x10;
1954
+ unused = 4;
1955
+ }
1956
+ if (e.keyAgreement) {
1957
+ b2 |= 0x08;
1958
+ unused = 3;
1959
+ }
1960
+ if (e.keyCertSign) {
1961
+ b2 |= 0x04;
1962
+ unused = 2;
1963
+ }
1964
+ if (e.cRLSign) {
1965
+ b2 |= 0x02;
1966
+ unused = 1;
1967
+ }
1968
+ if (e.encipherOnly) {
1969
+ b2 |= 0x01;
1970
+ unused = 0;
1971
+ }
1972
+ if (e.decipherOnly) {
1973
+ b3 |= 0x80;
1974
+ unused = 7;
1975
+ }
1976
+
1977
+ // create bit string
1978
+ var value = String.fromCharCode(unused);
1979
+ if (b3 !== 0) {
1980
+ value += String.fromCharCode(b2) + String.fromCharCode(b3);
1981
+ } else if (b2 !== 0) {
1982
+ value += String.fromCharCode(b2);
1983
+ }
1984
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
1985
+ } else if (e.name === 'basicConstraints') {
1986
+ // basicConstraints is a SEQUENCE
1987
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
1988
+ // cA BOOLEAN flag defaults to false
1989
+ if (e.cA) {
1990
+ e.value.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, String.fromCharCode(0xFF)));
1991
+ }
1992
+ if ('pathLenConstraint' in e) {
1993
+ e.value.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(e.pathLenConstraint).getBytes()));
1994
+ }
1995
+ } else if (e.name === 'extKeyUsage') {
1996
+ // extKeyUsage is a SEQUENCE of OIDs
1997
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
1998
+ var seq = e.value.value;
1999
+ for (var key in e) {
2000
+ if (e[key] !== true) {
2001
+ continue;
2002
+ }
2003
+ // key is name in OID map
2004
+ if (key in oids) {
2005
+ seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oids[key]).getBytes()));
2006
+ } else if (key.indexOf('.') !== -1) {
2007
+ // assume key is an OID
2008
+ seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(key).getBytes()));
2009
+ }
2010
+ }
2011
+ } else if (e.name === 'nsCertType') {
2012
+ // nsCertType is a BIT STRING
2013
+ // build flags
2014
+ var unused = 0;
2015
+ var b2 = 0x00;
2016
+ if (e.client) {
2017
+ b2 |= 0x80;
2018
+ unused = 7;
2019
+ }
2020
+ if (e.server) {
2021
+ b2 |= 0x40;
2022
+ unused = 6;
2023
+ }
2024
+ if (e.email) {
2025
+ b2 |= 0x20;
2026
+ unused = 5;
2027
+ }
2028
+ if (e.objsign) {
2029
+ b2 |= 0x10;
2030
+ unused = 4;
2031
+ }
2032
+ if (e.reserved) {
2033
+ b2 |= 0x08;
2034
+ unused = 3;
2035
+ }
2036
+ if (e.sslCA) {
2037
+ b2 |= 0x04;
2038
+ unused = 2;
2039
+ }
2040
+ if (e.emailCA) {
2041
+ b2 |= 0x02;
2042
+ unused = 1;
2043
+ }
2044
+ if (e.objCA) {
2045
+ b2 |= 0x01;
2046
+ unused = 0;
2047
+ }
2048
+
2049
+ // create bit string
2050
+ var value = String.fromCharCode(unused);
2051
+ if (b2 !== 0) {
2052
+ value += String.fromCharCode(b2);
2053
+ }
2054
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
2055
+ } else if (e.name === 'subjectAltName' || e.name === 'issuerAltName') {
2056
+ // SYNTAX SEQUENCE
2057
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
2058
+ var altName;
2059
+ for (var n = 0; n < e.altNames.length; ++n) {
2060
+ altName = e.altNames[n];
2061
+ var value = altName.value;
2062
+ // handle IP
2063
+ if (altName.type === 7 && altName.ip) {
2064
+ value = forge.util.bytesFromIP(altName.ip);
2065
+ if (value === null) {
2066
+ var error = new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');
2067
+ error.extension = e;
2068
+ throw error;
2069
+ }
2070
+ } else if (altName.type === 8) {
2071
+ // handle OID
2072
+ if (altName.oid) {
2073
+ value = asn1.oidToDer(asn1.oidToDer(altName.oid));
2074
+ } else {
2075
+ // deprecated ... convert value to OID
2076
+ value = asn1.oidToDer(value);
2077
+ }
2078
+ }
2079
+ e.value.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, altName.type, false, value));
2080
+ }
2081
+ } else if (e.name === 'nsComment' && options.cert) {
2082
+ // sanity check value is ASCII (req'd) and not too big
2083
+ if (!/^[\x00-\x7F]*$/.test(e.comment) || e.comment.length < 1 || e.comment.length > 128) {
2084
+ throw new Error('Invalid "nsComment" content.');
2085
+ }
2086
+ // IA5STRING opaque comment
2087
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);
2088
+ } else if (e.name === 'subjectKeyIdentifier' && options.cert) {
2089
+ var ski = options.cert.generateSubjectKeyIdentifier();
2090
+ e.subjectKeyIdentifier = ski.toHex();
2091
+ // OCTETSTRING w/digest
2092
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());
2093
+ } else if (e.name === 'authorityKeyIdentifier' && options.cert) {
2094
+ // SYNTAX SEQUENCE
2095
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
2096
+ var seq = e.value.value;
2097
+ if (e.keyIdentifier) {
2098
+ var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier;
2099
+ seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));
2100
+ }
2101
+ if (e.authorityCertIssuer) {
2102
+ var authorityCertIssuer = [asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [_dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer)])];
2103
+ seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));
2104
+ }
2105
+ if (e.serialNumber) {
2106
+ var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber);
2107
+ seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));
2108
+ }
2109
+ } else if (e.name === 'cRLDistributionPoints') {
2110
+ e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
2111
+ var seq = e.value.value;
2112
+
2113
+ // Create sub SEQUENCE of DistributionPointName
2114
+ var subSeq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
2115
+
2116
+ // Create fullName CHOICE
2117
+ var fullNameGeneralNames = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
2118
+ var altName;
2119
+ for (var n = 0; n < e.altNames.length; ++n) {
2120
+ altName = e.altNames[n];
2121
+ var value = altName.value;
2122
+ // handle IP
2123
+ if (altName.type === 7 && altName.ip) {
2124
+ value = forge.util.bytesFromIP(altName.ip);
2125
+ if (value === null) {
2126
+ var error = new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');
2127
+ error.extension = e;
2128
+ throw error;
2129
+ }
2130
+ } else if (altName.type === 8) {
2131
+ // handle OID
2132
+ if (altName.oid) {
2133
+ value = asn1.oidToDer(asn1.oidToDer(altName.oid));
2134
+ } else {
2135
+ // deprecated ... convert value to OID
2136
+ value = asn1.oidToDer(value);
2137
+ }
2138
+ }
2139
+ fullNameGeneralNames.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, altName.type, false, value));
2140
+ }
2141
+
2142
+ // Add to the parent SEQUENCE
2143
+ subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));
2144
+ seq.push(subSeq);
2145
+ }
2146
+
2147
+ // ensure value has been defined by now
2148
+ if (typeof e.value === 'undefined') {
2149
+ var error = new Error('Extension value not specified.');
2150
+ error.extension = e;
2151
+ throw error;
2152
+ }
2153
+ return e;
2154
+ }
2155
+
2156
+ /**
2157
+ * Convert signature parameters object to ASN.1
2158
+ *
2159
+ * @param {String} oid Signature algorithm OID
2160
+ * @param params The signature parametrs object
2161
+ * @return ASN.1 object representing signature parameters
2162
+ */
2163
+ function _signatureParametersToAsn1(oid, params) {
2164
+ switch (oid) {
2165
+ case oids['RSASSA-PSS']:
2166
+ var parts = [];
2167
+ if (params.hash.algorithmOid !== undefined) {
2168
+ parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.hash.algorithmOid).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')])]));
2169
+ }
2170
+ if (params.mgf.algorithmOid !== undefined) {
2171
+ parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.mgf.algorithmOid).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')])])]));
2172
+ }
2173
+ if (params.saltLength !== undefined) {
2174
+ parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(params.saltLength).getBytes())]));
2175
+ }
2176
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);
2177
+ default:
2178
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');
2179
+ }
2180
+ }
2181
+
2182
+ /**
2183
+ * Converts a certification request's attributes to an ASN.1 set of
2184
+ * CRIAttributes.
2185
+ *
2186
+ * @param csr certification request.
2187
+ *
2188
+ * @return the ASN.1 set of CRIAttributes.
2189
+ */
2190
+ function _CRIAttributesToAsn1(csr) {
2191
+ // create an empty context-specific container
2192
+ var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
2193
+
2194
+ // no attributes, return empty container
2195
+ if (csr.attributes.length === 0) {
2196
+ return rval;
2197
+ }
2198
+
2199
+ // each attribute has a sequence with a type and a set of values
2200
+ var attrs = csr.attributes;
2201
+ for (var i = 0; i < attrs.length; ++i) {
2202
+ var attr = attrs[i];
2203
+ var value = attr.value;
2204
+
2205
+ // reuse tag class for attribute value if available
2206
+ var valueTagClass = asn1.Type.UTF8;
2207
+ if ('valueTagClass' in attr) {
2208
+ valueTagClass = attr.valueTagClass;
2209
+ }
2210
+ if (valueTagClass === asn1.Type.UTF8) {
2211
+ value = forge.util.encodeUtf8(value);
2212
+ }
2213
+ var valueConstructed = false;
2214
+ if ('valueConstructed' in attr) {
2215
+ valueConstructed = attr.valueConstructed;
2216
+ }
2217
+ // FIXME: handle more encodings
2218
+
2219
+ // create a RelativeDistinguishedName set
2220
+ // each value in the set is an AttributeTypeAndValue first
2221
+ // containing the type (an OID) and second the value
2222
+ var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
2223
+ // AttributeType
2224
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(attr.type).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
2225
+ // AttributeValue
2226
+ asn1.create(asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)])]);
2227
+ rval.value.push(seq);
2228
+ }
2229
+ return rval;
2230
+ }
2231
+ var jan_1_1950 = new Date('1950-01-01T00:00:00Z');
2232
+ var jan_1_2050 = new Date('2050-01-01T00:00:00Z');
2233
+
2234
+ /**
2235
+ * Converts a Date object to ASN.1
2236
+ * Handles the different format before and after 1st January 2050
2237
+ *
2238
+ * @param date date object.
2239
+ *
2240
+ * @return the ASN.1 object representing the date.
2241
+ */
2242
+ function _dateToAsn1(date) {
2243
+ if (date >= jan_1_1950 && date < jan_1_2050) {
2244
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, asn1.dateToUtcTime(date));
2245
+ } else {
2246
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, asn1.dateToGeneralizedTime(date));
2247
+ }
2248
+ }
2249
+
2250
+ /**
2251
+ * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.
2252
+ *
2253
+ * @param cert the certificate.
2254
+ *
2255
+ * @return the asn1 TBSCertificate.
2256
+ */
2257
+ pki.getTBSCertificate = function (cert) {
2258
+ // TBSCertificate
2259
+ var notBefore = _dateToAsn1(cert.validity.notBefore);
2260
+ var notAfter = _dateToAsn1(cert.validity.notAfter);
2261
+ var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
2262
+ // version
2263
+ asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
2264
+ // integer
2265
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(cert.version).getBytes())]),
2266
+ // serialNumber
2267
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, forge.util.hexToBytes(cert.serialNumber)),
2268
+ // signature
2269
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
2270
+ // algorithm
2271
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),
2272
+ // parameters
2273
+ _signatureParametersToAsn1(cert.siginfo.algorithmOid, cert.siginfo.parameters)]),
2274
+ // issuer
2275
+ _dnToAsn1(cert.issuer),
2276
+ // validity
2277
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [notBefore, notAfter]),
2278
+ // subject
2279
+ _dnToAsn1(cert.subject),
2280
+ // SubjectPublicKeyInfo
2281
+ pki.publicKeyToAsn1(cert.publicKey)]);
2282
+ if (cert.issuer.uniqueId) {
2283
+ // issuerUniqueID (optional)
2284
+ tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
2285
+ // TODO: support arbitrary bit length ids
2286
+ String.fromCharCode(0x00) + cert.issuer.uniqueId)]));
2287
+ }
2288
+ if (cert.subject.uniqueId) {
2289
+ // subjectUniqueID (optional)
2290
+ tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
2291
+ // TODO: support arbitrary bit length ids
2292
+ String.fromCharCode(0x00) + cert.subject.uniqueId)]));
2293
+ }
2294
+ if (cert.extensions.length > 0) {
2295
+ // extensions (optional)
2296
+ tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));
2297
+ }
2298
+ return tbs;
2299
+ };
2300
+
2301
+ /**
2302
+ * Gets the ASN.1 CertificationRequestInfo part of a
2303
+ * PKCS#10 CertificationRequest.
2304
+ *
2305
+ * @param csr the certification request.
2306
+ *
2307
+ * @return the asn1 CertificationRequestInfo.
2308
+ */
2309
+ pki.getCertificationRequestInfo = function (csr) {
2310
+ // CertificationRequestInfo
2311
+ var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
2312
+ // version
2313
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(csr.version).getBytes()),
2314
+ // subject
2315
+ _dnToAsn1(csr.subject),
2316
+ // SubjectPublicKeyInfo
2317
+ pki.publicKeyToAsn1(csr.publicKey),
2318
+ // attributes
2319
+ _CRIAttributesToAsn1(csr)]);
2320
+ return cri;
2321
+ };
2322
+
2323
+ /**
2324
+ * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.
2325
+ *
2326
+ * @param dn the DistinguishedName.
2327
+ *
2328
+ * @return the asn1 representation of a DistinguishedName.
2329
+ */
2330
+ pki.distinguishedNameToAsn1 = function (dn) {
2331
+ return _dnToAsn1(dn);
2332
+ };
2333
+
2334
+ /**
2335
+ * Converts an X.509v3 RSA certificate to an ASN.1 object.
2336
+ *
2337
+ * @param cert the certificate.
2338
+ *
2339
+ * @return the asn1 representation of an X.509v3 RSA certificate.
2340
+ */
2341
+ pki.certificateToAsn1 = function (cert) {
2342
+ // prefer cached TBSCertificate over generating one
2343
+ var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);
2344
+
2345
+ // Certificate
2346
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
2347
+ // TBSCertificate
2348
+ tbsCertificate,
2349
+ // AlgorithmIdentifier (signature algorithm)
2350
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
2351
+ // algorithm
2352
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(cert.signatureOid).getBytes()),
2353
+ // parameters
2354
+ _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)]),
2355
+ // SignatureValue
2356
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0x00) + cert.signature)]);
2357
+ };
2358
+
2359
+ /**
2360
+ * Converts X.509v3 certificate extensions to ASN.1.
2361
+ *
2362
+ * @param exts the extensions to convert.
2363
+ *
2364
+ * @return the extensions in ASN.1 format.
2365
+ */
2366
+ pki.certificateExtensionsToAsn1 = function (exts) {
2367
+ // create top-level extension container
2368
+ var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);
2369
+
2370
+ // create extension sequence (stores a sequence for each extension)
2371
+ var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
2372
+ rval.value.push(seq);
2373
+ for (var i = 0; i < exts.length; ++i) {
2374
+ seq.value.push(pki.certificateExtensionToAsn1(exts[i]));
2375
+ }
2376
+ return rval;
2377
+ };
2378
+
2379
+ /**
2380
+ * Converts a single certificate extension to ASN.1.
2381
+ *
2382
+ * @param ext the extension to convert.
2383
+ *
2384
+ * @return the extension in ASN.1 format.
2385
+ */
2386
+ pki.certificateExtensionToAsn1 = function (ext) {
2387
+ // create a sequence for each extension
2388
+ var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
2389
+
2390
+ // extnID (OID)
2391
+ extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(ext.id).getBytes()));
2392
+
2393
+ // critical defaults to false
2394
+ if (ext.critical) {
2395
+ // critical BOOLEAN DEFAULT FALSE
2396
+ extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, String.fromCharCode(0xFF)));
2397
+ }
2398
+ var value = ext.value;
2399
+ if (typeof ext.value !== 'string') {
2400
+ // value is asn.1
2401
+ value = asn1.toDer(value).getBytes();
2402
+ }
2403
+
2404
+ // extnValue (OCTET STRING)
2405
+ extseq.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));
2406
+ return extseq;
2407
+ };
2408
+
2409
+ /**
2410
+ * Converts a PKCS#10 certification request to an ASN.1 object.
2411
+ *
2412
+ * @param csr the certification request.
2413
+ *
2414
+ * @return the asn1 representation of a certification request.
2415
+ */
2416
+ pki.certificationRequestToAsn1 = function (csr) {
2417
+ // prefer cached CertificationRequestInfo over generating one
2418
+ var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr);
2419
+
2420
+ // Certificate
2421
+ return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
2422
+ // CertificationRequestInfo
2423
+ cri,
2424
+ // AlgorithmIdentifier (signature algorithm)
2425
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
2426
+ // algorithm
2427
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(csr.signatureOid).getBytes()),
2428
+ // parameters
2429
+ _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)]),
2430
+ // signature
2431
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, String.fromCharCode(0x00) + csr.signature)]);
2432
+ };
2433
+
2434
+ /**
2435
+ * Creates a CA store.
2436
+ *
2437
+ * @param certs an optional array of certificate objects or PEM-formatted
2438
+ * certificate strings to add to the CA store.
2439
+ *
2440
+ * @return the CA store.
2441
+ */
2442
+ pki.createCaStore = function (certs) {
2443
+ // create CA store
2444
+ var caStore = {
2445
+ // stored certificates
2446
+ certs: {}
2447
+ };
2448
+
2449
+ /**
2450
+ * Gets the certificate that issued the passed certificate or its
2451
+ * 'parent'.
2452
+ *
2453
+ * @param cert the certificate to get the parent for.
2454
+ *
2455
+ * @return the parent certificate or null if none was found.
2456
+ */
2457
+ caStore.getIssuer = function (cert) {
2458
+ var rval = getBySubject(cert.issuer);
2459
+
2460
+ // see if there are multiple matches
2461
+ /*if(forge.util.isArray(rval)) {
2462
+ // TODO: resolve multiple matches by checking
2463
+ // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.
2464
+ // FIXME: or alternatively do authority key mapping
2465
+ // if possible (X.509v1 certs can't work?)
2466
+ throw new Error('Resolving multiple issuer matches not implemented yet.');
2467
+ }*/
2468
+
2469
+ return rval;
2470
+ };
2471
+
2472
+ /**
2473
+ * Adds a trusted certificate to the store.
2474
+ *
2475
+ * @param cert the certificate to add as a trusted certificate (either a
2476
+ * pki.certificate object or a PEM-formatted certificate).
2477
+ */
2478
+ caStore.addCertificate = function (cert) {
2479
+ // convert from pem if necessary
2480
+ if (typeof cert === 'string') {
2481
+ cert = forge.pki.certificateFromPem(cert);
2482
+ }
2483
+ ensureSubjectHasHash(cert.subject);
2484
+ if (!caStore.hasCertificate(cert)) {
2485
+ // avoid duplicate certificates in store
2486
+ if (cert.subject.hash in caStore.certs) {
2487
+ // subject hash already exists, append to array
2488
+ var tmp = caStore.certs[cert.subject.hash];
2489
+ if (!forge.util.isArray(tmp)) {
2490
+ tmp = [tmp];
2491
+ }
2492
+ tmp.push(cert);
2493
+ caStore.certs[cert.subject.hash] = tmp;
2494
+ } else {
2495
+ caStore.certs[cert.subject.hash] = cert;
2496
+ }
2497
+ }
2498
+ };
2499
+
2500
+ /**
2501
+ * Checks to see if the given certificate is in the store.
2502
+ *
2503
+ * @param cert the certificate to check (either a pki.certificate or a
2504
+ * PEM-formatted certificate).
2505
+ *
2506
+ * @return true if the certificate is in the store, false if not.
2507
+ */
2508
+ caStore.hasCertificate = function (cert) {
2509
+ // convert from pem if necessary
2510
+ if (typeof cert === 'string') {
2511
+ cert = forge.pki.certificateFromPem(cert);
2512
+ }
2513
+ var match = getBySubject(cert.subject);
2514
+ if (!match) {
2515
+ return false;
2516
+ }
2517
+ if (!forge.util.isArray(match)) {
2518
+ match = [match];
2519
+ }
2520
+ // compare DER-encoding of certificates
2521
+ var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();
2522
+ for (var i = 0; i < match.length; ++i) {
2523
+ var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();
2524
+ if (der1 === der2) {
2525
+ return true;
2526
+ }
2527
+ }
2528
+ return false;
2529
+ };
2530
+
2531
+ /**
2532
+ * Lists all of the certificates kept in the store.
2533
+ *
2534
+ * @return an array of all of the pki.certificate objects in the store.
2535
+ */
2536
+ caStore.listAllCertificates = function () {
2537
+ var certList = [];
2538
+ for (var hash in caStore.certs) {
2539
+ if (caStore.certs.hasOwnProperty(hash)) {
2540
+ var value = caStore.certs[hash];
2541
+ if (!forge.util.isArray(value)) {
2542
+ certList.push(value);
2543
+ } else {
2544
+ for (var i = 0; i < value.length; ++i) {
2545
+ certList.push(value[i]);
2546
+ }
2547
+ }
2548
+ }
2549
+ }
2550
+ return certList;
2551
+ };
2552
+
2553
+ /**
2554
+ * Removes a certificate from the store.
2555
+ *
2556
+ * @param cert the certificate to remove (either a pki.certificate or a
2557
+ * PEM-formatted certificate).
2558
+ *
2559
+ * @return the certificate that was removed or null if the certificate
2560
+ * wasn't in store.
2561
+ */
2562
+ caStore.removeCertificate = function (cert) {
2563
+ var result;
2564
+
2565
+ // convert from pem if necessary
2566
+ if (typeof cert === 'string') {
2567
+ cert = forge.pki.certificateFromPem(cert);
2568
+ }
2569
+ ensureSubjectHasHash(cert.subject);
2570
+ if (!caStore.hasCertificate(cert)) {
2571
+ return null;
2572
+ }
2573
+ var match = getBySubject(cert.subject);
2574
+ if (!forge.util.isArray(match)) {
2575
+ result = caStore.certs[cert.subject.hash];
2576
+ delete caStore.certs[cert.subject.hash];
2577
+ return result;
2578
+ }
2579
+
2580
+ // compare DER-encoding of certificates
2581
+ var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();
2582
+ for (var i = 0; i < match.length; ++i) {
2583
+ var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();
2584
+ if (der1 === der2) {
2585
+ result = match[i];
2586
+ match.splice(i, 1);
2587
+ }
2588
+ }
2589
+ if (match.length === 0) {
2590
+ delete caStore.certs[cert.subject.hash];
2591
+ }
2592
+ return result;
2593
+ };
2594
+ function getBySubject(subject) {
2595
+ ensureSubjectHasHash(subject);
2596
+ return caStore.certs[subject.hash] || null;
2597
+ }
2598
+ function ensureSubjectHasHash(subject) {
2599
+ // produce subject hash if it doesn't exist
2600
+ if (!subject.hash) {
2601
+ var md = forge.md.sha1.create();
2602
+ subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);
2603
+ subject.hash = md.digest().toHex();
2604
+ }
2605
+ }
2606
+
2607
+ // auto-add passed in certs
2608
+ if (certs) {
2609
+ // parse PEM-formatted certificates as necessary
2610
+ for (var i = 0; i < certs.length; ++i) {
2611
+ var cert = certs[i];
2612
+ caStore.addCertificate(cert);
2613
+ }
2614
+ }
2615
+ return caStore;
2616
+ };
2617
+
2618
+ /**
2619
+ * Certificate verification errors, based on TLS.
2620
+ */
2621
+ pki.certificateError = {
2622
+ bad_certificate: 'forge.pki.BadCertificate',
2623
+ unsupported_certificate: 'forge.pki.UnsupportedCertificate',
2624
+ certificate_revoked: 'forge.pki.CertificateRevoked',
2625
+ certificate_expired: 'forge.pki.CertificateExpired',
2626
+ certificate_unknown: 'forge.pki.CertificateUnknown',
2627
+ unknown_ca: 'forge.pki.UnknownCertificateAuthority'
2628
+ };
2629
+
2630
+ /**
2631
+ * Verifies a certificate chain against the given Certificate Authority store
2632
+ * with an optional custom verify callback.
2633
+ *
2634
+ * @param caStore a certificate store to verify against.
2635
+ * @param chain the certificate chain to verify, with the root or highest
2636
+ * authority at the end (an array of certificates).
2637
+ * @param options a callback to be called for every certificate in the chain or
2638
+ * an object with:
2639
+ * verify a callback to be called for every certificate in the
2640
+ * chain
2641
+ * validityCheckDate the date against which the certificate
2642
+ * validity period should be checked. Pass null to not check
2643
+ * the validity period. By default, the current date is used.
2644
+ *
2645
+ * The verify callback has the following signature:
2646
+ *
2647
+ * verified - Set to true if certificate was verified, otherwise the
2648
+ * pki.certificateError for why the certificate failed.
2649
+ * depth - The current index in the chain, where 0 is the end point's cert.
2650
+ * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous
2651
+ * end point.
2652
+ *
2653
+ * The function returns true on success and on failure either the appropriate
2654
+ * pki.certificateError or an object with 'error' set to the appropriate
2655
+ * pki.certificateError and 'message' set to a custom error message.
2656
+ *
2657
+ * @return true if successful, error thrown if not.
2658
+ */
2659
+ pki.verifyCertificateChain = function (caStore, chain, options) {
2660
+ /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate
2661
+ Section 6: Certification Path Validation
2662
+ See inline parentheticals related to this particular implementation.
2663
+ The primary goal of path validation is to verify the binding between
2664
+ a subject distinguished name or a subject alternative name and subject
2665
+ public key, as represented in the end entity certificate, based on the
2666
+ public key of the trust anchor. This requires obtaining a sequence of
2667
+ certificates that support that binding. That sequence should be provided
2668
+ in the passed 'chain'. The trust anchor should be in the given CA
2669
+ store. The 'end entity' certificate is the certificate provided by the
2670
+ end point (typically a server) and is the first in the chain.
2671
+ To meet this goal, the path validation process verifies, among other
2672
+ things, that a prospective certification path (a sequence of n
2673
+ certificates or a 'chain') satisfies the following conditions:
2674
+ (a) for all x in {1, ..., n-1}, the subject of certificate x is
2675
+ the issuer of certificate x+1;
2676
+ (b) certificate 1 is issued by the trust anchor;
2677
+ (c) certificate n is the certificate to be validated; and
2678
+ (d) for all x in {1, ..., n}, the certificate was valid at the
2679
+ time in question.
2680
+ Note that here 'n' is index 0 in the chain and 1 is the last certificate
2681
+ in the chain and it must be signed by a certificate in the connection's
2682
+ CA store.
2683
+ The path validation process also determines the set of certificate
2684
+ policies that are valid for this path, based on the certificate policies
2685
+ extension, policy mapping extension, policy constraints extension, and
2686
+ inhibit any-policy extension.
2687
+ Note: Policy mapping extension not supported (Not Required).
2688
+ Note: If the certificate has an unsupported critical extension, then it
2689
+ must be rejected.
2690
+ Note: A certificate is self-issued if the DNs that appear in the subject
2691
+ and issuer fields are identical and are not empty.
2692
+ The path validation algorithm assumes the following seven inputs are
2693
+ provided to the path processing logic. What this specific implementation
2694
+ will use is provided parenthetically:
2695
+ (a) a prospective certification path of length n (the 'chain')
2696
+ (b) the current date/time: ('now').
2697
+ (c) user-initial-policy-set: A set of certificate policy identifiers
2698
+ naming the policies that are acceptable to the certificate user.
2699
+ The user-initial-policy-set contains the special value any-policy
2700
+ if the user is not concerned about certificate policy
2701
+ (Not implemented. Any policy is accepted).
2702
+ (d) trust anchor information, describing a CA that serves as a trust
2703
+ anchor for the certification path. The trust anchor information
2704
+ includes:
2705
+ (1) the trusted issuer name,
2706
+ (2) the trusted public key algorithm,
2707
+ (3) the trusted public key, and
2708
+ (4) optionally, the trusted public key parameters associated
2709
+ with the public key.
2710
+ (Trust anchors are provided via certificates in the CA store).
2711
+ The trust anchor information may be provided to the path processing
2712
+ procedure in the form of a self-signed certificate. The trusted anchor
2713
+ information is trusted because it was delivered to the path processing
2714
+ procedure by some trustworthy out-of-band procedure. If the trusted
2715
+ public key algorithm requires parameters, then the parameters are
2716
+ provided along with the trusted public key (No parameters used in this
2717
+ implementation).
2718
+ (e) initial-policy-mapping-inhibit, which indicates if policy mapping is
2719
+ allowed in the certification path.
2720
+ (Not implemented, no policy checking)
2721
+ (f) initial-explicit-policy, which indicates if the path must be valid
2722
+ for at least one of the certificate policies in the user-initial-
2723
+ policy-set.
2724
+ (Not implemented, no policy checking)
2725
+ (g) initial-any-policy-inhibit, which indicates whether the
2726
+ anyPolicy OID should be processed if it is included in a
2727
+ certificate.
2728
+ (Not implemented, so any policy is valid provided that it is
2729
+ not marked as critical) */
2730
+
2731
+ /* Basic Path Processing:
2732
+ For each certificate in the 'chain', the following is checked:
2733
+ 1. The certificate validity period includes the current time.
2734
+ 2. The certificate was signed by its parent (where the parent is either
2735
+ the next in the chain or from the CA store). Allow processing to
2736
+ continue to the next step if no parent is found but the certificate is
2737
+ in the CA store.
2738
+ 3. TODO: The certificate has not been revoked.
2739
+ 4. The certificate issuer name matches the parent's subject name.
2740
+ 5. TODO: If the certificate is self-issued and not the final certificate
2741
+ in the chain, skip this step, otherwise verify that the subject name
2742
+ is within one of the permitted subtrees of X.500 distinguished names
2743
+ and that each of the alternative names in the subjectAltName extension
2744
+ (critical or non-critical) is within one of the permitted subtrees for
2745
+ that name type.
2746
+ 6. TODO: If the certificate is self-issued and not the final certificate
2747
+ in the chain, skip this step, otherwise verify that the subject name
2748
+ is not within one of the excluded subtrees for X.500 distinguished
2749
+ names and none of the subjectAltName extension names are excluded for
2750
+ that name type.
2751
+ 7. The other steps in the algorithm for basic path processing involve
2752
+ handling the policy extension which is not presently supported in this
2753
+ implementation. Instead, if a critical policy extension is found, the
2754
+ certificate is rejected as not supported.
2755
+ 8. If the certificate is not the first or if its the only certificate in
2756
+ the chain (having no parent from the CA store or is self-signed) and it
2757
+ has a critical key usage extension, verify that the keyCertSign bit is
2758
+ set. If the key usage extension exists, verify that the basic
2759
+ constraints extension exists. If the basic constraints extension exists,
2760
+ verify that the cA flag is set. If pathLenConstraint is set, ensure that
2761
+ the number of certificates that precede in the chain (come earlier
2762
+ in the chain as implemented below), excluding the very first in the
2763
+ chain (typically the end-entity one), isn't greater than the
2764
+ pathLenConstraint. This constraint limits the number of intermediate
2765
+ CAs that may appear below a CA before only end-entity certificates
2766
+ may be issued. */
2767
+
2768
+ // if a verify callback is passed as the third parameter, package it within
2769
+ // the options object. This is to support a legacy function signature that
2770
+ // expected the verify callback as the third parameter.
2771
+ if (typeof options === 'function') {
2772
+ options = {
2773
+ verify: options
2774
+ };
2775
+ }
2776
+ options = options || {};
2777
+
2778
+ // copy cert chain references to another array to protect against changes
2779
+ // in verify callback
2780
+ chain = chain.slice(0);
2781
+ var certs = chain.slice(0);
2782
+ var validityCheckDate = options.validityCheckDate;
2783
+ // if no validityCheckDate is specified, default to the current date. Make
2784
+ // sure to maintain the value null because it indicates that the validity
2785
+ // period should not be checked.
2786
+ if (typeof validityCheckDate === 'undefined') {
2787
+ validityCheckDate = new Date();
2788
+ }
2789
+
2790
+ // verify each cert in the chain using its parent, where the parent
2791
+ // is either the next in the chain or from the CA store
2792
+ var first = true;
2793
+ var error = null;
2794
+ var depth = 0;
2795
+ do {
2796
+ var cert = chain.shift();
2797
+ var parent = null;
2798
+ var selfSigned = false;
2799
+ if (validityCheckDate) {
2800
+ // 1. check valid time
2801
+ if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) {
2802
+ error = {
2803
+ message: 'Certificate is not valid yet or has expired.',
2804
+ error: pki.certificateError.certificate_expired,
2805
+ notBefore: cert.validity.notBefore,
2806
+ notAfter: cert.validity.notAfter,
2807
+ // TODO: we might want to reconsider renaming 'now' to
2808
+ // 'validityCheckDate' should this API be changed in the future.
2809
+ now: validityCheckDate
2810
+ };
2811
+ }
2812
+ }
2813
+
2814
+ // 2. verify with parent from chain or CA store
2815
+ if (error === null) {
2816
+ parent = chain[0] || caStore.getIssuer(cert);
2817
+ if (parent === null) {
2818
+ // check for self-signed cert
2819
+ if (cert.isIssuer(cert)) {
2820
+ selfSigned = true;
2821
+ parent = cert;
2822
+ }
2823
+ }
2824
+ if (parent) {
2825
+ // FIXME: current CA store implementation might have multiple
2826
+ // certificates where the issuer can't be determined from the
2827
+ // certificate (happens rarely with, eg: old certificates) so normalize
2828
+ // by always putting parents into an array
2829
+ // TODO: there's may be an extreme degenerate case currently uncovered
2830
+ // where an old intermediate certificate seems to have a matching parent
2831
+ // but none of the parents actually verify ... but the intermediate
2832
+ // is in the CA and it should pass this check; needs investigation
2833
+ var parents = parent;
2834
+ if (!forge.util.isArray(parents)) {
2835
+ parents = [parents];
2836
+ }
2837
+
2838
+ // try to verify with each possible parent (typically only one)
2839
+ var verified = false;
2840
+ while (!verified && parents.length > 0) {
2841
+ parent = parents.shift();
2842
+ try {
2843
+ verified = parent.verify(cert);
2844
+ } catch (ex) {
2845
+ // failure to verify, don't care why, try next one
2846
+ }
2847
+ }
2848
+ if (!verified) {
2849
+ error = {
2850
+ message: 'Certificate signature is invalid.',
2851
+ error: pki.certificateError.bad_certificate
2852
+ };
2853
+ }
2854
+ }
2855
+ if (error === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) {
2856
+ // no parent issuer and certificate itself is not trusted
2857
+ error = {
2858
+ message: 'Certificate is not trusted.',
2859
+ error: pki.certificateError.unknown_ca
2860
+ };
2861
+ }
2862
+ }
2863
+
2864
+ // TODO: 3. check revoked
2865
+
2866
+ // 4. check for matching issuer/subject
2867
+ if (error === null && parent && !cert.isIssuer(parent)) {
2868
+ // parent is not issuer
2869
+ error = {
2870
+ message: 'Certificate issuer is invalid.',
2871
+ error: pki.certificateError.bad_certificate
2872
+ };
2873
+ }
2874
+
2875
+ // 5. TODO: check names with permitted names tree
2876
+
2877
+ // 6. TODO: check names against excluded names tree
2878
+
2879
+ // 7. check for unsupported critical extensions
2880
+ if (error === null) {
2881
+ // supported extensions
2882
+ var se = {
2883
+ keyUsage: true,
2884
+ basicConstraints: true
2885
+ };
2886
+ for (var i = 0; error === null && i < cert.extensions.length; ++i) {
2887
+ var ext = cert.extensions[i];
2888
+ if (ext.critical && !(ext.name in se)) {
2889
+ error = {
2890
+ message: 'Certificate has an unsupported critical extension.',
2891
+ error: pki.certificateError.unsupported_certificate
2892
+ };
2893
+ }
2894
+ }
2895
+ }
2896
+
2897
+ // 8. check for CA if cert is not first or is the only certificate
2898
+ // remaining in chain with no parent or is self-signed
2899
+ if (error === null && (!first || chain.length === 0 && (!parent || selfSigned))) {
2900
+ // first check keyUsage extension and then basic constraints
2901
+ var bcExt = cert.getExtension('basicConstraints');
2902
+ var keyUsageExt = cert.getExtension('keyUsage');
2903
+ if (keyUsageExt !== null) {
2904
+ // keyCertSign must be true and there must be a basic
2905
+ // constraints extension
2906
+ if (!keyUsageExt.keyCertSign || bcExt === null) {
2907
+ // bad certificate
2908
+ error = {
2909
+ message: 'Certificate keyUsage or basicConstraints conflict ' + 'or indicate that the certificate is not a CA. ' + 'If the certificate is the only one in the chain or ' + 'isn\'t the first then the certificate must be a ' + 'valid CA.',
2910
+ error: pki.certificateError.bad_certificate
2911
+ };
2912
+ }
2913
+ }
2914
+ // basic constraints cA flag must be set
2915
+ if (error === null && bcExt !== null && !bcExt.cA) {
2916
+ // bad certificate
2917
+ error = {
2918
+ message: 'Certificate basicConstraints indicates the certificate ' + 'is not a CA.',
2919
+ error: pki.certificateError.bad_certificate
2920
+ };
2921
+ }
2922
+ // if error is not null and keyUsage is available, then we know it
2923
+ // has keyCertSign and there is a basic constraints extension too,
2924
+ // which means we can check pathLenConstraint (if it exists)
2925
+ if (error === null && keyUsageExt !== null && 'pathLenConstraint' in bcExt) {
2926
+ // pathLen is the maximum # of intermediate CA certs that can be
2927
+ // found between the current certificate and the end-entity (depth 0)
2928
+ // certificate; this number does not include the end-entity (depth 0,
2929
+ // last in the chain) even if it happens to be a CA certificate itself
2930
+ var pathLen = depth - 1;
2931
+ if (pathLen > bcExt.pathLenConstraint) {
2932
+ // pathLenConstraint violated, bad certificate
2933
+ error = {
2934
+ message: 'Certificate basicConstraints pathLenConstraint violated.',
2935
+ error: pki.certificateError.bad_certificate
2936
+ };
2937
+ }
2938
+ }
2939
+ }
2940
+
2941
+ // call application callback
2942
+ var vfd = error === null ? true : error.error;
2943
+ var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;
2944
+ if (ret === true) {
2945
+ // clear any set error
2946
+ error = null;
2947
+ } else {
2948
+ // if passed basic tests, set default message and alert
2949
+ if (vfd === true) {
2950
+ error = {
2951
+ message: 'The application rejected the certificate.',
2952
+ error: pki.certificateError.bad_certificate
2953
+ };
2954
+ }
2955
+
2956
+ // check for custom error info
2957
+ if (ret || ret === 0) {
2958
+ // set custom message and error
2959
+ if (typeof ret === 'object' && !forge.util.isArray(ret)) {
2960
+ if (ret.message) {
2961
+ error.message = ret.message;
2962
+ }
2963
+ if (ret.error) {
2964
+ error.error = ret.error;
2965
+ }
2966
+ } else if (typeof ret === 'string') {
2967
+ // set custom error
2968
+ error.error = ret;
2969
+ }
2970
+ }
2971
+
2972
+ // throw error
2973
+ throw error;
2974
+ }
2975
+
2976
+ // no longer first cert in chain
2977
+ first = false;
2978
+ ++depth;
2979
+ } while (chain.length > 0);
2980
+ return true;
2981
+ };
2982
+ return x509.exports;
2983
+ }
2984
+
2985
+ export { requireX509 as __require };
2986
+ //# sourceMappingURL=x509.js.map