UNPKG

@alessiofrittoli/crypto-signature

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