-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpkcs1To8.js
84 lines (75 loc) · 1.55 KB
/
pkcs1To8.js
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
/* eslint no-bitwise: 0 */
function wrap(text, len) {
const length = len || 72;
let result = "";
for (let i = 0; i < text.length; i += length) {
result += text.slice(i, i + length);
result += "\n";
}
return result;
}
function pemPrivateKey(key) {
return `-----BEGIN PRIVATE KEY-----\n${wrap(key, 64)}-----END PRIVATE KEY-----`;
}
function stripPemFormatting(str) {
return str
.replace(/^-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----$/m, "")
.replace(/^-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----$/m, "")
.replace(/[\n\r]/g, "");
}
function arrayToPem(a) {
return window.btoa(a.map(c => String.fromCharCode(c)).join(""));
}
function stringToArray(s) {
return s.split("").map(c => c.charCodeAt());
}
function pemToArray(pem) {
return stringToArray(window.atob(pem));
}
const prefix = [
0x30,
0x82,
0x04,
0xbc,
0x02,
0x01,
0x00,
0x30,
0x0d,
0x06,
0x09,
0x2a,
0x86,
0x48,
0x86,
0xf7,
0x0d,
0x01,
0x01,
0x01,
0x05,
0x00,
0x04,
0x82,
0x04,
0xa6,
];
function pkcs1To8(privateKeyPkcs1Pem) {
const pem = stripPemFormatting(privateKeyPkcs1Pem);
const privateKeyPkcs1Array = pemToArray(pem);
const prefixPkcs8 = prefix.concat(privateKeyPkcs1Array);
const privateKeyPkcs8Pem = arrayToPem(prefixPkcs8);
const pkcs8Pem = pemPrivateKey(privateKeyPkcs8Pem);
return pkcs8Pem;
}
// crypto.subtle.importKey(
// "spki",
// keyTextBuffer,
// {
// name: "RSASSA-PKCS1-v1_5",
// hash: { name: "SHA-256" },
// },
// true,
// ["verify"]
// );
module.exports = { pkcs1To8 };