-
Notifications
You must be signed in to change notification settings - Fork 10
/
rsa_algorithm.ts
64 lines (57 loc) · 2.44 KB
/
rsa_algorithm.ts
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
import * as asn1Rsa from "@peculiar/asn1-rsa";
import { AlgorithmIdentifier } from "@peculiar/asn1-x509";
import { container, injectable } from "tsyringe";
import { diAlgorithm, IAlgorithm } from "./algorithm";
import { HashedAlgorithm } from "./types";
/**
* RSA algorithm provider
*/
@injectable()
export class RsaAlgorithm implements IAlgorithm {
public toAsnAlgorithm(alg: Algorithm): AlgorithmIdentifier | null {
switch (alg.name.toLowerCase()) {
case "rsassa-pkcs1-v1_5":
if ("hash" in alg) {
let hash: string;
if (typeof alg.hash === "string") {
hash = alg.hash;
} else if (alg.hash && typeof alg.hash === "object"
&& "name" in alg.hash && typeof alg.hash.name === "string") {
hash = alg.hash.name.toUpperCase();
} else {
throw new Error("Cannot get hash algorithm name");
}
switch (hash.toLowerCase()) {
case "sha-1":
return new AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha1WithRSAEncryption, parameters: null });
case "sha-256":
return new AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha256WithRSAEncryption, parameters: null });
case "sha-384":
return new AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha384WithRSAEncryption, parameters: null });
case "sha-512":
return new AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha512WithRSAEncryption, parameters: null });
}
} else {
return new AlgorithmIdentifier({ algorithm: asn1Rsa.id_rsaEncryption, parameters: null });
}
}
return null;
}
public toWebAlgorithm(alg: AlgorithmIdentifier): Algorithm | HashedAlgorithm | null {
switch (alg.algorithm) {
case asn1Rsa.id_rsaEncryption:
return { name: "RSASSA-PKCS1-v1_5" };
case asn1Rsa.id_sha1WithRSAEncryption:
return { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-1" } };
case asn1Rsa.id_sha256WithRSAEncryption:
return { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } };
case asn1Rsa.id_sha384WithRSAEncryption:
return { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-384" } };
case asn1Rsa.id_sha512WithRSAEncryption:
return { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-512" } };
}
return null;
}
}
// register RSA algorithm provider as a singleton object
container.registerSingleton(diAlgorithm, RsaAlgorithm);