var ber=require("asn1").Ber,_=require("../utils")._,utils=require("../utils");const PRIVATE_OPENING_BOUNDARY="-----BEGIN RSA PRIVATE KEY-----",PRIVATE_CLOSING_BOUNDARY="-----END RSA PRIVATE KEY-----",PUBLIC_OPENING_BOUNDARY="-----BEGIN RSA PUBLIC KEY-----",PUBLIC_CLOSING_BOUNDARY="-----END RSA PUBLIC KEY-----";module.exports={privateExport:function(r,e){e=e||{};var t=r.n.toBuffer(),f=r.d.toBuffer(),n=r.p.toBuffer(),i=r.q.toBuffer(),u=r.dmp1.toBuffer(),B=r.dmq1.toBuffer(),o=r.coeff.toBuffer(),s=t.length+f.length+n.length+i.length+u.length+B.length+o.length+512,I=new ber.Writer({size:s});return I.startSequence(),I.writeInt(0),I.writeBuffer(t,2),I.writeInt(r.e),I.writeBuffer(f,2),I.writeBuffer(n,2),I.writeBuffer(i,2),I.writeBuffer(u,2),I.writeBuffer(B,2),I.writeBuffer(o,2),I.endSequence(),"der"===e.type?I.buffer:PRIVATE_OPENING_BOUNDARY+"\n"+utils.linebrk(I.buffer.toString("base64"),64)+"\n"+PRIVATE_CLOSING_BOUNDARY},privateImport:function(r,e,t){var f;if("der"!==(t=t||{}).type){if(Buffer.isBuffer(e)&&(e=e.toString("utf8")),!_.isString(e))throw Error("Unsupported key format");var n=utils.trimSurroundingText(e,PRIVATE_OPENING_BOUNDARY,PRIVATE_CLOSING_BOUNDARY).replace(/\s+|\n\r|\n|\r$/gm,"");f=Buffer.from(n,"base64")}else{if(!Buffer.isBuffer(e))throw Error("Unsupported key format");f=e}var i=new ber.Reader(f);i.readSequence(),i.readString(2,!0),r.setPrivate(i.readString(2,!0),i.readString(2,!0),i.readString(2,!0),i.readString(2,!0),i.readString(2,!0),i.readString(2,!0),i.readString(2,!0),i.readString(2,!0))},publicExport:function(r,e){e=e||{};var t=r.n.toBuffer(),f=t.length+512,n=new ber.Writer({size:f});return n.startSequence(),n.writeBuffer(t,2),n.writeInt(r.e),n.endSequence(),"der"===e.type?n.buffer:PUBLIC_OPENING_BOUNDARY+"\n"+utils.linebrk(n.buffer.toString("base64"),64)+"\n"+PUBLIC_CLOSING_BOUNDARY},publicImport:function(r,e,t){var f;if("der"!==(t=t||{}).type){if(Buffer.isBuffer(e)&&(e=e.toString("utf8")),_.isString(e)){var n=utils.trimSurroundingText(e,PUBLIC_OPENING_BOUNDARY,PUBLIC_CLOSING_BOUNDARY).replace(/\s+|\n\r|\n|\r$/gm,"");f=Buffer.from(n,"base64")}}else{if(!Buffer.isBuffer(e))throw Error("Unsupported key format");f=e}var i=new ber.Reader(f);i.readSequence(),r.setPublic(i.readString(2,!0),i.readString(2,!0))},autoImport:function(r,e){return/^[\S\s]*-----BEGIN RSA PRIVATE KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END RSA PRIVATE KEY-----[\S\s]*$/g.test(e)?(module.exports.privateImport(r,e),!0):!!/^[\S\s]*-----BEGIN RSA PUBLIC KEY-----\s*(?=(([A-Za-z0-9+/=]+\s*)+))\1-----END RSA PUBLIC KEY-----[\S\s]*$/g.test(e)&&(module.exports.publicImport(r,e),!0)}};