var forge=require("./forge");require("./util"),require("./random"),require("./sha1");var pkcs1=module.exports=forge.pkcs1=forge.pkcs1||{};function rsa_mgf1(e,t,r){r||(r=forge.md.sha1.create());for(var g="",s=Math.ceil(t/r.digestLength),i=0;i<s;++i){var n=String.fromCharCode(i>>24&255,i>>16&255,i>>8&255,255&i);r.start(),r.update(e+n),g+=r.digest().getBytes()}return g.substring(0,t)}pkcs1.encode_rsa_oaep=function(e,t,r){"string"==typeof r?(g=r,s=arguments[3]||void 0,i=arguments[4]||void 0):r&&(g=r.label||void 0,s=r.seed||void 0,i=r.md||void 0,r.mgf1&&r.mgf1.md&&(n=r.mgf1.md)),i?i.start():i=forge.md.sha1.create(),n||(n=i);var g,s,i,n,h=Math.ceil(e.n.bitLength()/8),o=h-2*i.digestLength-2;if(t.length>o){var d=Error("RSAES-OAEP input message length is too long.");throw d.length=t.length,d.maxLength=o,d}g||(g=""),i.update(g,"raw");for(var a=i.digest(),f="",l=o-t.length,m=0;m<l;m++)f+="\0";var u=a.getBytes()+f+"\x01"+t;if(s){if(s.length!==i.digestLength){var d=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw d.seedLength=s.length,d.digestLength=i.digestLength,d}}else s=forge.random.getBytes(i.digestLength);var v=rsa_mgf1(s,h-i.digestLength-1,n),c=forge.util.xorBytes(u,v,u.length),L=rsa_mgf1(c,i.digestLength,n);return"\0"+forge.util.xorBytes(s,L,s.length)+c},pkcs1.decode_rsa_oaep=function(e,t,r){"string"==typeof r?(g=r,s=arguments[3]||void 0):r&&(g=r.label||void 0,s=r.md||void 0,r.mgf1&&r.mgf1.md&&(i=r.mgf1.md));var g,s,i,n=Math.ceil(e.n.bitLength()/8);if(t.length!==n){var h=Error("RSAES-OAEP encoded message length is invalid.");throw h.length=t.length,h.expectedLength=n,h}if(void 0===s?s=forge.md.sha1.create():s.start(),i||(i=s),n<2*s.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");g||(g=""),s.update(g,"raw");for(var o=s.digest().getBytes(),d=t.charAt(0),a=t.substring(1,s.digestLength+1),f=t.substring(1+s.digestLength),l=rsa_mgf1(f,s.digestLength,i),m=rsa_mgf1(forge.util.xorBytes(a,l,a.length),n-s.digestLength-1,i),u=forge.util.xorBytes(f,m,f.length),v=u.substring(0,s.digestLength),h="\0"!==d,c=0;c<s.digestLength;++c)h|=o.charAt(c)!==v.charAt(c);for(var L=1,p=s.digestLength,A=s.digestLength;A<u.length;A++){var E=u.charCodeAt(A),y=1&E^1;h|=E&65534*!!L,L&=y,p+=L}if(h||1!==u.charCodeAt(p))throw Error("Invalid RSAES-OAEP padding.");return u.substring(p+1)};