source: frontend/node_modules/node-forge/lib/pem.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 6.5 KB
Line 
1/**
2 * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.
3 *
4 * See: RFC 1421.
5 *
6 * @author Dave Longley
7 *
8 * Copyright (c) 2013-2014 Digital Bazaar, Inc.
9 *
10 * A Forge PEM object has the following fields:
11 *
12 * type: identifies the type of message (eg: "RSA PRIVATE KEY").
13 *
14 * procType: identifies the type of processing performed on the message,
15 * it has two subfields: version and type, eg: 4,ENCRYPTED.
16 *
17 * contentDomain: identifies the type of content in the message, typically
18 * only uses the value: "RFC822".
19 *
20 * dekInfo: identifies the message encryption algorithm and mode and includes
21 * any parameters for the algorithm, it has two subfields: algorithm and
22 * parameters, eg: DES-CBC,F8143EDE5960C597.
23 *
24 * headers: contains all other PEM encapsulated headers -- where order is
25 * significant (for pairing data like recipient ID + key info).
26 *
27 * body: the binary-encoded body.
28 */
29var forge = require('./forge');
30require('./util');
31
32// shortcut for pem API
33var pem = module.exports = forge.pem = forge.pem || {};
34
35/**
36 * Encodes (serializes) the given PEM object.
37 *
38 * @param msg the PEM message object to encode.
39 * @param options the options to use:
40 * maxline the maximum characters per line for the body, (default: 64).
41 *
42 * @return the PEM-formatted string.
43 */
44pem.encode = function(msg, options) {
45 options = options || {};
46 var rval = '-----BEGIN ' + msg.type + '-----\r\n';
47
48 // encode special headers
49 var header;
50 if(msg.procType) {
51 header = {
52 name: 'Proc-Type',
53 values: [String(msg.procType.version), msg.procType.type]
54 };
55 rval += foldHeader(header);
56 }
57 if(msg.contentDomain) {
58 header = {name: 'Content-Domain', values: [msg.contentDomain]};
59 rval += foldHeader(header);
60 }
61 if(msg.dekInfo) {
62 header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};
63 if(msg.dekInfo.parameters) {
64 header.values.push(msg.dekInfo.parameters);
65 }
66 rval += foldHeader(header);
67 }
68
69 if(msg.headers) {
70 // encode all other headers
71 for(var i = 0; i < msg.headers.length; ++i) {
72 rval += foldHeader(msg.headers[i]);
73 }
74 }
75
76 // terminate header
77 if(msg.procType) {
78 rval += '\r\n';
79 }
80
81 // add body
82 rval += forge.util.encode64(msg.body, options.maxline || 64) + '\r\n';
83
84 rval += '-----END ' + msg.type + '-----\r\n';
85 return rval;
86};
87
88/**
89 * Decodes (deserializes) all PEM messages found in the given string.
90 *
91 * @param str the PEM-formatted string to decode.
92 *
93 * @return the PEM message objects in an array.
94 */
95pem.decode = function(str) {
96 var rval = [];
97
98 // split string into PEM messages (be lenient w/EOF on BEGIN line)
99 var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g;
100 var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/;
101 var rCRLF = /\r?\n/;
102 var match;
103 while(true) {
104 match = rMessage.exec(str);
105 if(!match) {
106 break;
107 }
108
109 // accept "NEW CERTIFICATE REQUEST" as "CERTIFICATE REQUEST"
110 // https://datatracker.ietf.org/doc/html/rfc7468#section-7
111 var type = match[1];
112 if(type === 'NEW CERTIFICATE REQUEST') {
113 type = 'CERTIFICATE REQUEST';
114 }
115
116 var msg = {
117 type: type,
118 procType: null,
119 contentDomain: null,
120 dekInfo: null,
121 headers: [],
122 body: forge.util.decode64(match[3])
123 };
124 rval.push(msg);
125
126 // no headers
127 if(!match[2]) {
128 continue;
129 }
130
131 // parse headers
132 var lines = match[2].split(rCRLF);
133 var li = 0;
134 while(match && li < lines.length) {
135 // get line, trim any rhs whitespace
136 var line = lines[li].replace(/\s+$/, '');
137
138 // RFC2822 unfold any following folded lines
139 for(var nl = li + 1; nl < lines.length; ++nl) {
140 var next = lines[nl];
141 if(!/\s/.test(next[0])) {
142 break;
143 }
144 line += next;
145 li = nl;
146 }
147
148 // parse header
149 match = line.match(rHeader);
150 if(match) {
151 var header = {name: match[1], values: []};
152 var values = match[2].split(',');
153 for(var vi = 0; vi < values.length; ++vi) {
154 header.values.push(ltrim(values[vi]));
155 }
156
157 // Proc-Type must be the first header
158 if(!msg.procType) {
159 if(header.name !== 'Proc-Type') {
160 throw new Error('Invalid PEM formatted message. The first ' +
161 'encapsulated header must be "Proc-Type".');
162 } else if(header.values.length !== 2) {
163 throw new Error('Invalid PEM formatted message. The "Proc-Type" ' +
164 'header must have two subfields.');
165 }
166 msg.procType = {version: values[0], type: values[1]};
167 } else if(!msg.contentDomain && header.name === 'Content-Domain') {
168 // special-case Content-Domain
169 msg.contentDomain = values[0] || '';
170 } else if(!msg.dekInfo && header.name === 'DEK-Info') {
171 // special-case DEK-Info
172 if(header.values.length === 0) {
173 throw new Error('Invalid PEM formatted message. The "DEK-Info" ' +
174 'header must have at least one subfield.');
175 }
176 msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};
177 } else {
178 msg.headers.push(header);
179 }
180 }
181
182 ++li;
183 }
184
185 if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {
186 throw new Error('Invalid PEM formatted message. The "DEK-Info" ' +
187 'header must be present if "Proc-Type" is "ENCRYPTED".');
188 }
189 }
190
191 if(rval.length === 0) {
192 throw new Error('Invalid PEM formatted message.');
193 }
194
195 return rval;
196};
197
198function foldHeader(header) {
199 var rval = header.name + ': ';
200
201 // ensure values with CRLF are folded
202 var values = [];
203 var insertSpace = function(match, $1) {
204 return ' ' + $1;
205 };
206 for(var i = 0; i < header.values.length; ++i) {
207 values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace));
208 }
209 rval += values.join(',') + '\r\n';
210
211 // do folding
212 var length = 0;
213 var candidate = -1;
214 for(var i = 0; i < rval.length; ++i, ++length) {
215 if(length > 65 && candidate !== -1) {
216 var insert = rval[candidate];
217 if(insert === ',') {
218 ++candidate;
219 rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate);
220 } else {
221 rval = rval.substr(0, candidate) +
222 '\r\n' + insert + rval.substr(candidate + 1);
223 }
224 length = (i - candidate - 1);
225 candidate = -1;
226 ++i;
227 } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') {
228 candidate = i;
229 }
230 }
231
232 return rval;
233}
234
235function ltrim(str) {
236 return str.replace(/^\s+/, '');
237}
Note: See TracBrowser for help on using the repository browser.