forked from node-saml/node-saml
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.ts
More file actions
45 lines (35 loc) · 1.3 KB
/
Copy pathcrypto.ts
File metadata and controls
45 lines (35 loc) · 1.3 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
import * as crypto from "crypto";
import { assertRequired } from "./utility";
export const keyToPEM = (
key: string | Buffer
): typeof key extends string | Buffer ? string | Buffer : Error => {
key = assertRequired(key, "key is required");
if (typeof key !== "string") return key;
if (key.split(/\r?\n/).length !== 1) return key;
const matchedKey = key.match(/.{1,64}/g);
if (matchedKey) {
const wrappedKey = [
"-----BEGIN PRIVATE KEY-----",
...matchedKey,
"-----END PRIVATE KEY-----",
"",
].join("\n");
return wrappedKey;
}
throw new Error("Invalid key");
};
export const certToPEM = (cert: string): string => {
cert = cert.match(/.{1,64}/g)!.join("\n");
if (cert.indexOf("-BEGIN CERTIFICATE-") === -1) cert = "-----BEGIN CERTIFICATE-----\n" + cert;
if (cert.indexOf("-END CERTIFICATE-") === -1) cert = cert + "\n-----END CERTIFICATE-----\n";
return cert;
};
export const generateUniqueId = (): string => {
return "_" + crypto.randomBytes(10).toString("hex");
};
export const removeCertPEMHeaderAndFooter = (certificate: string): string => {
certificate = certificate.replace(/-+BEGIN CERTIFICATE-+\r?\n?/, "");
certificate = certificate.replace(/-+END CERTIFICATE-+\r?\n?/, "");
certificate = certificate.replace(/\r\n/g, "\n");
return certificate;
};