@alessiofrittoli/crypto-signature
Version:
Lightweight TypeScript Signatures library
2 lines (1 loc) • 2.18 kB
JavaScript
import{a as r}from"./chunk-562UYTL3.mjs";import n from"crypto";import{Hmac as y}from"@alessiofrittoli/crypto-key/Hmac";import{Algorithm as m}from"@alessiofrittoli/crypto-algorithm";import{Exception as t}from"@alessiofrittoli/exception";import{coerceToUint8Array as g}from"@alessiofrittoli/crypto-buffer/coercion";var c=class c{static sign(a,f,s=c.Algorithm){if(!a)throw new t("No data to sign has been provided.",{code:r.EMPTY_VALUE});if(!f)throw new t("No Private Key has been provided.",{code:r.NO_PRIVATEKEY});let d=c.jwkAlgToHash(s),A=g(a);if(!d)throw new t("Invalid JWK Algorithm name.",{code:r.INVALID_JWKNAME});try{if(s.startsWith("HS")){let e=f;return e=e instanceof CryptoKey?n.KeyObject.from(e):e,y.digest(A,e,d)}if(s==="EdDSA"){let e=f;return e=e instanceof CryptoKey?n.KeyObject.from(e):e,n.sign(null,A,e)}let i=f;i=i instanceof CryptoKey?n.KeyObject.from(i):i;let S=n.createSign(d);return S.write(A),S.end(),S.sign(i)}catch(i){throw new t("An error occured while creating the signature.",{code:r.UNKNOWN,cause:i})}}static isValid(a,f,s,d=c.Algorithm){if(!a)throw new t("No signature provided.",{code:r.NO_SIGN});if(!f)throw new t("The signed data is needed for integrity controls.",{code:r.EMPTY_VALUE});if(!s)throw new t("No Public Key has been provided.",{code:r.NO_PUBLICKEY});let A=c.jwkAlgToHash(d);if(!A)throw new t("Invalid JWK Algorithm name.",{code:r.INVALID_JWKNAME});let i=g(a),S=g(f);try{if(d.startsWith("HS")){let o=s;if(o=o instanceof CryptoKey?n.KeyObject.from(o):o,!y.isValid(Buffer.from(i),S,o,A))throw new t("Invalid signature.",{code:r.INVALID_SIGN});return!0}if(d==="EdDSA"){let o=s;if(o=o instanceof CryptoKey?n.KeyObject.from(o):o,!n.verify(null,S,o,i))throw new t("Invalid signature.",{code:r.INVALID_SIGN});return!0}let e=s;e=e instanceof CryptoKey?n.KeyObject.from(e):e;let l=n.createVerify(A);if(l.write(S),l.end(),!l.verify(e,i))throw new t("Invalid signature.",{code:r.INVALID_SIGN});return!0}catch(e){throw t.isException(e)?e:new t("An error occured while verifying the signature.",{code:r.UNKNOWN,cause:e})}}static jwkAlgToHash(a){return m.by({jwkAlg:a})?.hash}};c.Algorithm="HS256",c.HashDigest="SHA-256";var h=c;export{h as Signature};