UNPKG

sm-js-bc

Version:

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

1 lines 76.4 kB
var Qt=Object.defineProperty;var jt=(u,e,t)=>e in u?Qt(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var s=(u,e,t)=>jt(u,typeof e!="symbol"?e+"":e,t);var C=class u{static bigEndianToInt(e,t){let r=e[t]<<24;return r|=(e[t+1]&255)<<16,r|=(e[t+2]&255)<<8,r|=e[t+3]&255,r}static intToBigEndian(e,t,r){t[r]=e>>>24&255,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=e&255}static bigEndianToLong(e,t){let r=u.bigEndianToInt(e,t),i=u.bigEndianToInt(e,t+4);return BigInt(r>>>0)<<32n|BigInt(i>>>0)}static longToBigEndian(e,t,r){let i=Number(e>>32n&0xffffffffn),n=Number(e&0xffffffffn);u.intToBigEndian(i,t,r),u.intToBigEndian(n,t,r+4)}};var K=class{static concatenate(...e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r}static fill(e,t){e.fill(t)}static areEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}static constantTimeAreEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}static copyOfRange(e,t,r){let i=r-t,n=new Uint8Array(i);return n.set(e.subarray(t,r)),n}};var ot=class{static xorTo(e,t,r,i,n){for(let o=0;o<e;o++)i[n+o]^=t[r+o]}};var Z=class Z{static asUnsignedByteArray(e,t){let r=new Uint8Array(e);for(let i=e-1;i>=0;i--)r[i]=Number(t&0xffn),t>>=8n;return r}static fromUnsignedByteArray(e){let t=0n;for(let r=0;r<e.length;r++)t=t<<8n|BigInt(e[r]);return t}static createRandomBigInteger(e,t){let r=Math.ceil(e/8),i=new Uint8Array(r);t.nextBytes(i);let n=r*8-e;return n>0&&(i[0]&=(1<<8-n)-1),Z.fromUnsignedByteArray(i)}static modOddInverse(e,t){return Z.modInverse(t,e)}static modInverse(e,t){if(e=(e%t+t)%t,e===0n)throw new Error("No modular inverse exists");let[r,i]=[e,t],[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%t+t)%t}static modPow(e,t,r){if(r===1n)return 0n;if(t===0n)return 1n;if(t===1n)return(e%r+r)%r;t<0n&&(e=Z.modInverse(e,r),t=-t);let i=1n;for(e=(e%r+r)%r;t>0n;)t&1n&&(i=i*e%r),e=e*e%r,t>>=1n;return i}static bitLength(e){if(e===0n)return 0;e<0n&&(e=-e);let t=0;for(;e>0n;)t++,e>>=1n;return t}static testBit(e,t){if(t<0)throw new Error("Bit index must be non-negative");return e<0n?(e=-e-1n,(e>>BigInt(t)&1n)===0n):(e>>BigInt(t)&1n)===1n}static legendreSymbol(e,t){if(e=(e%t+t)%t,e===0n)return 0;if(e===1n)return 1;let r=Z.modPow(e,(t-1n)/2n,t);return r===1n?1:r===t-1n?-1:0}static byteLength(e){let t=Z.bitLength(e);return Math.ceil(t/8)}static setBit(e,t){if(t<0)throw new Error("Bit index must be non-negative");return e|1n<<BigInt(t)}static clearBit(e,t){if(t<0)throw new Error("Bit index must be non-negative");return e&~(1n<<BigInt(t))}static flipBit(e,t){if(t<0)throw new Error("Bit index must be non-negative");return e^1n<<BigInt(t)}static getLowestBits(e,t){if(t<0)throw new Error("Bit count must be non-negative");return t===0?0n:e&(1n<<BigInt(t))-1n}};s(Z,"ZERO",0n);var f=Z;var _=class{static numberOfLeadingZeros(e){if(e=e|0,e===0)return 32;let t=1;return e>>>16||(t+=16,e<<=16),e>>>24||(t+=8,e<<=8),e>>>28||(t+=4,e<<=4),e>>>30||(t+=2,e<<=2),t-=e>>>31,t}static bitCount(e){return e=e|0,e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static rotateLeft(e,t){return e=e|0,t=t&31,e<<t|e>>>32-t}static rotateRight(e,t){return e=e|0,t=t&31,e>>>t|e<<32-t}static numberOfTrailingZeros(e){if(e=e|0,e===0)return 32;let t=31,r=e<<16;return r!==0&&(t-=16,e=r),r=e<<8,r!==0&&(t-=8,e=r),r=e<<4,r!==0&&(t-=4,e=r),r=e<<2,r!==0&&(t-=2,e=r),t-(e<<1>>>31)}static highestOneBit(e){return e=e|0,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e-(e>>>1)}static lowestOneBit(e){return e=e|0,e&-e}};var S=class{nextBytes(e){if(typeof crypto<"u"&&crypto.getRandomValues){crypto.getRandomValues(e);return}if(typeof globalThis<"u"&&globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e);return}console.warn("Using Math.random() for random number generation. This is NOT cryptographically secure!");for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}generateSeed(e){let t=new Uint8Array(e);return this.nextBytes(t),t}};var ft=class ft{constructor(e){s(this,"xBuf");s(this,"xBufOff");s(this,"byteCount");e?(this.xBuf=new Uint8Array(e.xBuf),this.xBufOff=e.xBufOff,this.byteCount=e.byteCount):(this.xBuf=new Uint8Array(4),this.xBufOff=0,this.byteCount=0n)}update(e){this.xBuf[this.xBufOff++]=e&255,this.xBufOff===this.xBuf.length&&(this.processWord(this.xBuf,0),this.xBufOff=0),this.byteCount+=1n}updateArray(e,t,r){let i=t,n=Math.max(0,r),o=0;if(this.xBufOff!==0){for(;o<n;)if(this.xBuf[this.xBufOff++]=e[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(e,i+o);for(;o<n;)this.xBuf[this.xBufOff++]=e[i+o++];this.byteCount+=BigInt(n)}finish(){let e=this.byteCount<<3n;for(this.update(128);this.xBufOff!==0;)this.update(0);this.processLength(e),this.processBlock()}reset(){this.byteCount=0n,this.xBufOff=0,this.xBuf.fill(0),this.resetState()}getByteLength(){return ft.BYTE_LENGTH}copyIn(e){this.xBuf=new Uint8Array(e.xBuf),this.xBufOff=e.xBufOff,this.byteCount=e.byteCount}};s(ft,"BYTE_LENGTH",64);var gt=ft;var F=class F extends gt{constructor(t){super(t);s(this,"V",new Array(8));s(this,"X",new Array(68));s(this,"xOff",0);t?this.copyInSM3(t):this.resetState()}getAlgorithmName(){return"SM3"}getDigestSize(){return F.DIGEST_LENGTH}getByteLength(){return F.BLOCK_SIZE}doFinal(t,r){this.finish();for(let i=0;i<8;i++)C.intToBigEndian(this.V[i],t,r+i*4);return this.reset(),F.DIGEST_LENGTH}reset(t){t!==void 0?this.resetFromMemoable(t):(super.reset(),this.resetState())}resetState(){this.V=[...F.IV],this.xOff=0,this.X.fill(0)}processWord(t,r){this.X[this.xOff]=C.bigEndianToInt(t,r),this.xOff++,this.xOff>=16&&this.processBlock()}processLength(t){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(t>>32n),this.X[this.xOff++]=Number(t&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 t=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=t<<12|t>>>20|0,g=m+o+F.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(t,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=t,t=w,c=a,a=l<<19|l>>>13|0,l=o,o=this.P0(I)}for(let h=16;h<64;h++){let m=t<<12|t>>>20|0,g=m+o+F.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(t,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=t,t=w,c=a,a=l<<19|l>>>13|0,l=o,o=this.P0(I)}this.V[0]^=t,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(t,r,i){return t^r^i}FF1(t,r,i){return t&r|t&i|r&i}GG0(t,r,i){return t^r^i}GG1(t,r,i){return t&r|~t&i}P0(t){return t^this.rotateLeft(t,9)^this.rotateLeft(t,17)}P1(t){return t^this.rotateLeft(t,15)^this.rotateLeft(t,23)}rotateLeft(t,r){return t<<r|t>>>32-r|0}copy(){return new F(this)}resetFromMemoable(t){if(!(t instanceof F))throw new Error("Cannot reset from different digest type");super.copyIn(t),this.copyInSM3(t)}copyInSM3(t){this.V=[...t.V],this.X=[...t.X],this.xOff=t.xOff}};s(F,"DIGEST_LENGTH",32),s(F,"BLOCK_SIZE",64),s(F,"IV",[1937774191,1226093241,388252375,3666478592,2842636476,372324522,3817729613,2969243214]),s(F,"T",(()=>{let t=new Array(64);for(let r=0;r<16;r++)t[r]=2043430169<<r|2043430169>>>32-r|0;for(let r=16;r<64;r++){let i=r%32,n=2055708042;t[r]=n<<i|n>>>32-i|0}return t})());var U=F;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 dt=class{isZero(){return this.toBigInteger()===0n}isOne(){return this.toBigInteger()===1n}testBitZero(){return f.testBit(this.toBigInteger(),0)}getEncoded(){let e=Math.ceil(this.getFieldSize()/8);return f.asUnsignedByteArray(e,this.toBigInteger())}equals(e){return this===e?!0:this.toBigInteger()===e.toBigInteger()}},G=class u extends dt{constructor(t,r){super();s(this,"q");s(this,"x");(r<0n||r>=t)&&(r=(r%t+t)%t),this.q=t,this.x=r}toBigInteger(){return this.x}getFieldName(){return"Fp"}getFieldSize(){return f.bitLength(this.q)}getQ(){return this.q}add(t){return new u(this.q,this.modAdd(this.x,t.toBigInteger()))}addOne(){let t=this.x+1n;return t===this.q&&(t=0n),new u(this.q,t)}subtract(t){return new u(this.q,this.modSubtract(this.x,t.toBigInteger()))}multiply(t){return new u(this.q,this.modMult(this.x,t.toBigInteger()))}multiplyMinusProduct(t,r,i){let n=this.x,o=t.toBigInteger(),l=r.toBigInteger(),a=i.toBigInteger(),c=n*o,h=l*a;return new u(this.q,this.modReduce(c-h))}multiplyPlusProduct(t,r,i){let n=this.x,o=t.toBigInteger(),l=r.toBigInteger(),a=i.toBigInteger(),c=n*o,h=l*a;return new u(this.q,this.modReduce(c+h))}divide(t){return new u(this.q,this.modMult(this.x,this.modInverse(t.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(t,r){let i=this.x,n=t.toBigInteger(),o=r.toBigInteger(),l=i*i,a=n*o;return new u(this.q,this.modReduce(l-a))}squarePlusProduct(t,r){let i=this.x,n=t.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 t=(this.q>>2n)+1n,r=new u(this.q,f.modPow(this.x,t,this.q));return this.checkSqrt(r)}if(f.testBit(this.q,2)){let t=f.modPow(this.x,this.q>>3n,this.q),r=this.modMult(t,this.x);if(this.modMult(r,t)===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 t=this.q>>1n;if(f.modPow(this.x,t,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,t,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(t){return t.square().toBigInteger()===this.x?t:null}modAdd(t,r){let i=t+r;return i>=this.q?i-this.q:i}modSubtract(t,r){let i=t-r;return i<0n?i+this.q:i}modMult(t,r){return this.modReduce(t*r)}modReduce(t){return(t%this.q+this.q)%this.q}modInverse(t){return f.modOddInverse(this.q,t)}equals(t){return this===t?!0:t instanceof u?this.q===t.q&&this.x===t.x:!1}hashCode(){return Number(this.q^this.x)}};var It=null;function Wt(u){It=u}function pt(u,e,t,r){if(!It)throw new Error("ECPoint factory not registered");return It(u,e,t,r)}var bt=class{lookupVar(e){return this.lookup(e)}};var St=(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))(St||{}),Ft=class{constructor(e=null,t=null){s(this,"a");s(this,"b");s(this,"order");s(this,"cofactor");s(this,"coord");this.order=e,this.cofactor=t,this.coord=0}getFieldElementEncodingLength(){return Math.ceil(this.getFieldSize()/8)}getAffinePointEncodingLength(e){let t=this.getFieldElementEncodingLength();return e?1+t:1+t*2}validatePoint(e,t){let r=this.createPoint(e,t);if(!r.isValid())throw new Error("Invalid point coordinates");return r}supportsCoordinateSystem(e){return e===0}getCoordinateSystem(){return this.coord}importPoint(e){if(this===e.getCurve())return e;if(e.isInfinity())return this.getInfinity();let t=e.normalize();return this.createPoint(t.getXCoord().toBigInteger(),t.getYCoord().toBigInteger())}normalizeAll(e){this.normalizeAllWithRange(e,0,e.length,null)}normalizeAllWithRange(e,t,r,i){switch(this.checkPoints(e,t,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=e[t+a];c&&(i!==null||!c.isNormalized())&&(n[l]=c.getZCoord(0),o[l++]=t+a)}if(l!==0)for(let a=0;a<l;a++){let c=o[a];e[c]=e[c].normalize()}}precompute(e,t,r){this.checkPoint(e),e.preCompTable||(e.preCompTable=new Map);let i=e.preCompTable.get(t)||null,n=r.precompute(i);return n!==i&&e.preCompTable.set(t,n),n}createCacheSafeLookupTable(e,t,r){let i=this.getFieldElementEncodingLength(),n=new Uint8Array(r*i*2),o=0;for(let a=0;a<r;a++){let c=e[t+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 bt{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(e){if(!e||this!==e.getCurve())throw new Error("'point' must be non-null and on this curve")}checkPoints(e,t=0,r=e.length){if(!e)throw new Error("'points' cannot be null");if(t<0||r<0||t>e.length-r)throw new Error("invalid range specified for points");for(let i=0;i<r;i++){let n=e[t+i];if(n&&this!==n.getCurve())throw new Error("'points' entries must be null or on this curve")}}equals(e){return this===e||e&&this.getFieldSize()===e.getFieldSize()&&this.a.toBigInteger()===e.a.toBigInteger()&&this.b.toBigInteger()===e.b.toBigInteger()}hashCode(){let e=Number(this.a.toBigInteger()&0xffffffffn),t=Number(this.b.toBigInteger()&0xffffffffn);return this.getFieldSize()^_.rotateLeft(e,8)^_.rotateLeft(t,16)}},yt=class extends Ft{constructor(t,r=null,i=null){super(r,i);s(this,"q");this.q=t}getQ(){return this.q}getFieldSize(){return f.bitLength(this.q)}isValidFieldElement(t){return t>=0n&&t<this.q}randomFieldElement(t){let r=this.getQ(),i=this.fromBigInteger(this.implRandomFieldElement(t,r)),n=this.fromBigInteger(this.implRandomFieldElement(t,r));return i.multiply(n)}randomFieldElementMult(t){let r=this.getQ(),i=this.fromBigInteger(this.implRandomFieldElementMult(t,r)),n=this.fromBigInteger(this.implRandomFieldElementMult(t,r));return i.multiply(n)}decompressPoint(t,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()!==(t===1)&&(o=o.negate()),this.createRawPoint(i,o)}implRandomFieldElement(t,r){let i;do i=f.createRandomBigInteger(f.bitLength(r),t);while(i>=r);return i}implRandomFieldElementMult(t,r){let i;do i=f.createRandomBigInteger(f.bitLength(r),t);while(i<=0n||i>=r);return i}},Y=class Y extends yt{constructor(t,r,i,n=null,o=null){super(t,n,o);s(this,"r");s(this,"_infinity",null);this.q=t,this.r=this.calculateResidue(t),this.a=new G(t,r),this.b=new G(t,i),this.coord=Y.FP_DEFAULT_COORDS}get infinity(){return this._infinity||(this._infinity=pt(this,null,null)),this._infinity}set infinity(t){this._infinity=t}static createInternal(t,r,i,n,o,l){let a=Object.create(Y.prototype);return a.q=t,a.r=r,a.a=i,a.b=n,a.order=o,a.cofactor=l,a.coord=Y.FP_DEFAULT_COORDS,a}calculateResidue(t){let r=f.bitLength(t);if(r>=96){let i=t>>BigInt(r-64);if(i===-1n)return 1n;if((i|1n)===-1n)return 2n}return 0n}cloneCurve(){return Y.createInternal(this.q,this.r,this.a,this.b,this.order,this.cofactor)}supportsCoordinateSystem(t){switch(t){case 0:case 1:case 2:case 4:return!0;default:return!1}}getQ(){return this.q}getFieldSize(){return f.bitLength(this.q)}fromBigInteger(t){return new G(this.q,t)}createRawPoint(t,r,i){return pt(this,t,r,i)}createPoint(t,r){return this.createRawPoint(this.fromBigInteger(t),this.fromBigInteger(r))}importPoint(t){if(this!==t.getCurve()&&this.getCoordinateSystem()===2&&!t.isInfinity()){let r=t.getCurve().getCoordinateSystem();if(r===2||r===3||r===4)return this.createRawPoint(this.fromBigInteger(t.getXCoord().toBigInteger()),this.fromBigInteger(t.getYCoord().toBigInteger()),[this.fromBigInteger(t.getZCoord(0).toBigInteger())])}return super.importPoint(t)}getInfinity(){return this._infinity||(this._infinity=pt(this,null,null)),this._infinity}setInfinity(t){this.infinity=t}decodePoint(t){if(t.length===0)throw new Error("Invalid point encoding");let r=t[0],i=this.getFieldElementEncodingLength();switch(r){case 0:if(t.length!==1)throw new Error("Incorrect length for infinity encoding");return this.getInfinity();case 2:case 3:if(t.length!==1+i)throw new Error("Incorrect length for compressed encoding");let n=r&1,o=f.fromUnsignedByteArray(t.subarray(1,1+i));return this.decompressPoint(n,o);case 4:if(t.length!==1+2*i)throw new Error("Incorrect length for uncompressed encoding");let l=f.fromUnsignedByteArray(t.subarray(1,1+i)),a=f.fromUnsignedByteArray(t.subarray(1+i,1+2*i));return this.validatePoint(l,a);case 6:case 7:if(t.length!==1+2*i)throw new Error("Incorrect length for hybrid encoding");let c=f.fromUnsignedByteArray(t.subarray(1,1+i)),h=f.fromUnsignedByteArray(t.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(Y,"FP_DEFAULT_COORDS",4);var st=Y;var H=class H{constructor(e,t,r,i){s(this,"curve");s(this,"x");s(this,"y");s(this,"zs");s(this,"preCompTable",null);this.curve=e,this.x=t,this.y=r,this.zs=i||H.getInitialZCoords(e)}static getInitialZCoords(e){if(!e)return H.EMPTY_ZS;switch(e.getCoordinateSystem()){case 0:case 5:return H.EMPTY_ZS;case 1:case 2:case 6:return[e.fromBigInteger(v.ONE)];case 3:{let r=e.fromBigInteger(v.ONE);return[r,r,r]}case 4:return[e.fromBigInteger(v.ONE),e.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(e){if(e<0||e>=this.zs.length)throw new Error("Invalid z-coordinate index");return this.zs[e]}getZCoords(){return this.zs.length===0?H.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 e=this.getCurveCoordinateSystem();return e===0||e===5||this.isInfinity()||this.zs[0].isOne()}normalize(){if(this.isInfinity())return this;switch(this.getCurveCoordinateSystem()){case 0:case 5:return this;default:{let e=this.getZCoord(0);if(e.isOne())return this;if(!this.curve)throw new Error("Detached points must be in affine coordinates");let t=e.invert();return this.normalizeWithZInv(t)}}}normalizeWithZInv(e){switch(this.getCurveCoordinateSystem()){case 1:case 6:return this.createScaledPoint(e,e);case 2:case 3:case 4:{let t=e.square(),r=t.multiply(e);return this.createScaledPoint(t,r)}default:throw new Error("not a projective coordinate system")}}createScaledPoint(e,t){let r=this.getRawXCoord(),i=this.getRawYCoord();if(!r||!i)throw new Error("Cannot scale infinity point");return this.getCurve().createRawPoint(r.multiply(e),i.multiply(t))}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 e=this.curve?.getOrder();return!0}subtract(e){return e.isInfinity()?this:this.add(e.negate())}timesPow2(e){if(e<0)throw new Error("'e' cannot be negative");let t=this;for(;--e>=0;)t=t.twice();return t}twicePlus(e){return this.twice().add(e)}threeTimes(){return this.twicePlus(this)}multiply(e){return this.simpleMultiply(e)}simpleMultiply(e){if(e===0n)return this.getCurve().getInfinity();if(e<0n)throw new Error("Scalar must be non-negative");let t=this.getCurve().getInfinity(),r=this;for(;e!==0n;)(e&1n)===1n&&(t=t.add(r)),r=r.twice(),e>>=1n;return t}equals(e){if(!e)return!1;let t=this.curve,r=e.curve,i=!t,n=!r,o=this.isInfinity(),l=e.isInfinity();if(o||l)return o&&l&&(i||n||t.equals(r));let a=this,c=e;if(!(i&&n))if(i)c=c.normalize();else if(n)a=a.normalize();else if(t.equals(r)){let h=[this,t.importPoint(c)];t.normalizeAll(h),a=h[0],c=h[1]}else return!1;return a.getXCoord().equals(c.getXCoord())&&a.getYCoord().equals(c.getYCoord())}hashCode(){let e=this.curve,t=e?~e.hashCode():0;if(!this.isInfinity()){let r=this.normalize(),i=Number(r.getXCoord().toBigInteger()&0xffffffffn),n=Number(r.getYCoord().toBigInteger()&0xffffffffn);t^=i*17,t^=n*257}return t|0}toString(){if(this.isInfinity())return"INF";let e=[`(${this.getRawXCoord().toBigInteger()}`,`${this.getRawYCoord().toBigInteger()}`];for(let t of this.zs)e.push(t.toBigInteger().toString());return e.join(",")+")"}getEncoded(e){if(this.isInfinity())return new Uint8Array([0]);let t=this.normalize(),r=t.getXCoord().getEncoded();if(e){let o=new Uint8Array(r.length+1);return o[0]=t.getCompressionYTilde()?3:2,o.set(r,1),o}let i=t.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(H,"EMPTY_ZS",[]);var Ut=H,Et=class extends Ut{constructor(e,t,r,i){super(e,t,r,i)}getCompressionYTilde(){return this.getAffineYCoord().testBitZero()}satisfiesCurveEquation(){let e=this.x,t=this.y;if(!e||!t)return!1;let r=this.getCurve(),i=r.getA(),n=r.getB(),o=t.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=e.square().add(i).multiply(e).add(n);return o.equals(l)}},Ct=class u extends Et{constructor(e,t,r,i){super(e,t,r,i)}detach(){return new u(null,this.getAffineXCoord(),this.getAffineYCoord())}getZCoord(e){return e===1&&this.getCurveCoordinateSystem()===4?this.getJacobianModifiedW():super.getZCoord(e)}getJacobianModifiedW(){let e=this.zs,t=e[1];return t||(t=this.calculateJacobianModifiedW(e[0],null),e[1]=t),t}calculateJacobianModifiedW(e,t){let r=this.getCurve().getA();if(r.isZero()||e.isOne())return r;let n=(t||e.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(e){if(this.isInfinity())return e;if(e.isInfinity())return this;if(this===e)return this.twice();let t=this.getCurve(),r=t.getCoordinateSystem(),i=this.x,n=this.y,o=e.x,l=e.y;switch(r){case 0:{let a=o.subtract(i),c=l.subtract(n);if(a.isZero())return c.isZero()?this.twice():t.getInfinity();let h=c.divide(a),m=h.square().subtract(i).subtract(o),g=h.multiply(i.subtract(m)).subtract(n);return new u(t,m,g)}case 2:case 4:{let a=this.zs[0],c=e.zs[0],h=a.isOne(),m=c.isOne(),g=i,y=o,d=n,b=l;if(!h){let D=a.square();y=y.multiply(D),b=b.multiply(D).multiply(a)}if(!m){let D=c.square();g=g.multiply(D),d=d.multiply(D).multiply(c)}let P=y.subtract(g),w=b.subtract(d);if(P.isZero())return w.isZero()?this.twice():t.getInfinity();let I=P.square(),nt=I.multiply(P),Bt=g.multiply(I),Ht=w.square().subtract(nt).subtract(Bt).subtract(Bt),Jt=Bt.subtract(Ht).multiply(w).subtract(d.multiply(nt)),N=P;h||(N=N.multiply(a)),m||(N=N.multiply(c));let wt;if(r===4){let D=t.getA(),vt;D.isZero()||N.isOne()?vt=D:vt=N.square().square().multiply(D),wt=[N,vt]}else wt=[N];return new u(t,Ht,Jt,wt)}default:throw new Error("unsupported coordinate system")}}twice(){if(this.isInfinity())return this;let e=this.getCurve(),t=this.y;if(t.isZero())return e.getInfinity();let r=e.getCoordinateSystem(),i=this.x;switch(r){case 0:{let n=i.square(),o=n.add(n).add(n).add(e.getA()).divide(t.add(t)),l=o.square().subtract(i).subtract(i),a=o.multiply(i.subtract(l)).subtract(t);return new u(e,l,a)}case 2:{let n=this.zs[0],o=n.isOne(),l=t.square(),a=l.square(),c=e.getA(),h=i.square().multiply(e.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(e.fromBigInteger(v.FOUR));let g=h.square().subtract(m).subtract(m),y;o?y=t.add(t):y=t.multiply(n).add(t.multiply(n));let d=h.multiply(m.subtract(g)).subtract(a.multiply(e.fromBigInteger(v.EIGHT)));return new u(e,g,d,[y])}case 4:return this.twiceJacobianModified(!0);default:throw new Error("unsupported coordinate system")}}twiceJacobianModified(e){let t=this.getCurve(),r=this.x,i=this.y,n=this.zs[0],o=this.getJacobianModifiedW(),a=r.square().multiply(t.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=e?d.multiply(o).add(d.multiply(o)):t.getA(),w=n.isOne()?c:c.multiply(n);return new u(t,g,b,[w,P])}negate(){if(this.isInfinity())return this;let e=this.getCurve();return e.getCoordinateSystem()!==0?new u(e,this.x,this.y.negate(),this.zs):new u(e,this.x,this.y.negate())}};Wt((u,e,t,r)=>new Ct(u,e,t,r));var tt=class{constructor(){s(this,"_offset",null);s(this,"_lookupTable",null);s(this,"_width",-1)}getLookupTable(){return this._lookupTable}setLookupTable(e){this._lookupTable=e}getOffset(){return this._offset}setOffset(e){this._offset=e}getWidth(){return this._width}setWidth(e){this._width=e}};var W=class W{static getCombSize(e){let t=e.getOrder();return t===null?e.getFieldSize()+1:this.bitLength(t)}static bitLength(e){return e===0n?0:e.toString(2).length}static getFixedPointPreCompInfo(e){return e instanceof tt?e:null}static precompute(e){let t=e.getCurve();return t.precompute(e,W.PRECOMP_NAME,{precompute(r){let i=r instanceof tt?r:null,n=W.getCombSize(t),o=n>250?6:5,l=1<<o;if(W.checkExisting(i,l))return i;let a=Math.floor((n+o-1)/o),c=new Array(o+1);c[0]=e;for(let g=1;g<o;g++)c[g]=c[g-1].timesPow2(a);c[o]=c[0].add(c[1].negate()),t.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)}t.normalizeAll(h);let m=new tt;return m.setLookupTable(t.createCacheSafeLookupTable(h,0,h.length)),m.setOffset(c[o]),m.setWidth(o),m}})}static checkExisting(e,t){return e!==null&&W.checkTable(e.getLookupTable(),t)}static checkTable(e,t){return e!==null&&e.getSize()>=t}};s(W,"PRECOMP_NAME","bc_fixed_point");var at=W;var xt=class{static fromBigInteger(e,t){if(t<0n)throw new Error("Value cannot be negative");if(t===0n){let n=e+31>>>5;return new Array(n).fill(0)}let r=e+31>>>5,i=new Array(r).fill(0);for(let n=0;n<r;n++)i[n]=Number(t&0xFFFFFFFFn),t=t>>32n;return i}static toBigInteger(e){let t=0n;for(let r=e.length-1;r>=0;r--)t=t<<32n|BigInt(e[r]>>>0);return t}static getBit(e,t){let r=t>>>5,i=t&31;return r>=e.length?0:e[r]>>>i&1}};var lt=class{multiply(e,t){if(t===0n||e.isInfinity())return e.getCurve().getInfinity();let r=t<0n?-1:1,i=t<0n?-t:t,n=this.multiplyPositive(e,i),o=r>0?n:n.negate();return this.checkResult(o)}checkResult(e){return e.isInfinity()||e.isValid()?e:e.getCurve().getInfinity()}},T=class extends lt{multiplyPositive(e,t){let r=e.getCurve(),i=at.getCombSize(r);if((t===0n?0:t.toString(2).length)>i)throw new Error("fixed-point comb doesn't support scalars larger than the curve order");let o=at.precompute(e),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=xt.fromBigInteger(m,t),y=m-1;for(let b=0;b<c;b++){let P=0;for(let I=y-b;I>=0;I-=c){let nt=g[I>>>5]>>>(I&31);P^=nt>>>1,P<<=1,P^=nt}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)}},kt=class extends lt{multiplyPositive(e,t){let r=e.getCurve().getInfinity(),i=e;for(;t!==0n;)(t&1n)===1n&&(r=r.add(i)),i=i.twice(),t>>=1n;return r}};var ct=class{constructor(e){s(this,"privateKey");this.privateKey=e}isPrivate(){return this.privateKey}};var ht=class u{constructor(e,t,r,i,n){s(this,"curve");s(this,"G");s(this,"n");s(this,"h");s(this,"seed");this.curve=e,this.G=t,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(e){return e instanceof u?this.curve.equals(e.curve)&&this.G.equals(e.G)&&this.n===e.n&&this.h===e.h:!1}hashCode(){let e=this.curve.hashCode();return e^=this.G.hashCode(),e^=Number(this.n&0xffffffffn),e^=Number(this.h&0xffffffffn),e}};var J=class extends ct{constructor(t,r){super(t);s(this,"parameters");this.parameters=r}getParameters(){return this.parameters}};var M=class extends J{constructor(t,r){super(!1,r);s(this,"Q");this.Q=t}getQ(){return this.Q}};var R=class extends J{constructor(t,r){super(!0,r);s(this,"d");this.d=t}getD(){return this.d}};var q=class{constructor(e,t){s(this,"parameters");s(this,"random");this.parameters=e,this.random=t??new S}getParameters(){return this.parameters}getRandom(){return this.random}};var V=class{constructor(e,t){s(this,"parameters");s(this,"id");this.parameters=e,this.id=new Uint8Array(t)}getParameters(){return this.parameters}getID(){return new Uint8Array(this.id)}};var Kt=class{constructor(){s(this,"digest");this.digest=new U}deriveKey(e,t){let r=this.digest.getDigestSize(),i=new Uint8Array(t),n=1,o=0,l=new Uint8Array(r);for(;o<t;){this.digest.reset(),this.digest.updateArray(e,0,e.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(t-o,r);i.set(l.subarray(0,c),o),o+=c,n++}return i}static isZero(e){for(let t=0;t<e.length;t++)if(e[t]!==0)return!1;return!0}};var Q=class extends Error{constructor(e){super(e),this.name="CryptoException"}};var z=class extends Q{constructor(e){super(e),this.name="InvalidCipherTextException"}};var x=class extends Q{constructor(e){super(e),this.name="DataLengthException"}};var zt=(t=>(t.C1C2C3="C1C2C3",t.C1C3C2="C1C3C2",t))(zt||{}),j=class{constructor(e,t){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);e instanceof U?(this.digest=e,this.mode=t??"C1C2C3"):(this.digest=new U,this.mode=e??"C1C2C3")}init(e,t){if(this.forEncryption=e,e){let r=t;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=t,this.ecParams=this.ecKey.getParameters();this.curveLength=Math.floor((this.ecParams.getCurve().getFieldSize()+7)/8)}processBlock(e,t,r){if(t+r>e.length||r===0)throw new x("input buffer too short");return this.forEncryption?this.encrypt(e,t,r):this.decrypt(e,t,r)}getOutputSize(e){return 1+2*this.curveLength+e+this.digest.getDigestSize()}createBasePointMultiplier(){return new T}encrypt(e,t,r){let i=new Uint8Array(r);i.set(e.subarray(t,t+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,e,t));let a=new Uint8Array(this.digest.getDigestSize());switch(this.addFieldElement(this.digest,l.getAffineXCoord()),this.digest.updateArray(e,t,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(e,t,r){let i=new Uint8Array(this.curveLength*2+1);i.set(e.subarray(t,t+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(e.subarray(t+i.length+a,t+r)):c.set(e.subarray(t+i.length,t+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]^e[t+i.length+g];else for(let g=0;g<h.length;g++)m|=h[g]^e[t+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(e,t,r){for(let i=0;i<e.length;i++)if(e[i]!==t[r+i])return!1;return!0}kdf(e,t,r){let i=e.getDigestSize(),n=new Uint8Array(Math.max(4,i)),o=0,l=null,a=null;e&&typeof e.copy=="function"&&(this.addFieldElement(e,t.getAffineXCoord()),this.addFieldElement(e,t.getAffineYCoord()),l=e,a=l.copy());let c=0;for(;o<r.length;){l&&a?l.resetFromMemoable(a):(this.addFieldElement(e,t.getAffineXCoord()),this.addFieldElement(e,t.getAffineYCoord())),c++,n[0]=c>>>24&255,n[1]=c>>>16&255,n[2]=c>>>8&255,n[3]=c&255,e.updateArray(n,0,4),e.doFinal(n,0);let h=Math.min(i,r.length-o);ot.xorTo(h,n,0,r,o),o+=h}}nextK(){let e=this.ecParams.getN(),t=this.getBitLength(e),r;do r=f.createRandomBigInteger(t,this.random);while(r===0n||r>=e);return r}getBitLength(e){return f.bitLength(e)}addFieldElement(e,t){let r=f.asUnsignedByteArray(this.curveLength,t.toBigInteger());e.updateArray(r,0,r.length)}};s(j,"Mode",zt);var Pt=class Pt{encode(e,t,r){if(t<=0n||t>=e)throw new Error("r component out of range");if(r<=0n||r>=e)throw new Error("s component out of range");let i=this.encodeInteger(t),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(e,t){let r=0;if(t[r]!==48)throw new Error("Invalid DER encoding: expected SEQUENCE tag");r++;let[i,n]=this.parseLength(t,r);if(r+=n,r+i!==t.length)throw new Error("Invalid DER encoding: incorrect sequence length");let[o,l]=this.parseInteger(t,r);r+=l;let[a,c]=this.parseInteger(t,r);if(r+=c,r!==t.length)throw new Error("Invalid DER encoding: extra bytes");if(o<=0n||o>=e)throw new Error("Invalid signature: r component out of range");if(a<=0n||a>=e)throw new Error("Invalid signature: s component out of range");return[o,a]}encodeInteger(e){if(e<=0n)throw new Error("Integer must be positive");let t=this.bigIntToBytes(e);if((t[0]&128)!==0){let o=new Uint8Array(t.length+1);o[0]=0,o.set(t,1),t=o}let r=this.lengthBytesCount(t.length),i=new Uint8Array(1+r+t.length),n=0;return i[n++]=2,n+=this.encodeLength(i,n,t.length),i.set(t,n),i}parseInteger(e,t){if(t>=e.length)throw new Error("Unexpected end of DER encoding");if(e[t]!==2)throw new Error("Invalid DER encoding: expected INTEGER tag");t++;let[r,i]=this.parseLength(e,t);if(t+=i,t+r>e.length)throw new Error("Invalid DER encoding: integer extends beyond available data");if(r>1&&e[t]===0&&(e[t+1]&128)===0)throw new Error("Invalid DER encoding: non-minimal integer");let n=e.slice(t,t+r),o=this.bytesToBigInt(n);if(o<=0n)throw new Error("Invalid DER encoding: non-positive integer");return[o,1+i+r]}lengthBytesCount(e){if(e<128)return 1;{let t=1,r=e;for(;r>0;)t++,r=r>>>8;return t}}encodeLength(e,t,r){if(r<128)return e[t]=r,1;{let i=0,n=r;for(;n>0;)i++,n=n>>>8;e[t]=128|i;let o=t+1;for(let l=i-1;l>=0;l--)e[o++]=r>>>l*8&255;return 1+i}}parseLength(e,t){if(t>=e.length)throw new Error("Unexpected end of DER encoding");let r=e[t];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(t+1+i>e.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|e[t+1+o];if(n<128)throw new Error("Invalid DER encoding: non-minimal length");return[n,1+i]}}bigIntToBytes(e){if(e===0n)return new Uint8Array([0]);let t=[];for(;e>0n;)t.unshift(Number(e&0xFFn)),e=e>>8n;return new Uint8Array(t)}bytesToBigInt(e){let t=0n;for(let r=0;r<e.length;r++)t=t<<8n|BigInt(e[r]);return t}};s(Pt,"INSTANCE",new Pt);var ut=Pt;var At=class{constructor(){s(this,"q",null);s(this,"random",null)}init(e,t){if(e<=1n)throw new Error("Order must be greater than 1");this.q=e,this.random=t}nextK(){if(!this.q||!this.random)throw new Error("Calculator not initialized");let e=this.getBitLength(this.q),t;do t=f.createRandomBigInteger(e-1,this.random),t===0n&&(t=1n);while(t>=this.q);return t}isDeterministic(){return!1}getBitLength(e){if(e===0n)return 0;let t=0,r=e;for(;r>0n;)t++,r=r>>1n;return t}};var et=class et{constructor(e=new U,t=new At){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=e,this.dsaKCalculator=t,this.userID=et.DEFAULT_USER_ID}getAlgorithmName(){return"SM2"}init(e,t){this.forSigning=e;let r,i=null;if(t instanceof V){let n=t;this.userID=n.getID();let o=n.getParameters();if(o instanceof q){let l=o;i=l.getRandom(),r=l.getParameters()}else r=o}else if(t instanceof q){let n=t;i=n.getRandom(),r=n.getParameters(),this.userID=et.DEFAULT_USER_ID}else r=t,this.userID=et.DEFAULT_USER_ID;if(this.keyParameters=r,this.ecParams=r.getParameters(),e){if(!(r instanceof R))throw new Error("Signing requires ECPrivateKeyParameters");this.kCalculator=this.dsaKCalculator;let n=i||new S;this.kCalculator.init(this.ecParams.getN(),n),this.publicKey=this.calculatePublicKey(r)}else{if(!(r instanceof M))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(e,t,r){typeof e=="number"?this.digest.update(e):this.digest.updateArray(e,t,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 e=this.keyParameters,t=this.ecParams.getN(),r=this.ecParams.getG(),i=e.getD(),n=new Uint8Array(this.digest.getDigestSize());this.digest.doFinal(n,0);let o=this.hashToInteger(n,t),l=0n,a=0n;do{let c=this.kCalculator.nextK(),m=r.multiply(c).normalize().getAffineXCoord().toBigInteger();if(l=(o+m)%t,l===0n||(l+c)%t===0n)continue;a=this.modInverse(1n+i,t)*(c-l*i%t)%t,a<0n&&(a+=t)}while(a===0n);return this.digest.reset(),this.z&&this.digest.updateArray(this.z,0,this.z.length),ut.INSTANCE.encode(t,l,a)}verifySignature(e){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 t=this.ecParams.getN(),r=this.ecParams.getG(),i=this.publicKey.getQ(),[n,o]=ut.INSTANCE.decode(t,e);if(n<=0n||n>=t||o<=0n||o>=t)return!1;let l=new Uint8Array(this.digest.getDigestSize());this.digest.doFinal(l,0);let a=this.hashToInteger(l,t),c=(n+o)%t;if(c===0n)return!1;let h=r.multiply(o),m=i.multiply(c),y=h.add(m).normalize().getAffineXCoord().toBigInteger(),b=(a+y)%t===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 T}calculatePublicKey(e){let t=e.getD(),r=e.getParameters(),i=r.getG().multiply(t);return new M(i,r)}calculateZ(e,t){let r=new U,i=e.length*8;r.update(i>>>8&255),r.update(i&255),r.updateArray(e,0,e.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=t.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(e,t){let r=0n;for(let i=0;i<t.length;i++)r=r<<8n|BigInt(t[i]);return r%e}hashToInteger(e,t){return this.calculateE(t,e)}modInverse(e,t){e<0n&&(e=(e%t+t)%t);let[r,i]=[e,t],[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+=t),n}};s(et,"DEFAULT_USER_ID",new TextEncoder().encode("1234567812345678"));var rt=et;var E=class E{static getParameters(){if(!E.domainParams){let e=new st(E.p,E.a,E.b,E.n,E.h),t=e.createPoint(E.Gx,E.Gy);E.domainParams=new ht(e,t,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(e){return!(e.isInfinity()||!e.isValid()||!e.multiply(E.n).isInfinity())}static validatePrivateKey(e){return e>0n&&e<E.n}static generateKeyPair(){let e=new S,t;do{let o=e.generateSeed(32);t=BigInt("0x"+Array.from(o).map(l=>l.toString(16).padStart(2,"0")).join(""))}while(t===0n||t>=E.n);let i=E.getG().multiply(t);if(i.isInfinity()||!E.validatePublicKey(i))throw new Error("Generated invalid public key");let n=i.normalize();return{privateKey:t,publicKey:{x:n.getAffineXCoord().toBigInteger(),y:n.getAffineYCoord().toBigInteger()}}}static encrypt(e,t,r){let i=typeof e=="string"?new TextEncoder().encode(e):e,n,o;if(typeof t=="object"&&t!==null)n=t.x,o=t.y;else if(typeof t=="bigint"&&typeof r=="bigint")n=t,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 M(a,c),m=new j;return m.init(!0,new q(h,new S)),m.processBlock(i,0,i.length)}static decrypt(e,t){let r=E.getParameters(),i=new R(t,r),n=new j;return n.init(!1,i),n.processBlock(e,0,e.length)}static sign(e,t){let r=typeof e=="string"?new TextEncoder().encode(e):e,i=E.getParameters(),n=new R(t,i),o=new rt;return o.init(!0,new q(n,new S)),o.update(r,0,r.length),o.generateSignature()}static verify(e,t,r,i){let n=typeof e=="string"?new TextEncoder().encode(e):e,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 M(c,h),g=new rt;return g.init(!1,m),g.update(n,0,n.length),g.verifySignature(t)}};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 Lt=E;var O=class{constructor(e){s(this,"key");this.key=new Uint8Array(e)}getKey(){return this.key}};var A=class A{constructor(){s(this,"X",new Int32Array(4));s(this,"rk",null)}init(e,t){if(!(t instanceof O))throw new Error(`invalid parameter passed to SM4 init - ${t.constructor.name}`);let r=t.getKey();if(r.length!==16)throw new Error("SM4 requires a 128 bit key");this.rk=this.expandKey(e,r)}getAlgorithmName(){return"SM4"}getBlockSize(){return A.BLOCK_SIZE}processBlock(e,t,r,i){if(this.rk===null)throw new Error("SM4 not initialised");if(t+A.BLOCK_SIZE>e.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(e,t),this.X[1]=C.bigEndianToInt(e,t+4),this.X[2]=C.bigEndianToInt(e,t+8),this.X[3]=C.bigEndianToInt(e,t+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(e,t){return e<<t|e>>>32-t|0}tau(e){let t=(A.Sbox[e>>>24&255]&255)<<24,r=(A.Sbox[e>>>16&255]&255)<<16,i=(A.Sbox[e>>>8&255]&255)<<8,n=A.Sbox[e&255]&255;return t|r|i|n|0}L_ap(e){return e^this.rotateLeft(e,13)^this.rotateLeft(e,23)|0}T_ap(e){return this.L_ap(this.tau(e))}expandKey(e,t){let r=new Int32Array(32),i=new Int32Array(4);i[0]=C.bigEndianToInt(t,0),i[1]=C.bigEndianToInt(t,4),i[2]=C.bigEndianToInt(t,8),i[3]=C.bigEndianToInt(t,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,e){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(e){return e^this.rotateLeft(e,2)^this.rotateLeft(e,10)^this.rotateLeft(e,18)^this.rotateLeft(e,24)|0}T(e){return this.L(this.tau(e))}F0(e,t){return e[0]^this.T(e[1]^e[2]^e[3]^t|0)|0}F1(e,t){return e[1]^this.T(e[2]^e[3]^e[0]^t|0)|0}F2(e,t){return e[2]^this.T(e[3]^e[0]^e[1]^t|0)|0}F3(e,t){return e[3]^this.T(e[0]^e[1]^e[2]^t|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 X=A;var B=class B{static generateKey(){return new S().generateSeed(B.KEY_SIZE)}static encrypt(e,t){if(t.length!==B.KEY_SIZE)throw new Error("SM4 requires a 128 bit (16 byte) key");let r=B.pkcs7Padding(e,B.BLOCK_SIZE),i=new X;i.init(!0,new O(t));let n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=B.BLOCK_SIZE)i.processBlock(r,o,n,o);return n}static decrypt(e,t){if(t.length!==B.KEY_SIZE)throw new Error("SM4 requires a 128 bit (16 byte) key");if(e.length%B.BLOCK_SIZE!==0)throw new Error("Ciphertext length must be a multiple of block size (16 bytes)");let r=new X;r.init(!1,new O(t));let i=new Uint8Array(e.length);for(let n=0;n<e.length;n+=B.BLOCK_SIZE)r.processBlock(e,n,i,n);return B.pkcs7Unpadding(i)}static encryptBlock(e,t){if(e.length!==B.BLOCK_SIZE)throw new Error("Block must be exactly 16 bytes");if(t.length!==B.KEY_SIZE)throw new Error("SM4 requires a 128 bit (16 byte) key");let r=new X;r.init(!0,new O(t));let i=new Uint8Array(B.BLOCK_SIZE);return r.processBlock(e,0,i,0),i}static decryptBlock(e,t){if(e.length!==B.BLOCK_SIZE)throw new Error("Block must be exactly 16 bytes");if(t.length!==B.KEY_SIZE)throw new Error("SM4 requires a 128 bit (16 byte) key");let r=new X;r.init(!1,new O(t));let i=new Uint8Array(B.BLOCK_SIZE);return r.processBlock(e,0,i,0),i}static pkcs7Padding(e,t){let r=t-e.length%t,i=new Uint8Array(e.length+r);i.set(e);for(let n=e.length;n<i.length;n++)i[n]=r;return i}static pkcs7Unpadding(e){if(e.length===0)throw new Error("Cannot unpad empty data");let t=e[e.length-1];if(t<1||t>B.BLOCK_SIZE)throw new Error("Invalid padding");for(let r=e.length-t;r<e.length;r++)if(e[r]!==t)throw new Error("Invalid padding");return e.slice(0,e.length-t)}};s