UNPKG

sm-js-bc

Version:

SM2/SM3/SM4 implementation in TypeScript based on Bouncy Castle Java

1 lines 76.9 kB
"use strict";var SMBC=(()=>{var bt=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var _t=Object.prototype.hasOwnProperty;var te=(u,t,e)=>t in u?bt(u,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):u[t]=e;var ee=(u,t)=>{for(var e in t)bt(u,e,{get:t[e],enumerable:!0})},re=(u,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $t(t))!_t.call(u,i)&&i!==e&&bt(u,i,{get:()=>t[i],enumerable:!(r=jt(t,i))||r.enumerable});return u};var ie=u=>re(bt({},"__esModule",{value:!0}),u);var s=(u,t,e)=>te(u,typeof t!="symbol"?t+"":t,e);var ne={};ee(ne,{AEADParameters:()=>lt,AbstractECMultiplier:()=>nt,Arrays:()=>K,AsymmetricKeyParameter:()=>ot,BigIntegers:()=>f,Bytes:()=>et,CBCBlockCipher:()=>Kt,CFBBlockCipher:()=>Lt,CoordinateSystem:()=>Pt,CryptoException:()=>H,DataLengthException:()=>x,ECBBlockCipher:()=>kt,ECConstants:()=>v,ECCurveAbstractFp:()=>mt,ECCurveFp:()=>rt,ECDomainParameters:()=>st,ECFieldElement:()=>ut,ECFieldElementFp:()=>G,ECKeyParameters:()=>Y,ECPointAbstractFp:()=>gt,ECPointFp:()=>ft,ECPrivateKeyParameters:()=>N,ECPublicKeyParameters:()=>T,FixedPointCombMultiplier:()=>D,GCMBlockCipher:()=>Dt,Integers:()=>J,InvalidCipherTextException:()=>z,KDF:()=>wt,KeyParameter:()=>L,OFBBlockCipher:()=>Ot,PKCS7Padding:()=>Tt,Pack:()=>C,PaddedBufferedBlockCipher:()=>Mt,ParametersWithID:()=>q,ParametersWithIV:()=>k,ParametersWithRandom:()=>M,SICBlockCipher:()=>zt,SM2:()=>St,SM2Engine:()=>W,SM2KeyExchange:()=>qt,SM2KeyExchangePrivateParameters:()=>Vt,SM2KeyExchangePublicParameters:()=>Nt,SM2Mode:()=>vt,SM2Signer:()=>_,SM3Digest:()=>U,SM4:()=>Ut,SM4Engine:()=>Z,SecureRandom:()=>F,SimpleECMultiplier:()=>Bt});var C=class u{static bigEndianToInt(t,e){let r=t[e]<<24;return r|=(t[e+1]&255)<<16,r|=(t[e+2]&255)<<8,r|=t[e+3]&255,r}static intToBigEndian(t,e,r){e[r]=t>>>24&255,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}static bigEndianToLong(t,e){let r=u.bigEndianToInt(t,e),i=u.bigEndianToInt(t,e+4);return BigInt(r>>>0)<<32n|BigInt(i>>>0)}static longToBigEndian(t,e,r){let i=Number(t>>32n&0xffffffffn),n=Number(t&0xffffffffn);u.intToBigEndian(i,e,r),u.intToBigEndian(n,e,r+4)}};var K=class{static concatenate(...t){let e=0;for(let n of t)e+=n.length;let r=new Uint8Array(e),i=0;for(let n of t)r.set(n,i),i+=n.length;return r}static fill(t,e){t.fill(e)}static areEqual(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}static constantTimeAreEqual(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}static copyOfRange(t,e,r){let i=r-e,n=new Uint8Array(i);return n.set(t.subarray(e,r)),n}};var et=class{static xorTo(t,e,r,i,n){for(let o=0;o<t;o++)i[n+o]^=e[r+o]}};var X=class X{static asUnsignedByteArray(t,e){let r=new Uint8Array(t);for(let i=t-1;i>=0;i--)r[i]=Number(e&0xffn),e>>=8n;return r}static fromUnsignedByteArray(t){let e=0n;for(let r=0;r<t.length;r++)e=e<<8n|BigInt(t[r]);return e}static createRandomBigInteger(t,e){let r=Math.ceil(t/8),i=new Uint8Array(r);e.nextBytes(i);let n=r*8-t;return n>0&&(i[0]&=(1<<8-n)-1),X.fromUnsignedByteArray(i)}static modOddInverse(t,e){return X.modInverse(e,t)}static modInverse(t,e){if(t=(t%e+e)%e,t===0n)throw new Error("No modular inverse exists");let[r,i]=[t,e],[n,o]=[1n,0n];for(;i!==0n;){let l=r/i;[r,i]=[i,r-l*i],[n,o]=[o,n-l*o]}if(r!==1n)throw new Error("No modular inverse exists");return(n%e+e)%e}static modPow(t,e,r){if(r===1n)return 0n;if(e===0n)return 1n;if(e===1n)return(t%r+r)%r;e<0n&&(t=X.modInverse(t,r),e=-e);let i=1n;for(t=(t%r+r)%r;e>0n;)e&1n&&(i=i*t%r),t=t*t%r,e>>=1n;return i}static bitLength(t){if(t===0n)return 0;t<0n&&(t=-t);let e=0;for(;t>0n;)e++,t>>=1n;return e}static testBit(t,e){if(e<0)throw new Error("Bit index must be non-negative");return t<0n?(t=-t-1n,(t>>BigInt(e)&1n)===0n):(t>>BigInt(e)&1n)===1n}static legendreSymbol(t,e){if(t=(t%e+e)%e,t===0n)return 0;if(t===1n)return 1;let r=X.modPow(t,(e-1n)/2n,e);return r===1n?1:r===e-1n?-1:0}static byteLength(t){let e=X.bitLength(t);return Math.ceil(e/8)}static setBit(t,e){if(e<0)throw new Error("Bit index must be non-negative");return t|1n<<BigInt(e)}static clearBit(t,e){if(e<0)throw new Error("Bit index must be non-negative");return t&~(1n<<BigInt(e))}static flipBit(t,e){if(e<0)throw new Error("Bit index must be non-negative");return t^1n<<BigInt(e)}static getLowestBits(t,e){if(e<0)throw new Error("Bit count must be non-negative");return e===0?0n:t&(1n<<BigInt(e))-1n}};s(X,"ZERO",0n);var f=X;var J=class{static numberOfLeadingZeros(t){if(t=t|0,t===0)return 32;let e=1;return t>>>16||(e+=16,t<<=16),t>>>24||(e+=8,t<<=8),t>>>28||(e+=4,t<<=4),t>>>30||(e+=2,t<<=2),e-=t>>>31,e}static bitCount(t){return t=t|0,t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),t=t+(t>>>4)&252645135,t=t+(t>>>8),t=t+(t>>>16),t&63}static rotateLeft(t,e){return t=t|0,e=e&31,t<<e|t>>>32-e}static rotateRight(t,e){return t=t|0,e=e&31,t>>>e|t<<32-e}static numberOfTrailingZeros(t){if(t=t|0,t===0)return 32;let e=31,r=t<<16;return r!==0&&(e-=16,t=r),r=t<<8,r!==0&&(e-=8,t=r),r=t<<4,r!==0&&(e-=4,t=r),r=t<<2,r!==0&&(e-=2,t=r),e-(t<<1>>>31)}static highestOneBit(t){return t=t|0,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t-(t>>>1)}static lowestOneBit(t){return t=t|0,t&-t}};var F=class{nextBytes(t){if(typeof crypto<"u"&&crypto.getRandomValues){crypto.getRandomValues(t);return}if(typeof globalThis<"u"&&globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(t);return}console.warn("Using Math.random() for random number generation. This is NOT cryptographically secure!");for(let e=0;e<t.length;e++)t[e]=Math.floor(Math.random()*256)}generateSeed(t){let e=new Uint8Array(t);return this.nextBytes(e),e}};var Et=class Et{constructor(t){s(this,"xBuf");s(this,"xBufOff");s(this,"byteCount");t?(this.xBuf=new Uint8Array(t.xBuf),this.xBufOff=t.xBufOff,this.byteCount=t.byteCount):(this.xBuf=new Uint8Array(4),this.xBufOff=0,this.byteCount=0n)}update(t){this.xBuf[this.xBufOff++]=t&255,this.xBufOff===this.xBuf.length&&(this.processWord(this.xBuf,0),this.xBufOff=0),this.byteCount+=1n}updateArray(t,e,r){let i=e,n=Math.max(0,r),o=0;if(this.xBufOff!==0){for(;o<n;)if(this.xBuf[this.xBufOff++]=t[i+o++],this.xBufOff===4){this.processWord(this.xBuf,0),this.xBufOff=0;break}}let l=(n-o&-4)+o;for(;o<l;o+=4)this.processWord(t,i+o);for(;o<n;)this.xBuf[this.xBufOff++]=t[i+o++];this.byteCount+=BigInt(n)}finish(){let t=this.byteCount<<3n;for(this.update(128);this.xBufOff!==0;)this.update(0);this.processLength(t),this.processBlock()}reset(){this.byteCount=0n,this.xBufOff=0,this.xBuf.fill(0),this.resetState()}getByteLength(){return Et.BYTE_LENGTH}copyIn(t){this.xBuf=new Uint8Array(t.xBuf),this.xBufOff=t.xBufOff,this.byteCount=t.byteCount}};s(Et,"BYTE_LENGTH",64);var yt=Et;var S=class S extends yt{constructor(e){super(e);s(this,"V",new Array(8));s(this,"X",new Array(68));s(this,"xOff",0);e?this.copyInSM3(e):this.resetState()}getAlgorithmName(){return"SM3"}getDigestSize(){return S.DIGEST_LENGTH}getByteLength(){return S.BLOCK_SIZE}doFinal(e,r){this.finish();for(let i=0;i<8;i++)C.intToBigEndian(this.V[i],e,r+i*4);return this.reset(),S.DIGEST_LENGTH}reset(e){e!==void 0?this.resetFromMemoable(e):(super.reset(),this.resetState())}resetState(){this.V=[...S.IV],this.xOff=0,this.X.fill(0)}processWord(e,r){this.X[this.xOff]=C.bigEndianToInt(e,r),this.xOff++,this.xOff>=16&&this.processBlock()}processLength(e){for(this.xOff>14&&(this.X[this.xOff]=0,this.xOff++,this.processBlock());this.xOff<14;)this.X[this.xOff]=0,this.xOff++;this.X[this.xOff++]=Number(e>>32n),this.X[this.xOff++]=Number(e&0xffffffffn)}processBlock(){for(let h=16;h<68;h++){let m=this.X[h-3],g=m<<15|m>>>17|0,y=this.X[h-13],d=y<<7|y>>>25|0;this.X[h]=this.P1(this.X[h-16]^this.X[h-9]^g)^d^this.X[h-6]|0}let e=this.V[0],r=this.V[1],i=this.V[2],n=this.V[3],o=this.V[4],l=this.V[5],a=this.V[6],c=this.V[7];for(let h=0;h<16;h++){let m=e<<12|e>>>20|0,g=m+o+S.T[h]|0,y=g<<7|g>>>25|0,d=y^m|0,b=this.X[h],P=b^this.X[h+4]|0,w=this.FF0(e,r,i)+n+d+P|0,I=this.GG0(o,l,a)+c+y+b|0;n=i,i=r<<9|r>>>23|0,r=e,e=w,c=a,a=l<<19|l>>>13|0,l=o,o=this.P0(I)}for(let h=16;h<64;h++){let m=e<<12|e>>>20|0,g=m+o+S.T[h]|0,y=g<<7|g>>>25|0,d=y^m|0,b=this.X[h],P=b^this.X[h+4]|0,w=this.FF1(e,r,i)+n+d+P|0,I=this.GG1(o,l,a)+c+y+b|0;n=i,i=r<<9|r>>>23|0,r=e,e=w,c=a,a=l<<19|l>>>13|0,l=o,o=this.P0(I)}this.V[0]^=e,this.V[1]^=r,this.V[2]^=i,this.V[3]^=n,this.V[4]^=o,this.V[5]^=l,this.V[6]^=a,this.V[7]^=c,this.xOff=0}FF0(e,r,i){return e^r^i}FF1(e,r,i){return e&r|e&i|r&i}GG0(e,r,i){return e^r^i}GG1(e,r,i){return e&r|~e&i}P0(e){return e^this.rotateLeft(e,9)^this.rotateLeft(e,17)}P1(e){return e^this.rotateLeft(e,15)^this.rotateLeft(e,23)}rotateLeft(e,r){return e<<r|e>>>32-r|0}copy(){return new S(this)}resetFromMemoable(e){if(!(e instanceof S))throw new Error("Cannot reset from different digest type");super.copyIn(e),this.copyInSM3(e)}copyInSM3(e){this.V=[...e.V],this.X=[...e.X],this.xOff=e.xOff}};s(S,"DIGEST_LENGTH",32),s(S,"BLOCK_SIZE",64),s(S,"IV",[1937774191,1226093241,388252375,3666478592,2842636476,372324522,3817729613,2969243214]),s(S,"T",(()=>{let e=new Array(64);for(let r=0;r<16;r++)e[r]=2043430169<<r|2043430169>>>32-r|0;for(let r=16;r<64;r++){let i=r%32,n=2055708042;e[r]=n<<i|n>>>32-i|0}return e})());var U=S;var v=class{};s(v,"ZERO",0n),s(v,"ONE",1n),s(v,"TWO",2n),s(v,"THREE",3n),s(v,"FOUR",4n),s(v,"EIGHT",8n);var ut=class{isZero(){return this.toBigInteger()===0n}isOne(){return this.toBigInteger()===1n}testBitZero(){return f.testBit(this.toBigInteger(),0)}getEncoded(){let t=Math.ceil(this.getFieldSize()/8);return f.asUnsignedByteArray(t,this.toBigInteger())}equals(t){return this===t?!0:this.toBigInteger()===t.toBigInteger()}},G=class u extends ut{constructor(e,r){super();s(this,"q");s(this,"x");(r<0n||r>=e)&&(r=(r%e+e)%e),this.q=e,this.x=r}toBigInteger(){return this.x}getFieldName(){return"Fp"}getFieldSize(){return f.bitLength(this.q)}getQ(){return this.q}add(e){return new u(this.q,this.modAdd(this.x,e.toBigInteger()))}addOne(){let e=this.x+1n;return e===this.q&&(e=0n),new u(this.q,e)}subtract(e){return new u(this.q,this.modSubtract(this.x,e.toBigInteger()))}multiply(e){return new u(this.q,this.modMult(this.x,e.toBigInteger()))}multiplyMinusProduct(e,r,i){let n=this.x,o=e.toBigInteger(),l=r.toBigInteger(),a=i.toBigInteger(),c=n*o,h=l*a;return new u(this.q,this.modReduce(c-h))}multiplyPlusProduct(e,r,i){let n=this.x,o=e.toBigInteger(),l=r.toBigInteger(),a=i.toBigInteger(),c=n*o,h=l*a;return new u(this.q,this.modReduce(c+h))}divide(e){return new u(this.q,this.modMult(this.x,this.modInverse(e.toBigInteger())))}negate(){return this.x===0n?this:new u(this.q,this.q-this.x)}square(){return new u(this.q,this.modMult(this.x,this.x))}squareMinusProduct(e,r){let i=this.x,n=e.toBigInteger(),o=r.toBigInteger(),l=i*i,a=n*o;return new u(this.q,this.modReduce(l-a))}squarePlusProduct(e,r){let i=this.x,n=e.toBigInteger(),o=r.toBigInteger(),l=i*i,a=n*o;return new u(this.q,this.modReduce(l+a))}invert(){return new u(this.q,this.modInverse(this.x))}sqrt(){if(this.isZero()||this.isOne())return this;if(!f.testBit(this.q,0))throw new Error("Square root not implemented for even modulus");if(f.testBit(this.q,1)){let e=(this.q>>2n)+1n,r=new u(this.q,f.modPow(this.x,e,this.q));return this.checkSqrt(r)}if(f.testBit(this.q,2)){let e=f.modPow(this.x,this.q>>3n,this.q),r=this.modMult(e,this.x);if(this.modMult(r,e)===1n)return this.checkSqrt(new u(this.q,r));let n=f.modPow(2n,this.q>>2n,this.q),o=this.modMult(r,n);return this.checkSqrt(new u(this.q,o))}return this.sqrtTonelliShanks()}sqrtTonelliShanks(){let e=this.q>>1n;if(f.modPow(this.x,e,this.q)!==1n)return null;let r=0,i=this.q-1n;for(;(i&1n)===0n;)r++,i>>=1n;let n=2n;for(;f.modPow(n,e,this.q)!==this.q-1n;)n++;let o=f.modPow(n,i,this.q),l=f.modPow(this.x,(i+1n)/2n,this.q),a=f.modPow(this.x,i,this.q),c=BigInt(r);for(;a!==1n;){let h=1n,m=this.modMult(a,a);for(;m!==1n&&h<c;)m=this.modMult(m,m),h++;let g=f.modPow(o,1n<<c-h-1n,this.q);l=this.modMult(l,g),o=this.modMult(g,g),a=this.modMult(a,o),c=h}return this.checkSqrt(new u(this.q,l))}checkSqrt(e){return e.square().toBigInteger()===this.x?e:null}modAdd(e,r){let i=e+r;return i>=this.q?i-this.q:i}modSubtract(e,r){let i=e-r;return i<0n?i+this.q:i}modMult(e,r){return this.modReduce(e*r)}modReduce(e){return(e%this.q+this.q)%this.q}modInverse(e){return f.modOddInverse(this.q,e)}equals(e){return this===e?!0:e instanceof u?this.q===e.q&&this.x===e.x:!1}hashCode(){return Number(this.q^this.x)}};var Gt=null;function Jt(u){Gt=u}function Ct(u,t,e,r){if(!Gt)throw new Error("ECPoint factory not registered");return Gt(u,t,e,r)}var xt=class{lookupVar(t){return this.lookup(t)}};var Pt=(a=>(a[a.AFFINE=0]="AFFINE",a[a.HOMOGENEOUS=1]="HOMOGENEOUS",a[a.JACOBIAN=2]="JACOBIAN",a[a.JACOBIAN_CHUDNOVSKY=3]="JACOBIAN_CHUDNOVSKY",a[a.JACOBIAN_MODIFIED=4]="JACOBIAN_MODIFIED",a[a.LAMBDA_AFFINE=5]="LAMBDA_AFFINE",a[a.LAMBDA_PROJECTIVE=6]="LAMBDA_PROJECTIVE",a[a.SKEWED=7]="SKEWED",a))(Pt||{}),Yt=class{constructor(t=null,e=null){s(this,"a");s(this,"b");s(this,"order");s(this,"cofactor");s(this,"coord");this.order=t,this.cofactor=e,this.coord=0}getFieldElementEncodingLength(){return Math.ceil(this.getFieldSize()/8)}getAffinePointEncodingLength(t){let e=this.getFieldElementEncodingLength();return t?1+e:1+e*2}validatePoint(t,e){let r=this.createPoint(t,e);if(!r.isValid())throw new Error("Invalid point coordinates");return r}supportsCoordinateSystem(t){return t===0}getCoordinateSystem(){return this.coord}importPoint(t){if(this===t.getCurve())return t;if(t.isInfinity())return this.getInfinity();let e=t.normalize();return this.createPoint(e.getXCoord().toBigInteger(),e.getYCoord().toBigInteger())}normalizeAll(t){this.normalizeAllWithRange(t,0,t.length,null)}normalizeAllWithRange(t,e,r,i){switch(this.checkPoints(t,e,r),this.getCoordinateSystem()){case 0:case 5:if(i!==null)throw new Error("'iso' not valid for affine coordinates");return}let n=[],o=[],l=0;for(let a=0;a<r;a++){let c=t[e+a];c&&(i!==null||!c.isNormalized())&&(n[l]=c.getZCoord(0),o[l++]=e+a)}if(l!==0)for(let a=0;a<l;a++){let c=o[a];t[c]=t[c].normalize()}}precompute(t,e,r){this.checkPoint(t),t.preCompTable||(t.preCompTable=new Map);let i=t.preCompTable.get(e)||null,n=r.precompute(i);return n!==i&&t.preCompTable.set(e,n),n}createCacheSafeLookupTable(t,e,r){let i=this.getFieldElementEncodingLength(),n=new Uint8Array(r*i*2),o=0;for(let a=0;a<r;a++){let c=t[e+a],h=c.getXCoord().getEncoded(),m=c.getYCoord().getEncoded();n.set(h,o),o+=i,n.set(m,o),o+=i}let l=this;return new class extends xt{getSize(){return r}lookup(a){let c=new Uint8Array(i),h=new Uint8Array(i),m=0;for(let g=0;g<r;g++){let y=(g^a)-1>>31;for(let d=0;d<i;d++)c[d]^=n[m+d]&y,h[d]^=n[m+i+d]&y;m+=i*2}return l.createRawPoint(l.fromBigInteger(f.fromUnsignedByteArray(c)),l.fromBigInteger(f.fromUnsignedByteArray(h)))}lookupVar(a){let c=new Uint8Array(i),h=new Uint8Array(i),m=a*i*2;for(let g=0;g<i;g++)c[g]=n[m+g],h[g]=n[m+i+g];return l.createRawPoint(l.fromBigInteger(f.fromUnsignedByteArray(c)),l.fromBigInteger(f.fromUnsignedByteArray(h)))}}}getA(){return this.a}getB(){return this.b}getOrder(){return this.order}getCofactor(){return this.cofactor}checkPoint(t){if(!t||this!==t.getCurve())throw new Error("'point' must be non-null and on this curve")}checkPoints(t,e=0,r=t.length){if(!t)throw new Error("'points' cannot be null");if(e<0||r<0||e>t.length-r)throw new Error("invalid range specified for points");for(let i=0;i<r;i++){let n=t[e+i];if(n&&this!==n.getCurve())throw new Error("'points' entries must be null or on this curve")}}equals(t){return this===t||t&&this.getFieldSize()===t.getFieldSize()&&this.a.toBigInteger()===t.a.toBigInteger()&&this.b.toBigInteger()===t.b.toBigInteger()}hashCode(){let t=Number(this.a.toBigInteger()&0xffffffffn),e=Number(this.b.toBigInteger()&0xffffffffn);return this.getFieldSize()^J.rotateLeft(t,8)^J.rotateLeft(e,16)}},mt=class extends Yt{constructor(e,r=null,i=null){super(r,i);s(this,"q");this.q=e}getQ(){return this.q}getFieldSize(){return f.bitLength(this.q)}isValidFieldElement(e){return e>=0n&&e<this.q}randomFieldElement(e){let r=this.getQ(),i=this.fromBigInteger(this.implRandomFieldElement(e,r)),n=this.fromBigInteger(this.implRandomFieldElement(e,r));return i.multiply(n)}randomFieldElementMult(e){let r=this.getQ(),i=this.fromBigInteger(this.implRandomFieldElementMult(e,r)),n=this.fromBigInteger(this.implRandomFieldElementMult(e,r));return i.multiply(n)}decompressPoint(e,r){let i=this.fromBigInteger(r),o=i.square().add(this.a).multiply(i).add(this.b).sqrt();if(o===null)throw new Error("Invalid point compression");return o.testBitZero()!==(e===1)&&(o=o.negate()),this.createRawPoint(i,o)}implRandomFieldElement(e,r){let i;do i=f.createRandomBigInteger(f.bitLength(r),e);while(i>=r);return i}implRandomFieldElementMult(e,r){let i;do i=f.createRandomBigInteger(f.bitLength(r),e);while(i<=0n||i>=r);return i}},Q=class Q extends mt{constructor(e,r,i,n=null,o=null){super(e,n,o);s(this,"r");s(this,"_infinity",null);this.q=e,this.r=this.calculateResidue(e),this.a=new G(e,r),this.b=new G(e,i),this.coord=Q.FP_DEFAULT_COORDS}get infinity(){return this._infinity||(this._infinity=Ct(this,null,null)),this._infinity}set infinity(e){this._infinity=e}static createInternal(e,r,i,n,o,l){let a=Object.create(Q.prototype);return a.q=e,a.r=r,a.a=i,a.b=n,a.order=o,a.cofactor=l,a.coord=Q.FP_DEFAULT_COORDS,a}calculateResidue(e){let r=f.bitLength(e);if(r>=96){let i=e>>BigInt(r-64);if(i===-1n)return 1n;if((i|1n)===-1n)return 2n}return 0n}cloneCurve(){return Q.createInternal(this.q,this.r,this.a,this.b,this.order,this.cofactor)}supportsCoordinateSystem(e){switch(e){case 0:case 1:case 2:case 4:return!0;default:return!1}}getQ(){return this.q}getFieldSize(){return f.bitLength(this.q)}fromBigInteger(e){return new G(this.q,e)}createRawPoint(e,r,i){return Ct(this,e,r,i)}createPoint(e,r){return this.createRawPoint(this.fromBigInteger(e),this.fromBigInteger(r))}importPoint(e){if(this!==e.getCurve()&&this.getCoordinateSystem()===2&&!e.isInfinity()){let r=e.getCurve().getCoordinateSystem();if(r===2||r===3||r===4)return this.createRawPoint(this.fromBigInteger(e.getXCoord().toBigInteger()),this.fromBigInteger(e.getYCoord().toBigInteger()),[this.fromBigInteger(e.getZCoord(0).toBigInteger())])}return super.importPoint(e)}getInfinity(){return this._infinity||(this._infinity=Ct(this,null,null)),this._infinity}setInfinity(e){this.infinity=e}decodePoint(e){if(e.length===0)throw new Error("Invalid point encoding");let r=e[0],i=this.getFieldElementEncodingLength();switch(r){case 0:if(e.length!==1)throw new Error("Incorrect length for infinity encoding");return this.getInfinity();case 2:case 3:if(e.length!==1+i)throw new Error("Incorrect length for compressed encoding");let n=r&1,o=f.fromUnsignedByteArray(e.subarray(1,1+i));return this.decompressPoint(n,o);case 4:if(e.length!==1+2*i)throw new Error("Incorrect length for uncompressed encoding");let l=f.fromUnsignedByteArray(e.subarray(1,1+i)),a=f.fromUnsignedByteArray(e.subarray(1+i,1+2*i));return this.validatePoint(l,a);case 6:case 7:if(e.length!==1+2*i)throw new Error("Incorrect length for hybrid encoding");let c=f.fromUnsignedByteArray(e.subarray(1,1+i)),h=f.fromUnsignedByteArray(e.subarray(1+i,1+2*i)),m=this.validatePoint(c,h);if(m.getYCoord().testBitZero()!==((r&1)===1))throw new Error("Inconsistent Y coordinate in hybrid encoding");return m;default:throw new Error("Invalid point encoding: "+r)}}};s(Q,"FP_DEFAULT_COORDS",4);var rt=Q;var j=class j{constructor(t,e,r,i){s(this,"curve");s(this,"x");s(this,"y");s(this,"zs");s(this,"preCompTable",null);this.curve=t,this.x=e,this.y=r,this.zs=i||j.getInitialZCoords(t)}static getInitialZCoords(t){if(!t)return j.EMPTY_ZS;switch(t.getCoordinateSystem()){case 0:case 5:return j.EMPTY_ZS;case 1:case 2:case 6:return[t.fromBigInteger(v.ONE)];case 3:{let r=t.fromBigInteger(v.ONE);return[r,r,r]}case 4:return[t.fromBigInteger(v.ONE),t.getA()];default:throw new Error("unknown coordinate system")}}getDetachedPoint(){return this.normalize().detach()}getCurve(){if(!this.curve)throw new Error("Detached point has no curve");return this.curve}getCurveCoordinateSystem(){return this.curve?this.curve.getCoordinateSystem():0}getAffineXCoord(){return this.checkNormalized(),this.getXCoord()}getAffineYCoord(){return this.checkNormalized(),this.getYCoord()}getXCoord(){if(!this.x)throw new Error("Point at infinity has no x-coordinate");return this.x}getYCoord(){if(!this.y)throw new Error("Point at infinity has no y-coordinate");return this.y}getZCoord(t){if(t<0||t>=this.zs.length)throw new Error("Invalid z-coordinate index");return this.zs[t]}getZCoords(){return this.zs.length===0?j.EMPTY_ZS:[...this.zs]}getRawXCoord(){return this.x}getRawYCoord(){return this.y}getRawZCoords(){return this.zs}checkNormalized(){if(!this.isNormalized())throw new Error("point not in normal form")}isNormalized(){let t=this.getCurveCoordinateSystem();return t===0||t===5||this.isInfinity()||this.zs[0].isOne()}normalize(){if(this.isInfinity())return this;switch(this.getCurveCoordinateSystem()){case 0:case 5:return this;default:{let t=this.getZCoord(0);if(t.isOne())return this;if(!this.curve)throw new Error("Detached points must be in affine coordinates");let e=t.invert();return this.normalizeWithZInv(e)}}}normalizeWithZInv(t){switch(this.getCurveCoordinateSystem()){case 1:case 6:return this.createScaledPoint(t,t);case 2:case 3:case 4:{let e=t.square(),r=e.multiply(t);return this.createScaledPoint(e,r)}default:throw new Error("not a projective coordinate system")}}createScaledPoint(t,e){let r=this.getRawXCoord(),i=this.getRawYCoord();if(!r||!i)throw new Error("Cannot scale infinity point");return this.getCurve().createRawPoint(r.multiply(t),i.multiply(e))}isInfinity(){return!this.x||!this.y||this.zs.length>0&&this.zs[0].isZero()}isValid(){if(this.isInfinity())return!0;if(!this.satisfiesCurveEquation())return!1;let t=this.curve?.getOrder();return!0}subtract(t){return t.isInfinity()?this:this.add(t.negate())}timesPow2(t){if(t<0)throw new Error("'e' cannot be negative");let e=this;for(;--t>=0;)e=e.twice();return e}twicePlus(t){return this.twice().add(t)}threeTimes(){return this.twicePlus(this)}multiply(t){return this.simpleMultiply(t)}simpleMultiply(t){if(t===0n)return this.getCurve().getInfinity();if(t<0n)throw new Error("Scalar must be non-negative");let e=this.getCurve().getInfinity(),r=this;for(;t!==0n;)(t&1n)===1n&&(e=e.add(r)),r=r.twice(),t>>=1n;return e}equals(t){if(!t)return!1;let e=this.curve,r=t.curve,i=!e,n=!r,o=this.isInfinity(),l=t.isInfinity();if(o||l)return o&&l&&(i||n||e.equals(r));let a=this,c=t;if(!(i&&n))if(i)c=c.normalize();else if(n)a=a.normalize();else if(e.equals(r)){let h=[this,e.importPoint(c)];e.normalizeAll(h),a=h[0],c=h[1]}else return!1;return a.getXCoord().equals(c.getXCoord())&&a.getYCoord().equals(c.getYCoord())}hashCode(){let t=this.curve,e=t?~t.hashCode():0;if(!this.isInfinity()){let r=this.normalize(),i=Number(r.getXCoord().toBigInteger()&0xffffffffn),n=Number(r.getYCoord().toBigInteger()&0xffffffffn);e^=i*17,e^=n*257}return e|0}toString(){if(this.isInfinity())return"INF";let t=[`(${this.getRawXCoord().toBigInteger()}`,`${this.getRawYCoord().toBigInteger()}`];for(let e of this.zs)t.push(e.toBigInteger().toString());return t.join(",")+")"}getEncoded(t){if(this.isInfinity())return new Uint8Array([0]);let e=this.normalize(),r=e.getXCoord().getEncoded();if(t){let o=new Uint8Array(r.length+1);return o[0]=e.getCompressionYTilde()?3:2,o.set(r,1),o}let i=e.getYCoord().getEncoded(),n=new Uint8Array(r.length+i.length+1);return n[0]=4,n.set(r,1),n.set(i,r.length+1),n}};s(j,"EMPTY_ZS",[]);var Ht=j,gt=class extends Ht{constructor(t,e,r,i){super(t,e,r,i)}getCompressionYTilde(){return this.getAffineYCoord().testBitZero()}satisfiesCurveEquation(){let t=this.x,e=this.y;if(!t||!e)return!1;let r=this.getCurve(),i=r.getA(),n=r.getB(),o=e.square();switch(this.getCurveCoordinateSystem()){case 0:break;case 1:{let a=this.zs[0];if(!a.isOne()){let c=a.square(),h=a.multiply(c);o=o.multiply(a),i=i.multiply(c),n=n.multiply(h)}break}case 2:case 3:case 4:{let a=this.zs[0];if(!a.isOne()){let c=a.square(),h=c.square(),m=c.multiply(h);i=i.multiply(h),n=n.multiply(m)}break}default:throw new Error("unsupported coordinate system")}let l=t.square().add(i).multiply(t).add(n);return o.equals(l)}},ft=class u extends gt{constructor(t,e,r,i){super(t,e,r,i)}detach(){return new u(null,this.getAffineXCoord(),this.getAffineYCoord())}getZCoord(t){return t===1&&this.getCurveCoordinateSystem()===4?this.getJacobianModifiedW():super.getZCoord(t)}getJacobianModifiedW(){let t=this.zs,e=t[1];return e||(e=this.calculateJacobianModifiedW(t[0],null),t[1]=e),e}calculateJacobianModifiedW(t,e){let r=this.getCurve().getA();if(r.isZero()||t.isOne())return r;let n=(e||t.square()).square(),o=r.negate(),l=o.toBigInteger()<0n?BigInt.asIntN(256,o.toBigInteger()).toString(2).length:o.toBigInteger().toString(2).length,a=r.toBigInteger()<0n?BigInt.asIntN(256,r.toBigInteger()).toString(2).length:r.toBigInteger().toString(2).length;return l<a?n.multiply(o).negate():n.multiply(r)}add(t){if(this.isInfinity())return t;if(t.isInfinity())return this;if(this===t)return this.twice();let e=this.getCurve(),r=e.getCoordinateSystem(),i=this.x,n=this.y,o=t.x,l=t.y;switch(r){case 0:{let a=o.subtract(i),c=l.subtract(n);if(a.isZero())return c.isZero()?this.twice():e.getInfinity();let h=c.divide(a),m=h.square().subtract(i).subtract(o),g=h.multiply(i.subtract(m)).subtract(n);return new u(e,m,g)}case 2:case 4:{let a=this.zs[0],c=t.zs[0],h=a.isOne(),m=c.isOne(),g=i,y=o,d=n,b=l;if(!h){let V=a.square();y=y.multiply(V),b=b.multiply(V).multiply(a)}if(!m){let V=c.square();g=g.multiply(V),d=d.multiply(V).multiply(c)}let P=y.subtract(g),w=b.subtract(d);if(P.isZero())return w.isZero()?this.twice():e.getInfinity();let I=P.square(),ht=I.multiply(P),Zt=g.multiply(I),Wt=w.square().subtract(ht).subtract(Zt).subtract(Zt),Qt=Zt.subtract(Wt).multiply(w).subtract(d.multiply(ht)),R=P;h||(R=R.multiply(a)),m||(R=R.multiply(c));let Rt;if(r===4){let V=e.getA(),Xt;V.isZero()||R.isOne()?Xt=V:Xt=R.square().square().multiply(V),Rt=[R,Xt]}else Rt=[R];return new u(e,Wt,Qt,Rt)}default:throw new Error("unsupported coordinate system")}}twice(){if(this.isInfinity())return this;let t=this.getCurve(),e=this.y;if(e.isZero())return t.getInfinity();let r=t.getCoordinateSystem(),i=this.x;switch(r){case 0:{let n=i.square(),o=n.add(n).add(n).add(t.getA()).divide(e.add(e)),l=o.square().subtract(i).subtract(i),a=o.multiply(i.subtract(l)).subtract(e);return new u(t,l,a)}case 2:{let n=this.zs[0],o=n.isOne(),l=e.square(),a=l.square(),c=t.getA(),h=i.square().multiply(t.fromBigInteger(v.THREE)),m;if(!c.isZero())if(o)h=h.add(c);else{let P=n.square().square();h=h.add(c.multiply(P))}m=i.multiply(l).multiply(t.fromBigInteger(v.FOUR));let g=h.square().subtract(m).subtract(m),y;o?y=e.add(e):y=e.multiply(n).add(e.multiply(n));let d=h.multiply(m.subtract(g)).subtract(a.multiply(t.fromBigInteger(v.EIGHT)));return new u(t,g,d,[y])}case 4:return this.twiceJacobianModified(!0);default:throw new Error("unsupported coordinate system")}}twiceJacobianModified(t){let e=this.getCurve(),r=this.x,i=this.y,n=this.zs[0],o=this.getJacobianModifiedW(),a=r.square().multiply(e.fromBigInteger(v.THREE)).add(o),c=i.add(i),h=c.multiply(i),m=r.multiply(h).add(r.multiply(h)),g=a.square().subtract(m.add(m)),y=h.square(),d=y.add(y),b=a.multiply(m.subtract(g)).subtract(d),P=t?d.multiply(o).add(d.multiply(o)):e.getA(),w=n.isOne()?c:c.multiply(n);return new u(e,g,b,[w,P])}negate(){if(this.isInfinity())return this;let t=this.getCurve();return t.getCoordinateSystem()!==0?new u(t,this.x,this.y.negate(),this.zs):new u(t,this.x,this.y.negate())}};Jt((u,t,e,r)=>new ft(u,t,e,r));var it=class{constructor(){s(this,"_offset",null);s(this,"_lookupTable",null);s(this,"_width",-1)}getLookupTable(){return this._lookupTable}setLookupTable(t){this._lookupTable=t}getOffset(){return this._offset}setOffset(t){this._offset=t}getWidth(){return this._width}setWidth(t){this._width=t}};var $=class ${static getCombSize(t){let e=t.getOrder();return e===null?t.getFieldSize()+1:this.bitLength(e)}static bitLength(t){return t===0n?0:t.toString(2).length}static getFixedPointPreCompInfo(t){return t instanceof it?t:null}static precompute(t){let e=t.getCurve();return e.precompute(t,$.PRECOMP_NAME,{precompute(r){let i=r instanceof it?r:null,n=$.getCombSize(e),o=n>250?6:5,l=1<<o;if($.checkExisting(i,l))return i;let a=Math.floor((n+o-1)/o),c=new Array(o+1);c[0]=t;for(let g=1;g<o;g++)c[g]=c[g-1].timesPow2(a);c[o]=c[0].add(c[1].negate()),e.normalizeAll(c);let h=new Array(l);h[0]=c[0];for(let g=o-1;g>=0;g--){let y=c[g],d=1<<g;for(let b=d;b<l;b+=d<<1)h[b]=h[b-d].add(y)}e.normalizeAll(h);let m=new it;return m.setLookupTable(e.createCacheSafeLookupTable(h,0,h.length)),m.setOffset(c[o]),m.setWidth(o),m}})}static checkExisting(t,e){return t!==null&&$.checkTable(t.getLookupTable(),e)}static checkTable(t,e){return t!==null&&t.getSize()>=e}};s($,"PRECOMP_NAME","bc_fixed_point");var dt=$;var At=class{static fromBigInteger(t,e){if(e<0n)throw new Error("Value cannot be negative");if(e===0n){let n=t+31>>>5;return new Array(n).fill(0)}let r=t+31>>>5,i=new Array(r).fill(0);for(let n=0;n<r;n++)i[n]=Number(e&0xFFFFFFFFn),e=e>>32n;return i}static toBigInteger(t){let e=0n;for(let r=t.length-1;r>=0;r--)e=e<<32n|BigInt(t[r]>>>0);return e}static getBit(t,e){let r=e>>>5,i=e&31;return r>=t.length?0:t[r]>>>i&1}};var nt=class{multiply(t,e){if(e===0n||t.isInfinity())return t.getCurve().getInfinity();let r=e<0n?-1:1,i=e<0n?-e:e,n=this.multiplyPositive(t,i),o=r>0?n:n.negate();return this.checkResult(o)}checkResult(t){return t.isInfinity()||t.isValid()?t:t.getCurve().getInfinity()}},D=class extends nt{multiplyPositive(t,e){let r=t.getCurve(),i=dt.getCombSize(r);if((e===0n?0:e.toString(2).length)>i)throw new Error("fixed-point comb doesn't support scalars larger than the curve order");let o=dt.precompute(t),l=o.getLookupTable(),a=o.getWidth();if(!l)throw new Error("Failed to precompute lookup table");let c=Math.floor((i+a-1)/a),h=r.getInfinity(),m=c*a,g=At.fromBigInteger(m,e),y=m-1;for(let b=0;b<c;b++){let P=0;for(let I=y-b;I>=0;I-=c){let ht=g[I>>>5]>>>(I&31);P^=ht>>>1,P<<=1,P^=ht}let w=l.lookup(P);h=h.twicePlus(w)}let d=o.getOffset();if(!d)throw new Error("Missing offset in precomputed data");return h.add(d)}},Bt=class extends nt{multiplyPositive(t,e){let r=t.getCurve().getInfinity(),i=t;for(;e!==0n;)(e&1n)===1n&&(r=r.add(i)),i=i.twice(),e>>=1n;return r}};var ot=class{constructor(t){s(this,"privateKey");this.privateKey=t}isPrivate(){return this.privateKey}};var st=class u{constructor(t,e,r,i,n){s(this,"curve");s(this,"G");s(this,"n");s(this,"h");s(this,"seed");this.curve=t,this.G=e,this.n=r,this.h=i??1n,this.seed=n??null}getCurve(){return this.curve}getG(){return this.G}getN(){return this.n}getH(){return this.h}getSeed(){return this.seed}equals(t){return t instanceof u?this.curve.equals(t.curve)&&this.G.equals(t.G)&&this.n===t.n&&this.h===t.h:!1}hashCode(){let t=this.curve.hashCode();return t^=this.G.hashCode(),t^=Number(this.n&0xffffffffn),t^=Number(this.h&0xffffffffn),t}};var Y=class extends ot{constructor(e,r){super(e);s(this,"parameters");this.parameters=r}getParameters(){return this.parameters}};var T=class extends Y{constructor(e,r){super(!1,r);s(this,"Q");this.Q=e}getQ(){return this.Q}};var N=class extends Y{constructor(e,r){super(!0,r);s(this,"d");this.d=e}getD(){return this.d}};var M=class{constructor(t,e){s(this,"parameters");s(this,"random");this.parameters=t,this.random=e??new F}getParameters(){return this.parameters}getRandom(){return this.random}};var q=class{constructor(t,e){s(this,"parameters");s(this,"id");this.parameters=t,this.id=new Uint8Array(e)}getParameters(){return this.parameters}getID(){return new Uint8Array(this.id)}};var wt=class{constructor(){s(this,"digest");this.digest=new U}deriveKey(t,e){let r=this.digest.getDigestSize(),i=new Uint8Array(e),n=1,o=0,l=new Uint8Array(r);for(;o<e;){this.digest.reset(),this.digest.updateArray(t,0,t.length);let a=new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,n&255]);this.digest.updateArray(a,0,4),this.digest.doFinal(l,0);let c=Math.min(e-o,r);i.set(l.subarray(0,c),o),o+=c,n++}return i}static isZero(t){for(let e=0;e<t.length;e++)if(t[e]!==0)return!1;return!0}};var H=class extends Error{constructor(t){super(t),this.name="CryptoException"}};var z=class extends H{constructor(t){super(t),this.name="InvalidCipherTextException"}};var x=class extends H{constructor(t){super(t),this.name="DataLengthException"}};var vt=(e=>(e.C1C2C3="C1C2C3",e.C1C3C2="C1C3C2",e))(vt||{}),W=class{constructor(t,e){s(this,"digest");s(this,"mode");s(this,"forEncryption",!1);s(this,"ecKey",null);s(this,"ecParams",null);s(this,"curveLength",0);s(this,"random",null);t instanceof U?(this.digest=t,this.mode=e??"C1C2C3"):(this.digest=new U,this.mode=t??"C1C2C3")}init(t,e){if(this.forEncryption=t,t){let r=e;if(this.ecKey=r.getParameters(),this.ecParams=this.ecKey.getParameters(),this.ecKey.getQ().multiply(this.ecParams.getH()).isInfinity())throw new Error("invalid key: [h]Q at infinity");this.random=r.getRandom()}else this.ecKey=e,this.ecParams=this.ecKey.getParameters();this.curveLength=Math.floor((this.ecParams.getCurve().getFieldSize()+7)/8)}processBlock(t,e,r){if(e+r>t.length||r===0)throw new x("input buffer too short");return this.forEncryption?this.encrypt(t,e,r):this.decrypt(t,e,r)}getOutputSize(t){return 1+2*this.curveLength+t+this.digest.getDigestSize()}createBasePointMultiplier(){return new D}encrypt(t,e,r){let i=new Uint8Array(r);i.set(t.subarray(e,e+r));let n=this.createBasePointMultiplier(),o,l;do{let c=this.nextK();o=n.multiply(this.ecParams.getG(),c).normalize().getEncoded(!1),l=this.ecKey.getQ().multiply(c).normalize(),this.kdf(this.digest,l,i)}while(this.notEncrypted(i,t,e));let a=new Uint8Array(this.digest.getDigestSize());switch(this.addFieldElement(this.digest,l.getAffineXCoord()),this.digest.updateArray(t,e,r),this.addFieldElement(this.digest,l.getAffineYCoord()),this.digest.doFinal(a,0),this.mode){case"C1C3C2":return K.concatenate(o,a,i);default:return K.concatenate(o,i,a)}}decrypt(t,e,r){let i=new Uint8Array(this.curveLength*2+1);i.set(t.subarray(e,e+i.length));let n=this.ecParams.getCurve().decodePoint(i);if(n.multiply(this.ecParams.getH()).isInfinity())throw new z("[h]C1 at infinity");let l=n.multiply(this.ecKey.getD()).normalize(),a=this.digest.getDigestSize(),c=new Uint8Array(r-i.length-a);this.mode==="C1C3C2"?c.set(t.subarray(e+i.length+a,e+r)):c.set(t.subarray(e+i.length,e+i.length+c.length)),this.kdf(this.digest,l,c);let h=new Uint8Array(a);this.addFieldElement(this.digest,l.getAffineXCoord()),this.digest.updateArray(c,0,c.length),this.addFieldElement(this.digest,l.getAffineYCoord()),this.digest.doFinal(h,0);let m=0;if(this.mode==="C1C3C2")for(let g=0;g<h.length;g++)m|=h[g]^t[e+i.length+g];else for(let g=0;g<h.length;g++)m|=h[g]^t[e+i.length+c.length+g];if(K.fill(i,0),K.fill(h,0),m!==0)throw K.fill(c,0),new z("invalid cipher text");return c}notEncrypted(t,e,r){for(let i=0;i<t.length;i++)if(t[i]!==e[r+i])return!1;return!0}kdf(t,e,r){let i=t.getDigestSize(),n=new Uint8Array(Math.max(4,i)),o=0,l=null,a=null;t&&typeof t.copy=="function"&&(this.addFieldElement(t,e.getAffineXCoord()),this.addFieldElement(t,e.getAffineYCoord()),l=t,a=l.copy());let c=0;for(;o<r.length;){l&&a?l.resetFromMemoable(a):(this.addFieldElement(t,e.getAffineXCoord()),this.addFieldElement(t,e.getAffineYCoord())),c++,n[0]=c>>>24&255,n[1]=c>>>16&255,n[2]=c>>>8&255,n[3]=c&255,t.updateArray(n,0,4),t.doFinal(n,0);let h=Math.min(i,r.length-o);et.xorTo(h,n,0,r,o),o+=h}}nextK(){let t=this.ecParams.getN(),e=this.getBitLength(t),r;do r=f.createRandomBigInteger(e,this.random);while(r===0n||r>=t);return r}getBitLength(t){return f.bitLength(t)}addFieldElement(t,e){let r=f.asUnsignedByteArray(this.curveLength,e.toBigInteger());t.updateArray(r,0,r.length)}};s(W,"Mode",vt);var It=class It{encode(t,e,r){if(e<=0n||e>=t)throw new Error("r component out of range");if(r<=0n||r>=t)throw new Error("s component out of range");let i=this.encodeInteger(e),n=this.encodeInteger(r),o=i.length+n.length,l=this.lengthBytesCount(o),a=new Uint8Array(1+l+o),c=0;return a[c++]=48,c+=this.encodeLength(a,c,o),a.set(i,c),c+=i.length,a.set(n,c),a}decode(t,e){let r=0;if(e[r]!==48)throw new Error("Invalid DER encoding: expected SEQUENCE tag");r++;let[i,n]=this.parseLength(e,r);if(r+=n,r+i!==e.length)throw new Error("Invalid DER encoding: incorrect sequence length");let[o,l]=this.parseInteger(e,r);r+=l;let[a,c]=this.parseInteger(e,r);if(r+=c,r!==e.length)throw new Error("Invalid DER encoding: extra bytes");if(o<=0n||o>=t)throw new Error("Invalid signature: r component out of range");if(a<=0n||a>=t)throw new Error("Invalid signature: s component out of range");return[o,a]}encodeInteger(t){if(t<=0n)throw new Error("Integer must be positive");let e=this.bigIntToBytes(t);if((e[0]&128)!==0){let o=new Uint8Array(e.length+1);o[0]=0,o.set(e,1),e=o}let r=this.lengthBytesCount(e.length),i=new Uint8Array(1+r+e.length),n=0;return i[n++]=2,n+=this.encodeLength(i,n,e.length),i.set(e,n),i}parseInteger(t,e){if(e>=t.length)throw new Error("Unexpected end of DER encoding");if(t[e]!==2)throw new Error("Invalid DER encoding: expected INTEGER tag");e++;let[r,i]=this.parseLength(t,e);if(e+=i,e+r>t.length)throw new Error("Invalid DER encoding: integer extends beyond available data");if(r>1&&t[e]===0&&(t[e+1]&128)===0)throw new Error("Invalid DER encoding: non-minimal integer");let n=t.slice(e,e+r),o=this.bytesToBigInt(n);if(o<=0n)throw new Error("Invalid DER encoding: non-positive integer");return[o,1+i+r]}lengthBytesCount(t){if(t<128)return 1;{let e=1,r=t;for(;r>0;)e++,r=r>>>8;return e}}encodeLength(t,e,r){if(r<128)return t[e]=r,1;{let i=0,n=r;for(;n>0;)i++,n=n>>>8;t[e]=128|i;let o=e+1;for(let l=i-1;l>=0;l--)t[o++]=r>>>l*8&255;return 1+i}}parseLength(t,e){if(e>=t.length)throw new Error("Unexpected end of DER encoding");let r=t[e];if((r&128)===0)return[r,1];{let i=r&127;if(i===0)throw new Error("Invalid DER encoding: indefinite length not allowed");if(i>4)throw new Error("Invalid DER encoding: length too large");if(e+1+i>t.length)throw new Error("Invalid DER encoding: length extends beyond available data");let n=0;for(let o=0;o<i;o++)n=n<<8|t[e+1+o];if(n<128)throw new Error("Invalid DER encoding: non-minimal length");return[n,1+i]}}bigIntToBytes(t){if(t===0n)return new Uint8Array([0]);let e=[];for(;t>0n;)e.unshift(Number(t&0xFFn)),t=t>>8n;return new Uint8Array(e)}bytesToBigInt(t){let e=0n;for(let r=0;r<t.length;r++)e=e<<8n|BigInt(t[r]);return e}};s(It,"INSTANCE",new It);var pt=It;var Ft=class{constructor(){s(this,"q",null);s(this,"random",null)}init(t,e){if(t<=1n)throw new Error("Order must be greater than 1");this.q=t,this.random=e}nextK(){if(!this.q||!this.random)throw new Error("Calculator not initialized");let t=this.getBitLength(this.q),e;do e=f.createRandomBigInteger(t-1,this.random),e===0n&&(e=1n);while(e>=this.q);return e}isDeterministic(){return!1}getBitLength(t){if(t===0n)return 0;let e=0,r=t;for(;r>0n;)e++,r=r>>1n;return e}};var at=class at{constructor(t=new U,e=new Ft){s(this,"digest");s(this,"dsaKCalculator");s(this,"keyParameters",null);s(this,"publicKey",null);s(this,"ecParams",null);s(this,"kCalculator",null);s(this,"forSigning",!1);s(this,"userID");s(this,"z",null);this.digest=t,this.dsaKCalculator=e,this.userID=at.DEFAULT_USER_ID}getAlgorithmName(){return"SM2"}init(t,e){this.forSigning=t;let r,i=null;if(e instanceof q){let n=e;this.userID=n.getID();let o=n.getParameters();if(o instanceof M){let l=o;i=l.getRandom(),r=l.getParameters()}else r=o}else if(e instanceof M){let n=e;i=n.getRandom(),r=n.getParameters(),this.userID=at.DEFAULT_USER_ID}else r=e,this.userID=at.DEFAULT_USER_ID;if(this.keyParameters=r,this.ecParams=r.getParameters(),t){if(!(r instanceof N))throw new Error("Signing requires ECPrivateKeyParameters");this.kCalculator=this.dsaKCalculator;let n=i||new F;this.kCalculator.init(this.ecParams.getN(),n),this.publicKey=this.calculatePublicKey(r)}else{if(!(r instanceof T))throw new Error("Verification requires ECPublicKeyParameters");this.publicKey=r}this.z=this.calculateZ(this.userID,this.publicKey),this.digest.reset(),this.digest.updateArray(this.z,0,this.z.length)}update(t,e,r){typeof t=="number"?this.digest.update(t):this.digest.updateArray(t,e,r)}generateSignature(){if(!this.forSigning)throw new Error("Signer not initialized for signing");if(!this.kCalculator||!this.ecParams||!this.keyParameters)throw new Error("Signer not properly initialized");let t=this.keyParameters,e=this.ecParams.getN(),r=this.ecParams.getG(),i=t.getD(),n=new Uint8Array(this.digest.getDigestSize());this.digest.doFinal(n,0);let o=this.hashToInteger(n,e),l=0n,a=0n;do{let c=this.kCalculator.nextK(),m=r.multiply(c).normalize().getAffineXCoord().toBigInteger();if(l=(o+m)%e,l===0n||(l+c)%e===0n)continue;a=this.modInverse(1n+i,e)*(c-l*i%e)%e,a<0n&&(a+=e)}while(a===0n);return this.digest.reset(),this.z&&this.digest.updateArray(this.z,0,this.z.length),pt.INSTANCE.encode(e,l,a)}verifySignature(t){if(this.forSigning)throw new Error("Signer not initialized for verification");if(!this.ecParams||!this.publicKey)throw new Error("Signer not properly initialized");try{let e=this.ecParams.getN(),r=this.ecParams.getG(),i=this.publicKey.getQ(),[n,o]=pt.INSTANCE.decode(e,t);if(n<=0n||n>=e||o<=0n||o>=e)return!1;let l=new Uint8Array(this.digest.getDigestSize());this.digest.doFinal(l,0);let a=this.hashToInteger(l,e),c=(n+o)%e;if(c===0n)return!1;let h=r.multiply(o),m=i.multiply(c),y=h.add(m).normalize().getAffineXCoord().toBigInteger(),b=(a+y)%e===n;return this.digest.reset(),this.z&&this.digest.updateArray(this.z,0,this.z.length),b}catch{return this.digest.reset(),this.z&&this.digest.updateArray(this.z,0,this.z.length),!1}}reset(){this.digest.reset(),this.z&&this.digest.updateArray(this.z,0,this.z.length)}createBasePointMultiplier(){return new D}calculatePublicKey(t){let e=t.getD(),r=t.getParameters(),i=r.getG().multiply(e);return new T(i,r)}calculateZ(t,e){let r=new U,i=t.length*8;r.update(i>>>8&255),r.update(i&255),r.updateArray(t,0,t.length);let n=this.ecParams.getCurve(),o=n.getFieldSize(),l=Math.ceil(o/8),a=n.getA().toBigInteger(),c=n.getB().toBigInteger(),h=f.asUnsignedByteArray(l,a),m=f.asUnsignedByteArray(l,c);r.updateArray(h,0,h.length),r.updateArray(m,0,m.length);let g=this.ecParams.getG().normalize(),y=f.asUnsignedByteArray(l,g.getAffineXCoord().toBigInteger()),d=f.asUnsignedByteArray(l,g.getAffineYCoord().toBigInteger());r.updateArray(y,0,y.length),r.updateArray(d,0,d.length);let b=e.getQ().normalize(),P=f.asUnsignedByteArray(l,b.getAffineXCoord().toBigInteger()),w=f.asUnsignedByteArray(l,b.getAffineYCoord().toBigInteger());r.updateArray(P,0,P.length),r.updateArray(w,0,w.length);let I=new Uint8Array(r.getDigestSize());return r.doFinal(I,0),I}calculateE(t,e){let r=0n;for(let i=0;i<e.length;i++)r=r<<8n|BigInt(e[i]);return r%t}hashToInteger(t,e){return this.calculateE(e,t)}modInverse(t,e){t<0n&&(t=(t%e+e)%e);let[r,i]=[t,e],[n,o]=[1n,0n];for(;i!==0n;){let l=r/i;[r,i]=[i,r-l*i],[n,o]=[o,n-l*o]}if(r>1n)throw new Error("Modular inverse does not exist");return n<0n&&(n+=e),n}};s(at,"DEFAULT_USER_ID",new TextEncoder().encode("1234567812345678"));var _=at;var E=class E{static getParameters(){if(!E.domainParams){let t=new rt(E.p,E.a,E.b,E.n,E.h),e=t.createPoint(E.Gx,E.Gy);E.domainParams=new st(t,e,E.n,E.h,null)}return E.domainParams}static getCurve(){return E.getParameters().getCurve()}static getG(){return E.getParameters().getG()}static getN(){return E.n}static getH(){return E.h}static validatePublicKey(t){return!(t.isInfinity()||!t.isValid()||!t.multiply(E.n).isInfinity())}static validatePrivateKey(t){return t>0n&&t<E.n}static generateKeyPair(){let t=new F,e;do{let o=t.generateSeed(32);e=BigInt("0x"+Array.from(o).map(l=>l.toString(16).padStart(2,"0")).join(""))}while(e===0n||e>=E.n);let i=E.getG().multiply(e);if(i.isInfinity()||!E.validatePublicKey(i))throw new Error("Generated invalid public key");let n=i.normalize();return{privateKey:e,publicKey:{x:n.getAffineXCoord().toBigInteger(),y:n.getAffineYCoord().toBigInteger()}}}static encrypt(t,e,r){let i=typeof t=="string"?new TextEncoder().encode(t):t,n,o;if(typeof e=="object"&&e!==null)n=e.x,o=e.y;else if(typeof e=="bigint"&&typeof r=="bigint")n=e,o=r;else throw new Error("Invalid public key format. Expected object with x,y properties or separate x,y BigInt values");let a=E.getCurve().createPoint(n,o),c=E.getParameters(),h=new T(a,c),m=new W;return m.init(!0,new M(h,new F)),m.processBlock(i,0,i.length)}static decrypt(t,e){let r=E.getParameters(),i=new N(e,r),n=new W;return n.init(!1,i),n.processBlock(t,0,t.length)}static sign(t,e){let r=typeof t=="string"?new TextEncoder().encode(t):t,i=E.getParameters(),n=new N(e,i),o=new _;return o.init(!0,new M(n,new F)),o.update(r,0,r.length),o.generateSignature()}static verify(t,e,r,i){let n=typeof t=="string"?new TextEncoder().encode(t):t,o,l;if(typeof r=="object"&&r!==null)o=r.x,l=r.y;else if(typeof r=="bigint"&&typeof i=="bigint")o=r,l=i;else throw new Error("Invalid public key format. Expected object with x,y properties or separate x,y BigInt values");let c=E.getCurve().createPoint(o,l),h=E.getParameters(),m=new T(c,h),g=new _;return g.init(!1,m),g.update(n,0,n.length),g.verifySignature(e)}};s(E,"p",0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFFn),s(E,"a",0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFCn),s(E,"b",0x28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93n),s(E,"n",0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123n),s(E,"h",1n),s(E,"Gx",0x32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7n),s(E,"Gy",0xBC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0n),s(E,"domainParams",null);var St=E;var L=class{constructor(t){s(this,"key");this.key=new Uint8Array(t)}getKey(){return this.key}};var A=class A{constructor(){s(this,"X",new Int32Array(4));s(this,"rk",null)}init(t,e){if(!(e instanceof L))throw new Error(`invalid parameter passed to SM4 init - ${e.constructor.name}`);let r=e.getKey();if(r.length!==16)throw new Error("SM4 requires a 128 bit key");this.rk=this.expandKey(t,r)}getAlgorithmName(){return"SM4"}getBlockSize(){return A.BLOCK_SIZE}processBlock(t,e,r,i){if(this.rk===null)throw new Error("SM4 not initialised");if(e+A.BLOCK_SIZE>t.length)throw new x("input buffer too short");if(i+A.BLOCK_SIZE>r.length)throw new x("output buffer too short");this.X[0]=C.bigEndianToInt(t,e),this.X[1]=C.bigEndianToInt(t,e+4),this.X[2]=C.bigEndianToInt(t,e+8),this.X[3]=C.bigEndianToInt(t,e+12);for(let n=0;n<32;n+=4)this.X[0]=this.F0(this.X,this.rk[n]),this.X[1]=this.F1(this.X,this.rk[n+1]),this.X[2]=this.F2(this.X,this.rk[n+2]),this.X[3]=this.F3(this.X,this.rk[n+3]);return C.intToBigEndian(this.X[3],r,i),C.intToBigEndian(this.X[2],r,i+4),C.intToBigEndian(this.X[1],r,i+8),C.intToBigEndian(this.X[0],r,i+12),A.BLOCK_SIZE}reset(){}rotateLeft(t,e){return t<<e|t>>>32-e|0}tau(t){let e=(A.Sbox[t>>>24&255]&255)<<24,r=(A.Sbox[t>>>16&255]&255)<<16,i=(A.Sbox[t>>>8&255]&255)<<8,n=A.Sbox[t&255]&255;return e|r|i|n|0}L_ap(t){return t^this.rotateLeft(t,13)^this.rotateLeft(t,23)|0}T_ap(t){return this.L_ap(this.tau(t))}expandKey(t,e){let r=new Int32Array(32),i=new Int32Array(4);i[0]=C.bigEndianToInt(e,0),i[1]=C.bigEndianToInt(e,4),i[2]=C.bigEndianToInt(e,8),i[3]=C.bigEndianToInt(e,12);let n=new Int32Array(4);if(n[0]=i[0]^A.FK[0]|0,n[1]=i[1]^A.FK[1]|0,n[2]=i[2]^A.FK[2]|0,n[3]=i[3]^A.FK[3]|0,t){r[0]=n[0]^this.T_ap(n[1]^n[2]^n[3]^A.CK[0]|0)|0,r[1]=n[1]^this.T_ap(n[2]^n[3]^r[0]^A.CK[1]|0)|0,r[2]=n[2]^this.T_ap(n[3]^r[0]^r[1]^A.CK[2]|0)|0,r[3]=n[3]^this.T_ap(r[0]^r[1]^r[2]^A.CK[3]|0)|0;for(let o=4;o<32;o++)r[o]=r[o-4]^this.T_ap(r[o-3]^r[o-2]^r[o-1]^A.CK[o]|0)|0}else{r[31]=n[0]^this.T_ap(n[1]^n[2]^n[3]^A.CK[0]|0)|0,r[30]=n[1]^this.T_ap(n[2]^n[3]^r[31]^A.CK[1]|0)|0,r[29]=n[2]^this.T_ap(n[3]^r[31]^r[30]^A.CK[2]|0)|0,r[28]=n[3]^this.T_ap(r[31]^r[30]^r[29]^A.CK[3]|0)|0;for(let o=27;o>=0;o--)r[o]=r[o+4]^this.T_ap(r[o+3]^r[o+2]^r[o+1]^A.CK[31-o]|0)|0}return r}L(t){return t^this.rotateLeft(t,2)^this.rotateLeft(t,10)^this.rotateLeft(t,18)^this.rotateLeft(t,24)|0}T(t){return this.L(this.tau(t))}F0(t,e){return t[0]^this.T(t[1]^t[2]^t[3]^e|0)|0}F1(t,e){return t[1]^this.T(t[2]^t[3]^t[0]^e|0)|0}F2(t,e){return t[2]^this.T(t[3]^t[0]^t[1]^e|0)|0}F3(t,e){return t[3]^this.T(t[0]^t[1]^t[2]^e|0)|0}};s(A,"BLOCK_SIZE",16),s(A,"Sbox",new Uint8Array([214,144,233,254,204,225,61,183,22,182,20,194,40,251,44,5,43,103,154,118,42,190,4,195,170,68,19,38,73,134,6,153,156,66,80,244,145,239,152,122,51,84,11,67,237,207,172,98,228,179,28,169,201,8,232,149,128,223,148,250,117,143,63,166,71,7,167,252,243,115,23,186,131,89,60,25,230,133,79,168,104,107,129,178,113,100,218,139,248,235,15,75,112,86,157,53,30,36,14,94,99,88,209,162,37,34,124,59,1,33,120,135,212,0,70,87,159,211,39,82,76,54,2,231,160,196,200,158,234,191,138,210,64,199,56,181,163,247,242,206,249,97,21,161,224,174,93,164,155,52,26,85,173,147,50,48,245,140,177,227,29,246,226,46,130,102,202,96,192,41,35,171,13,83,78,111,213,219,55,69,222,253,142,47,3,255,106,114,109,108,91,81,141,27,175,146,187,221,188,127,17,217,92,65,31,16,90,216,10,193,49,136,165,205,123,189,45,116,208,18,184,229,180,176,137,105,151,74,12,150,119,126,101,185,241,9,197,110,198,132,24,240,125,236,58,220,77,32,121,238,95,62,215,203,57,72])),s(A,"CK",new Int32Array([462357,472066609,943670861,1415275113,1886879365,2358483617,2830087869,3301692121,3773296373,4228057617,404694573,876298825,1347903077,1819507329,2291111581,2762715833,3234320085,3705924337,4177462797,337322537,808926789,1280531041,1752135293,2223739545,2695343797,3166948049,3638552301,4110090761,269950501,741554753,1213159005,1684763257])),s(A,"FK",new Int32Array([2746333894,1453994832,1736282519,2993693404]));var Z=A;var B=class B{static generateKey(){return new F().generateSeed(B.KEY_SIZE)}static encrypt(t,e){if(e.length!==B.KEY_SIZE)throw new Error("SM4 requires a 128 bit (16 byte) k