UNPKG

@ldclabs/cose-ts

Version:

Implemented Keys, Algorithms (RFC9053), COSE (RFC9052) and CWT (RFC8392) in TypeScript.

75 lines 2.65 kB
// (c) 2023-present, LDC Labs. All rights reserved. // See the file LICENSE for licensing terms. import { ed25519 } from '@noble/curves/ed25519'; import * as iana from './iana'; import { assertBytes } from './map'; import { Key } from './key'; import { randomBytes, decodeCBOR } from './utils'; // TODO: more checks // Ed25519Key implements signature algorithm Ed25519 for COSE as defined in RFC9053. // https://datatracker.ietf.org/doc/html/rfc9053#name-edwards-curve-digital-signa. export class Ed25519Key extends Key { static fromBytes(data) { return new Ed25519Key(decodeCBOR(data)); } static generate(kid) { return Ed25519Key.fromSecret(randomBytes(32), kid); } static fromSecret(secret, kid) { assertBytes(secret, 'secret'); if (secret.length !== 32) { throw new Error(`cose-ts: Ed25519Key.fromSecret: secret size mismatch, expected 32, got ${secret.length}`); } const key = new Ed25519Key(); key.setParam(iana.OKPKeyParameterD, secret); if (kid != null) { key.setKid(kid); } return key; } static fromPublic(pubkey, kid) { assertBytes(pubkey, 'public key'); if (pubkey.length !== 32) { throw new Error(`cose-ts: Ed25519Key.fromPublic: public key size mismatch, expected 32, got ${pubkey.length}`); } const key = new Ed25519Key(); key.setParam(iana.OKPKeyParameterX, pubkey); if (kid != null) { key.setKid(kid); } return key; } constructor(kv) { super(kv); this.kty = iana.KeyTypeOKP; this.alg = iana.AlgorithmEdDSA; this.setParam(iana.OKPKeyParameterCrv, iana.EllipticCurveEd25519); } getSecretKey() { return this.getBytes(iana.OKPKeyParameterD, 'd'); } getPublicKey() { if (this.has(iana.OKPKeyParameterX)) { return this.getBytes(iana.OKPKeyParameterX, 'x'); } return ed25519.getPublicKey(this.getSecretKey()); } public() { const key = new Ed25519Key(this.clone()); if (key.has(iana.OKPKeyParameterD)) { key.setParam(iana.OKPKeyParameterX, key.getPublicKey()); key.delete(iana.OKPKeyParameterD); } if (key.has(iana.KeyParameterKeyOps)) { key.ops = [iana.KeyOperationVerify]; } return key; } sign(message) { return ed25519.sign(message, this.getSecretKey()); } verify(message, signature) { return ed25519.verify(signature, message, this.getPublicKey()); } } //# sourceMappingURL=ed25519.js.map