This repository has been archived on 2023-04-04. You can view files and clone it, but cannot push or open issues or pull requests.
webcrypto/src/mechs/rsa/private_key.ts

41 lines
1.3 KiB
TypeScript
Raw Normal View History

2019-01-25 10:43:13 +00:00
import { AsnParser, AsnSerializer } from "@peculiar/asn1-schema";
import { JsonParser, JsonSerializer } from "@peculiar/json-schema";
2020-04-06 12:21:38 +00:00
import * as core from "webcrypto-core";
2019-01-25 10:43:13 +00:00
import { AsymmetricKey } from "../../keys";
import { getJwkAlgorithm } from "./helper";
export class RsaPrivateKey extends AsymmetricKey {
public readonly type: "private" = "private";
2022-03-02 18:35:31 +00:00
public override algorithm!: RsaHashedKeyAlgorithm;
2019-01-25 10:43:13 +00:00
public getKey() {
2020-04-06 12:21:38 +00:00
const keyInfo = AsnParser.parse(this.data, core.asn1.PrivateKeyInfo);
return AsnParser.parse(keyInfo.privateKey, core.asn1.RsaPrivateKey);
2019-01-25 10:43:13 +00:00
}
public toJSON() {
const key = this.getKey();
const json: JsonWebKey = {
kty: "RSA",
alg: getJwkAlgorithm(this.algorithm),
key_ops: this.usages,
ext: this.extractable,
};
return Object.assign(json, JsonSerializer.toJSON(key));
}
public fromJSON(json: JsonWebKey) {
2020-04-06 12:21:38 +00:00
const key = JsonParser.fromJSON(json, { targetSchema: core.asn1.RsaPrivateKey });
2019-01-25 10:43:13 +00:00
2020-04-06 12:21:38 +00:00
const keyInfo = new core.asn1.PrivateKeyInfo();
2019-01-25 10:43:13 +00:00
keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1";
keyInfo.privateKeyAlgorithm.parameters = null;
keyInfo.privateKey = AsnSerializer.serialize(key);
this.data = Buffer.from(AsnSerializer.serialize(keyInfo));
}
}