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