pki.js
2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Javascript implementation of a basic Public Key Infrastructure, including
* support for RSA public and private keys.
*
* @author Dave Longley
*
* Copyright (c) 2010-2013 Digital Bazaar, Inc.
*/
var forge = require('./forge');
require('./asn1');
require('./oids');
require('./pbe');
require('./pem');
require('./pbkdf2');
require('./pkcs12');
require('./pss');
require('./rsa');
require('./util');
require('./x509');
// shortcut for asn.1 API
var asn1 = forge.asn1;
/* Public Key Infrastructure (PKI) implementation. */
var pki = module.exports = forge.pki = forge.pki || {};
/**
* NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.
*
* Converts PEM-formatted data to DER.
*
* @param pem the PEM-formatted data.
*
* @return the DER-formatted data.
*/
pki.pemToDer = function(pem) {
var msg = forge.pem.decode(pem)[0];
if(msg.procType && msg.procType.type === 'ENCRYPTED') {
throw new Error('Could not convert PEM to DER; PEM is encrypted.');
}
return forge.util.createBuffer(msg.body);
};
/**
* Converts an RSA private key from PEM format.
*
* @param pem the PEM-formatted private key.
*
* @return the private key.
*/
pki.privateKeyFromPem = function(pem) {
var msg = forge.pem.decode(pem)[0];
if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {
var error = new Error('Could not convert private key from PEM; PEM ' +
'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');
error.headerType = msg.type;
throw error;
}
if(msg.procType && msg.procType.type === 'ENCRYPTED') {
throw new Error('Could not convert private key from PEM; PEM is encrypted.');
}
// convert DER to ASN.1 object
var obj = asn1.fromDer(msg.body);
return pki.privateKeyFromAsn1(obj);
};
/**
* Converts an RSA private key to PEM format.
*
* @param key the private key.
* @param maxline the maximum characters per line, defaults to 64.
*
* @return the PEM-formatted private key.
*/
pki.privateKeyToPem = function(key, maxline) {
// convert to ASN.1, then DER, then PEM-encode
var msg = {
type: 'RSA PRIVATE KEY',
body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()
};
return forge.pem.encode(msg, {maxline: maxline});
};
/**
* Converts a PrivateKeyInfo to PEM format.
*
* @param pki the PrivateKeyInfo.
* @param maxline the maximum characters per line, defaults to 64.
*
* @return the PEM-formatted private key.
*/
pki.privateKeyInfoToPem = function(pki, maxline) {
// convert to DER, then PEM-encode
var msg = {
type: 'PRIVATE KEY',
body: asn1.toDer(pki).getBytes()
};
return forge.pem.encode(msg, {maxline: maxline});
};