var BigInteger=require("../libs/jsbn"),crypt=require("crypto");module.exports={isEncryption:!1,isSignature:!0};var DEFAULT_HASH_FUNCTION="sha1",DEFAULT_SALT_LENGTH=20;module.exports.makeScheme=function(e,t){var i=require("./schemes").pkcs1_oaep;function n(e,t){this.key=e,this.options=t}return n.prototype.sign=function(e){var t=crypt.createHash(this.options.signingSchemeOptions.hash||DEFAULT_HASH_FUNCTION);t.update(e);var i=this.emsa_pss_encode(t.digest(),this.key.keySize-1);return this.key.$doPrivate(new BigInteger(i)).toBuffer(this.key.encryptedDataLength)},n.prototype.verify=function(e,t,i){i&&(t=Buffer.from(t,i)),t=new BigInteger(t);var n=Math.ceil((this.key.keySize-1)/8),s=this.key.$doPublic(t).toBuffer(n),r=crypt.createHash(this.options.signingSchemeOptions.hash||DEFAULT_HASH_FUNCTION);return r.update(e),this.emsa_pss_verify(r.digest(),s,this.key.keySize-1)},n.prototype.emsa_pss_encode=function(e,t){var n=this.options.signingSchemeOptions.hash||DEFAULT_HASH_FUNCTION,s=this.options.signingSchemeOptions.mgf||i.eme_oaep_mgf1,r=this.options.signingSchemeOptions.saltLength||DEFAULT_SALT_LENGTH,o=i.digestLength[n],h=Math.ceil(t/8);if(h<o+r+2)throw new Error("Output length passed to emBits("+t+") is too small for the options specified("+n+", "+r+"). To fix this issue increase the value of emBits. (minimum size: "+(8*o+8*r+9)+")");var a=crypt.randomBytes(r),g=Buffer.alloc(8+o+r);g.fill(0,0,8),e.copy(g,8),a.copy(g,8+e.length);var p=crypt.createHash(n);p.update(g),p=p.digest();var c=Buffer.alloc(h-a.length-o-2);c.fill(0);var l=Buffer.alloc(c.length+1+a.length);c.copy(l),l[c.length]=1,a.copy(l,c.length+1);for(var f=s(p,l.length,n),u=Buffer.alloc(l.length),y=0;y<f.length;y++)u[y]=l[y]^f[y];var m=8*h-t,_=255^255>>8-m<<8-m;u[0]=u[0]&_;var v=Buffer.alloc(u.length+p.length+1);return u.copy(v,0),p.copy(v,u.length),v[v.length-1]=188,v},n.prototype.emsa_pss_verify=function(e,t,n){var s=this.options.signingSchemeOptions.hash||DEFAULT_HASH_FUNCTION,r=this.options.signingSchemeOptions.mgf||i.eme_oaep_mgf1,o=this.options.signingSchemeOptions.saltLength||DEFAULT_SALT_LENGTH,h=i.digestLength[s],a=Math.ceil(n/8);if(a<h+o+2||188!=t[t.length-1])return!1;var g=Buffer.alloc(a-h-1);t.copy(g,0,0,a-h-1);for(var p=0,c=0,l=8*a-n;c<l;c++)p|=1<<7-c;if(0!=(g[0]&p))return!1;var f=t.slice(a-h-1,a-1),u=r(f,g.length,s);for(c=0;c<g.length;c++)g[c]^=u[c];for(p=255^255>>8-(l=8*a-n)<<8-l,g[0]=g[0]&p,c=0;0===g[c]&&c<g.length;c++);if(1!=g[c])return!1;var y=g.slice(g.length-o),m=Buffer.alloc(8+h+o);m.fill(0,0,8),e.copy(m,8),y.copy(m,8+e.length);var _=crypt.createHash(s);return _.update(m),_=_.digest(),f.toString("hex")===_.toString("hex")},new n(e,t)};