var forge=require("./forge");require("./aes"),require("./hmac"),require("./md5"),require("./sha1"),require("./util");var ssh=module.exports=forge.ssh=forge.ssh||{};function _addBigIntegerToBuffer(e,r){var t=r.toString(16);t[0]>="8"&&(t="00"+t);var n=forge.util.hexToBytes(t);e.putInt32(n.length),e.putBytes(n)}function _addStringToBuffer(e,r){e.putInt32(r.length),e.putString(r)}function _sha1(){for(var e=forge.md.sha1.create(),r=arguments.length,t=0;t<r;++t)e.update(arguments[t]);return e.digest()}ssh.privateKeyToPutty=function(e,r,t){t=t||"";var n,f="ssh-rsa",a=""===(r=r||"")?"none":"aes256-cbc",i="PuTTY-User-Key-File-2: "+f+"\r\n";i+="Encryption: "+a+"\r\n",i+="Comment: "+t+"\r\n";var u=forge.util.createBuffer();_addStringToBuffer(u,f),_addBigIntegerToBuffer(u,e.e),_addBigIntegerToBuffer(u,e.n);var o=forge.util.encode64(u.bytes(),64),g=Math.floor(o.length/66)+1;i+="Public-Lines: "+g+"\r\n",i+=o;var d=forge.util.createBuffer();if(_addBigIntegerToBuffer(d,e.d),_addBigIntegerToBuffer(d,e.p),_addBigIntegerToBuffer(d,e.q),_addBigIntegerToBuffer(d,e.qInv),r){var s=d.length()+16-1;s-=s%16;var B=_sha1(d.bytes());B.truncate(B.length()-s+d.length()),d.putBuffer(B);var c=forge.util.createBuffer();c.putBuffer(_sha1("\0\0\0\0",r)),c.putBuffer(_sha1("\0\0\0\x01",r));var h=forge.aes.createEncryptionCipher(c.truncate(8),"CBC");h.start(forge.util.createBuffer().fillWithByte(0,16)),h.update(d.copy()),h.finish();var l=h.output;l.truncate(16),n=forge.util.encode64(l.bytes(),64)}else n=forge.util.encode64(d.bytes(),64);i+="\r\nPrivate-Lines: "+(g=Math.floor(n.length/66)+1)+"\r\n",i+=n;var p=_sha1("putty-private-key-file-mac-key",r),v=forge.util.createBuffer();_addStringToBuffer(v,f),_addStringToBuffer(v,a),_addStringToBuffer(v,t),v.putInt32(u.length()),v.putBuffer(u),v.putInt32(d.length()),v.putBuffer(d);var y=forge.hmac.create();return y.start("sha1",p),y.update(v.bytes()),i+="\r\nPrivate-MAC: "+y.digest().toHex()+"\r\n"},ssh.publicKeyToOpenSSH=function(e,r){var t="ssh-rsa";r=r||"";var n=forge.util.createBuffer();return _addStringToBuffer(n,t),_addBigIntegerToBuffer(n,e.e),_addBigIntegerToBuffer(n,e.n),t+" "+forge.util.encode64(n.bytes())+" "+r},ssh.privateKeyToOpenSSH=function(e,r){return r?forge.pki.encryptRsaPrivateKey(e,r,{legacy:!0,algorithm:"aes128"}):forge.pki.privateKeyToPem(e)},ssh.getPublicKeyFingerprint=function(e,r){var t=(r=r||{}).md||forge.md.md5.create(),n=forge.util.createBuffer();_addStringToBuffer(n,"ssh-rsa"),_addBigIntegerToBuffer(n,e.e),_addBigIntegerToBuffer(n,e.n),t.start(),t.update(n.getBytes());var f=t.digest();if("hex"===r.encoding){var a=f.toHex();return r.delimiter?a.match(/.{2}/g).join(r.delimiter):a}if("binary"===r.encoding)return f.getBytes();if(r.encoding)throw Error('Unknown encoding "'+r.encoding+'".');return f};