Пример #1
0
        public SshHelper(string Host, string UserName, string Password)
        {
            host = Host;
            var jsch = new JSch();
            session = jsch.getSession(UserName, host, 22);
            session.setPassword(Password);

            var config = new Hashtable { { "StrictHostKeyChecking", "no" } };
            session.setConfig(config);

            session.connect();

            channel = (ChannelShell)session.openChannel("shell");

            writer_po = new PipedOutputStream();
            var writer_pi = new PipedInputStream(writer_po);

            var reader_pi = new PipedInputStream();
            var reader_po = new PipedOutputStream(reader_pi);
            reader = new StreamReader(reader_pi, Encoding.UTF8);

            channel.setInputStream(writer_pi);
            channel.setOutputStream(reader_po);

            channel.connect();
            channel.setPtySize(132, 132, 1024, 768);
        }
Пример #2
0
 public void Connect()
 {
     InitVAHInfo();
     try
     {
         JSch jsch = new JSch();
         _ssn = jsch.getSession(_usr, _hip, _hp);
         System.Collections.Hashtable hashConfig = new Hashtable();
         hashConfig.Add("StrictHostKeyChecking", "No");
         _ssn.setConfig(hashConfig);
         jsch.addIdentity(_ppk);
         _ssn.connect();
         if (_ssn.isConnected())
         {
             Console.WriteLine("Log Successfully.");
         }
         else
         {
             Console.WriteLine("Log failed.");
         }
     }
     catch (Tamir.SharpSsh.jsch.JSchException jschex)
     {
         Console.WriteLine(jschex.Message);
     }
     catch (Exception anyex)
     {
         Console.WriteLine(anyex.Message);
     }
 }
Пример #3
0
		public static void Run()
		{
			JSch jsch=new JSch();
			Session session=jsch.getSession("root", "rhmanage", 22);
			session.setPassword( "cisco" );

			Hashtable config=new Hashtable();
			config.Add("StrictHostKeyChecking", "no");
			session.setConfig(config);

			session.connect();
			
				Channel channel=session.openChannel("exec"); 
				((ChannelExec)channel).setCommand("ifconfig");

				StreamReader sr = new StreamReader( channel.getInputStream() );

				channel.connect();

				string line;

				while( (line=sr.ReadLine()) != null )
				{
					Console.WriteLine( line );
				}		

				channel.disconnect();
				session.disconnect();
		}
Пример #4
0
        public static void Connect()
        {
            try
             {
                 var jsch = new JSch();

                 _session = jsch.getSession(Settings.SSHUsername, Settings.SSHHost, Settings.SSHPort);
                 _session.setHost(Settings.SSHHost);
                 _session.setPassword(Settings.SSHPassword);
                 UserInfo ui = new MyUserInfo(Settings.SSHPassword);
                 _session.setUserInfo(ui);
                 _session.connect();
                 int port;
                 if (!int.TryParse(Settings.Port, out port))
                     port = 3306;
                 _session.setPortForwardingL(Settings.SSHLocalPort, "localhost", port);
                 if (!_session.isConnected())
                    Enabled = false;
             }
             catch (Exception ex)
             {
                Enabled = false;
                Trace.WriteLine(ex.Message + " at ssh connect.");
                Disconnect();
            }
        }
Пример #5
0
		public static void RunExample(String[] arg)
		{
			try
			{
				//Create a new JSch instance
				JSch jsch=new JSch();
			
				//Prompt for username and server host
				Console.WriteLine("Please enter the user and host info at the popup window...");
				String host = InputForm.GetUserInput
					("Enter username@hostname",
					Environment.UserName+"@localhost");
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				//Create a new SSH session
				Session session=jsch.getSession(user, host, 22);

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);

				//Add AES128 as default cipher in the session config store
				System.Collections.Hashtable config=new System.Collections.Hashtable();
				config.Add("cipher.s2c", "aes128-cbc,3des-cbc");
				config.Add("cipher.c2s", "aes128-cbc,3des-cbc");
				session.setConfig(config);

				//Connect to remote SSH server
				session.connect();			

				//Open a new Shell channel on the SSH session
				Channel channel=session.openChannel("shell");

				//Redirect standard I/O to the SSH channel
				channel.setInputStream(Console.OpenStandardInput());
				channel.setOutputStream(Console.OpenStandardOutput());

				//Connect the channel
				channel.connect();

				Console.WriteLine("-- Shell channel is connected using the {0} cipher", 
					session.getCipher());

				//Wait till channel is closed
				while(!channel.isClosed())
				{
					System.Threading.Thread.Sleep(500);
				}

				//Disconnect from remote server
				channel.disconnect();
				session.disconnect();			

			}
			catch(Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
Пример #6
0
        public SshHelper(string host, string username, string password)
        {
            this.host = host;
            JSch jsch=new JSch();
            Session session=jsch.getSession(username, host, 22);
            session.setPassword( password );

            Hashtable config=new Hashtable();
            config.Add("StrictHostKeyChecking", "no");
            session.setConfig(config);

            session.connect();

            channel=(ChannelShell)session.openChannel("shell");

            writer_po = new PipedOutputStream();
            PipedInputStream writer_pi = new PipedInputStream( writer_po );

            PipedInputStream reader_pi = new PipedInputStream();
            PipedOutputStream reader_po = new PipedOutputStream( reader_pi );
            reader = new StreamReader (reader_pi,Encoding.UTF8);

            channel.setInputStream( writer_pi );
            channel.setOutputStream( reader_po );

            channel.connect();
            channel.setPtySize(132, 132, 1024, 768);
        }
Пример #7
0
		/// <summary>
		/// Constructs a new SSH instance
		/// </summary>
		/// <param name="sftpHost">The remote SSH host</param>
		/// <param name="user">The login username</param>
		/// <param name="password">The login password</param>
		public SshBase(string sftpHost, string user, string password)
		{
			this.m_host = sftpHost;
			this.m_user = user;
			this.Password = password;
			m_jsch = new JSch();
		}
Пример #8
0
		public String getFingerPrint(JSch jsch){
			HASH hash=null;
			try{
			hash=(HASH)Activator.CreateInstance(Type.GetType(jsch.getConfig("md5")));
			}
			catch(Exception e){ Console.Error.WriteLine("getFingerPrint: "+e); }
			return Util.getFingerPrint(hash, key);
		}
Пример #9
0
		public static void RunExample(String[] arg)
		{
			try
			{
				JSch jsch=new JSch();

				//Get the "known hosts" filename from the user
				Console.WriteLine("Please choose your private key file...");
				String file = InputForm.GetFileFromUser("Choose your privatekey(ex. ~/.ssh/id_dsa)");
				Console.WriteLine("You chose "+file+".");

				//Add the identity file to JSch
				jsch.addIdentity(file);

				//Prompt for username and server host
				Console.WriteLine("Please enter the user and host info at the popup window...");
				String host = InputForm.GetUserInput
					("Enter username@hostname",
					Environment.UserName+"@localhost");
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				//Create a new SSH session
				Session session=jsch.getSession(user, host, 22);

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);

				//Connect to remote SSH server
				session.connect();

				//Open a new Shell channel on the SSH session
				Channel channel=session.openChannel("shell");

				//Redirect standard I/O to the SSH channel
				channel.setInputStream(Console.OpenStandardInput());
				channel.setOutputStream(Console.OpenStandardOutput());

				//Connect the channel
				channel.connect();

				//Wait till channel is closed
				while(!channel.isClosed())
				{
					System.Threading.Thread.Sleep(500);
				}

				//Disconnect from remote server
				channel.disconnect();
				session.disconnect();			

			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}
		}
Пример #10
0
 public override void Connect(string Host, int Port, string Username, string Password, int timeout = 10000)
 {
     this.Host = Host;
     this.Port = Port;
     this.Username = Username;
     this.Password = Password;
     this.timeout = timeout;
     _jsch = null;
 }
Пример #11
0
        internal IdentityCert(String identity, JSch jsch)
        {
            this._identity = identity;
            this._jsch     = jsch;
            X509Store certStore       = null;
            bool      foundPrivateKey = false;
            string    thumbprint      = identity.ToUpperInvariant().Replace(" ", "");

            try
            {
                certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                certStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                foreach (X509Certificate2 certificate in certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, true))
                {
                    RSACryptoServiceProvider privateKey = certificate.PrivateKey as RSACryptoServiceProvider;
                    if (privateKey != null)
                    {
                        RSAParameters rsaKeyInfo = privateKey.ExportParameters(true);
                        List <byte>   modulus    = new List <byte>(1 + rsaKeyInfo.Modulus.Length);
                        modulus.Add(0);
                        modulus.AddRange(rsaKeyInfo.Modulus);
                        _n_array        = modulus.ToArray();
                        _d_array        = rsaKeyInfo.D;
                        _dmp1_array     = rsaKeyInfo.DP;
                        _dmq1_array     = rsaKeyInfo.DQ;
                        _e_array        = rsaKeyInfo.Exponent;
                        _iqmp_array     = rsaKeyInfo.InverseQ;
                        _p_array        = rsaKeyInfo.P;
                        _q_array        = rsaKeyInfo.Q;
                        foundPrivateKey = true;
                    }
                    break;
                }

                if (!foundPrivateKey)
                {
                    throw new JSchException("privatekey not found: " + identity);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Identity: " + e);
                if (e is JSchException)
                {
                    throw (JSchException)e;
                }
                throw new JSchException(e.ToString());
            }
            finally
            {
                if (certStore != null)
                {
                    certStore.Close();
                }
            }
        }
Пример #12
0
        public String getFingerPrint(JSch jsch)
        {
            HASH hash = null;

            try{
                hash = (HASH)Activator.CreateInstance(Type.GetType(jsch.getConfig("md5")));
            }
            catch (Exception e) { Console.Error.WriteLine("getFingerPrint: " + e); }
            return(Util.getFingerPrint(hash, key));
        }
Пример #13
0
		public static void RunExample(params string[] arg)
		{
			if(arg.Length<3)
			{
				Console.Error.WriteLine(
					"usage: java KeyGen rsa output_keyfile comment\n"+
					"       java KeyGen dsa  output_keyfile comment");
				return;
			}

			try
			{
				//Get sig type ('rsa' or 'dsa')
				String _type=arg[0];
				int type=0;
				if(_type.Equals("rsa")){type=KeyPair.RSA;}
				else if(_type.Equals("dsa")){type=KeyPair.DSA;}
				else 
				{
					Console.Error.WriteLine(
						"usage: java KeyGen rsa output_keyfile comment\n"+
						"       java KeyGen dsa  output_keyfile comment");
					return;
				}
				//Output file name
				String filename=arg[1];
				//Signature comment
				String comment=arg[2];

				//Create a new JSch instance
				JSch jsch=new JSch();

				//Prompt the user for a passphrase for the private key file
				String passphrase=InputForm.GetUserInput("Enter passphrase (empty for no passphrase)", true);


				//Generate the new key pair
				KeyPair kpair=KeyPair.genKeyPair(jsch, type);
				//Set a passphrase
				kpair.setPassphrase(passphrase);
				//Write the private key to "filename"
				kpair.writePrivateKey(filename);
				//Write the public key to "filename.pub"
				kpair.writePublicKey(filename+".pub", comment);
				//Print the key fingerprint
				Console.WriteLine("Finger print: "+kpair.getFingerPrint());
				//Free resources
				kpair.dispose();
			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}
			return;
		}
Пример #14
0
		public static KeyPair genKeyPair(JSch jsch, int type, int key_size)
		{
			KeyPair kpair=null;
			if(type==DSA){ kpair=new KeyPairDSA(jsch); }
			else if(type==RSA){ kpair=new KeyPairRSA(jsch); }
			if(kpair!=null)
			{
				kpair.generate(key_size);
			}
			return kpair;
		}
Пример #15
0
        public static KeyPair load(JSch jsch, String prvkey)
        {
            String pubkey = prvkey + ".pub";

//			if(!new File(pubkey).exists())
            if (!File.Exists(pubkey))
            {
                pubkey = null;
            }
            return(load(jsch, prvkey, pubkey));
        }
Пример #16
0
 /// <summary>
 /// 构造方法
 /// </summary>
 /// <param name="host"></param>
 /// <param name="user"></param>
 /// <param name="pwd"></param>
 public SftpHelper(string host, string user, string pwd)
 {
     string[] arr = host.Split(':');
     string ip = arr[0];
     int port = 22;
     if (arr.Length > 1) port = Int32.Parse(arr[1]);
     JSch jsch = new JSch();
     m_session = jsch.getSession(user, ip, port);
     MyUserInfo ui = new MyUserInfo();
     ui.setPassword(pwd);
     m_session.setUserInfo(ui);
 }
Пример #17
0
        public static void RunExample(String[] arg)
        {
            if(arg.Length<3)
            {
                Console.Error.WriteLine(
                    "usage: java KeyGen rsa output_keyfile comment\n"+
                    "       java KeyGen dsa  output_keyfile comment");
                Environment.Exit(-1);
            }
            String _type=arg[0];
            int type=0;
            if(_type.Equals("rsa")){type=KeyPair.RSA;}
            else if(_type.Equals("dsa")){type=KeyPair.DSA;}
            else
            {
                Console.Error.WriteLine(
                    "usage: java KeyGen rsa output_keyfile comment\n"+
                    "       java KeyGen dsa  output_keyfile comment");
                Environment.Exit(-1);
            }
            String filename=arg[1];
            String comment=arg[2];

            JSch jsch=new JSch();

            String passphrase="";
            InputForm passphraseField=new InputForm();
            passphraseField.PasswordField = true;
            Object[] ob={passphraseField};

                passphraseField.Text="Enter passphrase (empty for no passphrase)";
                bool result=passphraseField.PromptForInput();
            if(result)
            {
                passphrase=passphraseField.getText();
            }

            try
            {
                KeyPair kpair=KeyPair.genKeyPair(jsch, type);
                kpair.setPassphrase(passphrase);
                kpair.writePrivateKey(filename);
                kpair.writePublicKey(filename+".pub", comment);
                Console.WriteLine("Finger print: "+kpair.getFingerPrint());
                kpair.dispose();
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
            Environment.Exit(0);
        }
Пример #18
0
		public static void RunExample(String[] arg)
		{
			int port;

			try
			{
				//Create a new JSch instance
				JSch jsch=new JSch();

				//Prompt for username and server host
				Console.WriteLine("Please enter the user and host info at the popup window...");
				String host = InputForm.GetUserInput
					("Enter username@hostname",
					Environment.UserName+"@localhost");
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				//Create a new SSH session
				Session session=jsch.getSession(user, host, 22);

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);
				session.connect();

				//Get from user the remote host and remote host port
				String foo = InputForm.GetUserInput("Enter host and port", "host:port");
				host=foo.Substring(0, foo.IndexOf(':'));
				port=int.Parse(foo.Substring(foo.IndexOf(':')+1));

				Console.WriteLine("System.{in,out} will be forwarded to "+
					host+":"+port+".");
				Channel channel=session.openChannel("direct-tcpip");
				((ChannelDirectTCPIP)channel).setInputStream(Console.OpenStandardInput());
				((ChannelDirectTCPIP)channel).setOutputStream(Console.OpenStandardOutput());
				((ChannelDirectTCPIP)channel).setHost(host);
				((ChannelDirectTCPIP)channel).setPort(port);
				channel.connect();

				while(!channel.isClosed())
				{
					System.Threading.Thread.Sleep(500);
				}
				channel.disconnect();
				session.disconnect();
			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}
		}
Пример #19
0
		public static void RunExample(String[] arg)
		{
			//Get the private key filename from the user
			Console.WriteLine("Please choose your private key file...");
			String pkey = InputForm.GetFileFromUser("Choose your privatekey(ex. ~/.ssh/id_dsa)");
			Console.WriteLine("You chose "+pkey+".");

			//Create a new JSch instance
			JSch jsch=new JSch();

			try
			{
				//Load the key pair
				KeyPair kpair=KeyPair.load(jsch, pkey);

				//Print the key file encryption status
				Console.WriteLine(pkey+" has "+(kpair.isEncrypted()?"been ":"not been ")+"encrypted");

				String passphrase = "";

				while(kpair.isEncrypted())
				{
					passphrase = InputForm.GetUserInput("Enter passphrase for "+pkey, true);
					if(!kpair.decrypt(passphrase))
					{
						Console.WriteLine("failed to decrypt "+pkey);
					}
					else
					{
						Console.WriteLine(pkey+" is decrypted.");
					}
				}

				passphrase="";

				passphrase=InputForm.GetUserInput("Enter new passphrase for "+pkey+
					       " (empty for no passphrase)", true);

				//Set the new passphrase
				kpair.setPassphrase(passphrase);
				//write the key to file
				kpair.writePrivateKey(pkey);
				//free the resource
				kpair.dispose();
			}
			catch(Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
Пример #20
0
		protected void _Connect()
		{
			_jsch = new JSch();
			//session.setConfig();
			_session = _jsch.getSession(this.Username, this.Host, this.Port);
			UserInfo ui = new DirectPasswordUserInfo(this.Password);
			_session.setUserInfo(ui);
			_session.connect();

			_csftp = (ChannelSftp)_session.openChannel("sftp");
			_csftp.connect();

			//RootPath = csftp.getHome();
			RootPath = "";
		}
Пример #21
0
        public static KeyPair genKeyPair(JSch jsch, int type, int key_size)
        {
            KeyPair kpair = null;

            if (type == DSA)
            {
                kpair = new KeyPairDSA(jsch);
            }
            else if (type == RSA)
            {
                kpair = new KeyPairRSA(jsch);
            }
            if (kpair != null)
            {
                kpair.generate(key_size);
            }
            return(kpair);
        }
Пример #22
0
		public static void test()
		{
			JSch jsch = new JSch();
			DH dh1 = null;
			DH dh2 = null;
			try
			{
				Type t=Type.GetType(jsch.getConfig("dh"));
				dh1=(DH)(Activator.CreateInstance(t));
				dh1.init();
				dh2=(DH)(Activator.CreateInstance(t));
				dh2.init();
			}
			catch(Exception ee)
			{
				Console.WriteLine(ee);
			}

			dh1.setP(DHG1.p);
			dh1.setG(DHG1.g);
			dh2.setP(DHG1.p);
			dh2.setG(DHG1.g);

			// The client responds with:
			// byte  SSH_MSG_KEXDH_INIT(30)
			// mpint e <- g^x mod p
			//         x is a random number (1 < x < (p-1)/2)

			byte[] e=dh1.getE();
			byte[] f=dh2.getE();
			Console.WriteLine("Private1 = {0}", hex(e));
			Console.WriteLine();
			Console.WriteLine("Private2 = {0}", hex(f));
			Console.WriteLine();
			dh1.setF(f);
			dh2.setF(e);
			byte[] k1 = dh1.getK();
			byte[] k2 = dh2.getK();
			Console.WriteLine("Public1 = {0}", hex(k1));
			Console.WriteLine();
			Console.WriteLine("Public2 = {0}", hex(k2));
			Console.WriteLine();
		}
Пример #23
0
		public static void RunExample(String[] arg)
		{
			//int port;

			try
			{
				//Create a new JSch instance
				JSch jsch=new JSch();

				//Prompt for username and server host
				Console.WriteLine("Please enter the user and host info at the popup window...");
				String host = InputForm.GetUserInput
					("Enter username@hostname",
					Environment.UserName+"@localhost");
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				//Create a new SSH session
				Session session=jsch.getSession(user, host, 22);

				//Get from user the local port, remote host and remote host port
				String foo = InputForm.GetUserInput("Enter -L port:host:hostport","port:host:hostport");
				int lport=int.Parse(foo.Substring(0, foo.IndexOf(':')));
				foo=foo.Substring(foo.IndexOf(':')+1);
				String rhost=foo.Substring(0, foo.IndexOf(':'));
				int rport=int.Parse(foo.Substring(foo.IndexOf(':')+1));

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);
				session.connect();

				Console.WriteLine("localhost:"+lport+" -> "+rhost+":"+rport);

				//Set port forwarding on the opened session
				session.setPortForwardingL(lport, rhost, rport);			
			}
			catch(Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
Пример #24
0
		/// <summary>
		/// Constructs a new SSH stream.
		/// </summary>
		/// <param name="host">The hostname or IP address of the remote SSH machine</param>
		/// <param name="username">The name of the user connecting to the remote machine</param>
		/// <param name="password">The password of the user connecting to the remote machine</param>
		public SshStream(string host, string username, string password)
		{
			this.m_host = host;
			JSch jsch=new JSch();
			m_session=jsch.getSession(username, host, 22);
			m_session.setPassword( password );
		
			Hashtable config=new Hashtable();
			config.Add("StrictHostKeyChecking", "no");
			m_session.setConfig(config);
		
			m_session.connect();
			m_channel=(ChannelShell)m_session.openChannel("shell");

			m_in	= m_channel.getInputStream();
			m_out	= m_channel.getOutputStream();

			m_channel.connect();
			m_channel.setPtySize(80, 132, 1024, 768);

			Prompt = "\n";
			m_escapeCharPattern = "\\[[0-9;?]*[^0-9;]";
		}
Пример #25
0
 internal IdentityFile(String identity, JSch jsch)
 {
     this.identity = identity;
     this.jsch     = jsch;
     byte[] buf;
     try
     {
         var file = new FileInfo(identity);
         var fis  = File.OpenRead(identity);
         buf = new byte[(int)(file.Length)];
         var len = fis.Read(buf, 0, buf.Length);
         fis.Close();
     }
     catch (Exception e)
     {
         Console.WriteLine("Identity: " + e);
         if (e is JSchException)
         {
             throw (JSchException)e;
         }
         throw new JSchException(e.ToString());
     }
     InitPrivate(buf);
 }
Пример #26
0
 public static KeyPair genKeyPair(JSch jsch, int type)
 {
     return(genKeyPair(jsch, type, 1024));
 }
Пример #27
0
		internal Session(JSch jsch)  
		{
			;
			this.jsch=jsch;
			buf=new Buffer();
			packet=new Packet(buf);
		}
Пример #28
0
        public static void Main(String[] arg)
        {
            if(arg.Length!=2)
            {
                Console.WriteLine("usage: java ScpTo file1 user@remotehost:file2");
                Environment.Exit(-1);
            }

            try
            {

                String lfile=arg[0];
                String user=arg[1].Substring(0, arg[1].IndexOf('@'));
                arg[1]=arg[1].Substring(arg[1].IndexOf('@')+1);
                String host=arg[1].Substring(0, arg[1].IndexOf(':'));
                String rfile=arg[1].Substring(arg[1].IndexOf(':')+1);

                JSch jsch=new JSch();
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                // exec 'scp -t rfile' remotely
                String command="scp -p -t "+rfile;
                Channel channel=session.openChannel("exec");
                ((ChannelExec)channel).setCommand(command);

                // get I/O streams for remote scp
                Stream outs=channel.getOutputStream();
                Stream ins=channel.getInputStream();

                channel.connect();

                byte[] tmp=new byte[1];

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }

                // send "C0644 filesize filename", where filename should not include '/'

                int filesize=(int)(new FileInfo(lfile)).Length;
                command="C0644 "+filesize+" ";
                if(lfile.LastIndexOf('/')>0)
                {
                    command+=lfile.Substring(lfile.LastIndexOf('/')+1);
                }
                else
                {
                    command+=lfile;
                }
                command+="\n";
                byte[] buff = Util.getBytes(command);
                outs.Write(buff, 0, buff.Length); outs.Flush();

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }

                // send a content of lfile
                FileStream fis=File.OpenRead(lfile);
                byte[] buf=new byte[1024];
                while(true)
                {
                    int len=fis.Read(buf, 0, buf.Length);
                    if(len<=0) break;
                    outs.Write(buf, 0, len); outs.Flush();
                    Console.Write("#");
                }

                // send '\0'
                buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();
                Console.Write(".");

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }
                Console.WriteLine("OK");
                Environment.Exit(0);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #29
0
		public KeyPairDSA(JSch jsch):base(jsch)
		{
		}
Пример #30
0
 internal KnownHosts(JSch jsch)
 {
     this.jsch = jsch;
     pool      = new ArrayList();
 }
Пример #31
0
 internal IdentityFile(byte[] buf, String name, JSch jsch)
 {
     this.identity = name;
     this.jsch     = jsch;
     InitPrivate(buf);
 }
Пример #32
0
 private static void loadIdentity(JSch sch, FileInfo priv)
 {
     if (!priv.IsFile()) return;
     try
     {
         sch.addIdentity(priv.FullName);
     }
     catch (JSchException)
     {
         // Instead, pretend the key doesn't exist.
     }
 }
Пример #33
0
 private static void identities(JSch sch)
 {
     DirectoryInfo home = FS.userHome();
     if (home == null)
         return;
     var sshdir = PathUtil.CombineDirectoryPath(home, ".ssh");
     if (sshdir.IsDirectory())
     {
         loadIdentity(sch, PathUtil.CombineFilePath(sshdir, "identity"));
         loadIdentity(sch, PathUtil.CombineFilePath(sshdir, "id_rsa"));
         loadIdentity(sch, PathUtil.CombineFilePath(sshdir, "id_dsa"));
     }
 }
Пример #34
0
 private static void knownHosts(JSch sch)
 {
     DirectoryInfo home = FS.userHome();
     if (home == null)
         return;
     var known_hosts = new FileInfo(Path.Combine(home.ToString(), ".ssh/known_hosts"));
     try
     {
         using (var s = new StreamReader(known_hosts.FullName))
         {
             sch.setKnownHosts(s);
         }
     }
     catch (FileNotFoundException)
     {
         // Oh well. They don't have a known hosts in home.
     }
     catch (IOException)
     {
         // Oh well. They don't have a known hosts in home.
     }
 }
Пример #35
0
 /// <summary>
 /// Returns the new default JSch implementation
 /// </summary>
 /// <returns>the new default JSch implementation</returns>
 protected static JSch createDefaultJSch()
 {
     JSch jsch = new JSch();
     knownHosts(jsch);
     identities(jsch);
     return jsch;
 }
Пример #36
0
 internal KnownHosts(JSch jsch) : base()
 {
     this.jsch = jsch;
     pool      = new System.Collections.ArrayList();
 }
Пример #37
0
 public KeyPairRSA(JSch jsch) : base(jsch)
 {
 }
Пример #38
0
        public static KeyPair load(JSch jsch, String prvkey, String pubkey)
        {
            byte[] iv        = new byte[8];          // 8
            bool   encrypted = true;

            byte[] data = null;

            byte[] publickeyblob = null;

            int type   = ERROR;
            int vendor = VENDOR_OPENSSH;

            try
            {
                //File file=new File(prvkey);
                FileStream fis = File.OpenRead(prvkey);
                byte[]     buf = new byte[(int)(fis.Length)];
                int        len = fis.Read(buf, 0, buf.Length);
                fis.Close();

                int i = 0;

                while (i < len)
                {
                    if (buf[i] == 'B' && buf[i + 1] == 'E' && buf[i + 2] == 'G' && buf[i + 3] == 'I')
                    {
                        i += 6;
                        if (buf[i] == 'D' && buf[i + 1] == 'S' && buf[i + 2] == 'A')
                        {
                            type = DSA;
                        }
                        else if (buf[i] == 'R' && buf[i + 1] == 'S' && buf[i + 2] == 'A')
                        {
                            type = RSA;
                        }
                        else if (buf[i] == 'S' && buf[i + 1] == 'S' && buf[i + 2] == 'H')
                        {                         // FSecure
                            type   = UNKNOWN;
                            vendor = VENDOR_FSECURE;
                        }
                        else
                        {
                            //System.outs.println("invalid format: "+identity);
                            throw new JSchException("invaid privatekey: " + prvkey);
                        }
                        i += 3;
                        continue;
                    }
                    if (buf[i] == 'C' && buf[i + 1] == 'B' && buf[i + 2] == 'C' && buf[i + 3] == ',')
                    {
                        i += 4;
                        for (int ii = 0; ii < iv.Length; ii++)
                        {
                            iv[ii] = (byte)(((a2b(buf[i++]) << 4) & 0xf0) + (a2b(buf[i++]) & 0xf));
                        }
                        continue;
                    }
                    if (buf[i] == 0x0d &&
                        i + 1 < buf.Length && buf[i + 1] == 0x0a)
                    {
                        i++;
                        continue;
                    }
                    if (buf[i] == 0x0a && i + 1 < buf.Length)
                    {
                        if (buf[i + 1] == 0x0a)
                        {
                            i += 2; break;
                        }
                        if (buf[i + 1] == 0x0d &&
                            i + 2 < buf.Length && buf[i + 2] == 0x0a)
                        {
                            i += 3; break;
                        }
                        bool inheader = false;
                        for (int j = i + 1; j < buf.Length; j++)
                        {
                            if (buf[j] == 0x0a)
                            {
                                break;
                            }
                            //if(buf[j]==0x0d) break;
                            if (buf[j] == ':')
                            {
                                inheader = true; break;
                            }
                        }
                        if (!inheader)
                        {
                            i++;
                            encrypted = false;                              // no passphrase
                            break;
                        }
                    }
                    i++;
                }

                if (type == ERROR)
                {
                    throw new JSchException("invaid privatekey: " + prvkey);
                }

                int start = i;
                while (i < len)
                {
                    if (buf[i] == 0x0a)
                    {
                        bool xd = (buf[i - 1] == 0x0d);
                        Array.Copy(buf, i + 1,
                                   buf,
                                   i - (xd ? 1 : 0),
                                   len - i - 1 - (xd ? 1 : 0)
                                   );
                        if (xd)
                        {
                            len--;
                        }
                        len--;
                        continue;
                    }
                    if (buf[i] == '-')
                    {
                        break;
                    }
                    i++;
                }
                data = Util.fromBase64(buf, start, i - start);

                if (data.Length > 4 &&                         // FSecure
                    data[0] == (byte)0x3f &&
                    data[1] == (byte)0x6f &&
                    data[2] == (byte)0xf9 &&
                    data[3] == (byte)0xeb)
                {
                    Buffer _buf = new Buffer(data);
                    _buf.ReadInt();                      // 0x3f6ff9be
                    _buf.ReadInt();
                    byte[] _type = _buf.ReadString();
                    //System.outs.println("type: "+Encoding.UTF8.GetString(_type));
                    byte[] _cipher = _buf.ReadString();
                    String cipher  = Util.getString(_cipher);
                    //System.outs.println("cipher: "+cipher);
                    if (cipher.Equals("3des-cbc"))
                    {
                        _buf.ReadInt();
                        byte[] foo = new byte[data.Length - _buf.Offset];
                        _buf.ReadByte(foo);
                        data      = foo;
                        encrypted = true;
                        throw new JSchException("unknown privatekey format: " + prvkey);
                    }
                    else if (cipher.Equals("none"))
                    {
                        _buf.ReadInt();
                        _buf.ReadInt();

                        encrypted = false;

                        byte[] foo = new byte[data.Length - _buf.Offset];
                        _buf.ReadByte(foo);
                        data = foo;
                    }
                }

                if (pubkey != null)
                {
                    try
                    {
                        //file=new File(pubkey);
                        fis = File.OpenRead(pubkey);
                        buf = new byte[(int)(fis.Length)];
                        len = fis.Read(buf, 0, buf.Length);
                        fis.Close();

                        if (buf.Length > 4 &&                                  // FSecure's public key
                            buf[0] == '-' && buf[1] == '-' && buf[2] == '-' && buf[3] == '-')
                        {
                            bool valid = true;
                            i = 0;
                            do
                            {
                                i++;
                            }while(buf.Length > i && buf[i] != 0x0a);
                            if (buf.Length <= i)
                            {
                                valid = false;
                            }

                            while (valid)
                            {
                                if (buf[i] == 0x0a)
                                {
                                    bool inheader = false;
                                    for (int j = i + 1; j < buf.Length; j++)
                                    {
                                        if (buf[j] == 0x0a)
                                        {
                                            break;
                                        }
                                        if (buf[j] == ':')
                                        {
                                            inheader = true; break;
                                        }
                                    }
                                    if (!inheader)
                                    {
                                        i++;
                                        break;
                                    }
                                }
                                i++;
                            }
                            if (buf.Length <= i)
                            {
                                valid = false;
                            }

                            start = i;
                            while (valid && i < len)
                            {
                                if (buf[i] == 0x0a)
                                {
                                    Array.Copy(buf, i + 1, buf, i, len - i - 1);
                                    len--;
                                    continue;
                                }
                                if (buf[i] == '-')
                                {
                                    break;
                                }
                                i++;
                            }
                            if (valid)
                            {
                                publickeyblob = Util.fromBase64(buf, start, i - start);
                                if (type == UNKNOWN)
                                {
                                    if (publickeyblob[8] == 'd')
                                    {
                                        type = DSA;
                                    }
                                    else if (publickeyblob[8] == 'r')
                                    {
                                        type = RSA;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (buf[0] == 's' && buf[1] == 's' && buf[2] == 'h' && buf[3] == '-')
                            {
                                i = 0;
                                while (i < len)
                                {
                                    if (buf[i] == ' ')
                                    {
                                        break;
                                    }
                                    i++;
                                }
                                i++;
                                if (i < len)
                                {
                                    start = i;
                                    while (i < len)
                                    {
                                        if (buf[i] == ' ')
                                        {
                                            break;
                                        }
                                        i++;
                                    }
                                    publickeyblob = Util.fromBase64(buf, start, i - start);
                                }
                            }
                        }
                    }
                    catch                    //(Exception ee)
                    {
                    }
                }
            }
            catch (Exception e)
            {
                if (e is JSchException)
                {
                    throw (JSchException)e;
                }
                throw new JSchException(e.ToString());
            }

            KeyPair kpair = null;

            if (type == DSA)
            {
                kpair = new KeyPairDSA(jsch);
            }
            else if (type == RSA)
            {
                kpair = new KeyPairRSA(jsch);
            }

            if (kpair != null)
            {
                kpair.encrypted     = encrypted;
                kpair.publickeyblob = publickeyblob;
                kpair.vendor        = vendor;

                if (encrypted)
                {
                    kpair.iv   = iv;
                    kpair.data = data;
                }
                else
                {
                    if (kpair.parse(data))
                    {
                        return(kpair);
                    }
                    else
                    {
                        throw new JSchException("invaid privatekey: " + prvkey);
                    }
                }
            }

            return(kpair);
        }
Пример #39
0
        /// <summary>
        ///  This class creates a jsch instance using the host that user wants. This makes it possible to
        ///  forward the MySql Database port to a user's local port.
        /// </summary>
        public string jschServer(string host, string user, string password)
        {
            try
            {
                // Create a new JSch instance
                JSch jsch = new JSch();

                // Saves the info to make other sessions
                this.host = host;
                this.user = user;
                this.password = password;

                // Create a new SSH session
                session = jsch.getSession(user, password, port);
                session.setHost(host); ;
                session.setPassword(password);

                // Creates a userinfo instance to pass into the session
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);

                session.connect();

                return null;
            }
            catch (Exception ex)
            {
                session.disconnect();
                return ex.Message;
            }
        }
Пример #40
0
 public KeyPair(JSch jsch)
 {
     this.jsch = jsch;
 }
Пример #41
0
        ///SFTP Code Starting here
        ///hell yeah
        private void sftp_login()
        {
            JSch jsch = new JSch();

            String host = ftpHost();
            String user = ftpUser();

            Session session = jsch.getSession(user, host, 22);

            // username and password will be given via UserInfo interface.
            UserInfo ui = new MyUserInfo();

            session.setUserInfo(ui);

            session.setPort(ftpPort());

            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpc = (ChannelSftp)channel;
            //sftpc = (ChannelSftp)channel;
        }
Пример #42
0
		public static void RunExample(String[] arg)
		{
			try
			{
				JSch jsch=new JSch();

				InputForm inForm = new InputForm();
				inForm.Text = "Enter username@hostname";
				inForm.textBox1.Text = Environment.UserName+"@localhost"; 

				if (!inForm.PromptForInput())
				{
					Console.WriteLine("Cancelled");
					return;
				}
				String host = inForm.textBox1.Text;
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				Session session=jsch.getSession(user, host, 22);

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);

				session.connect();

				Channel channel=session.openChannel("sftp");
				channel.connect();
				ChannelSftp c=(ChannelSftp)channel;

				Stream ins=Console.OpenStandardInput();
				TextWriter outs=Console.Out;

				ArrayList cmds=new ArrayList();
				byte[] buf=new byte[1024];
				int i;
				String str;
				int level=0;

				while(true)
				{
					outs.Write("sftp> ");
					cmds.Clear();
					i=ins.Read(buf, 0, 1024);
					if(i<=0)break;

					i--;
					if(i>0 && buf[i-1]==0x0d)i--;
					//str=Util.getString(buf, 0, i);
					//Console.WriteLine("|"+str+"|");
					int s=0;
					for(int ii=0; ii<i; ii++)
					{
						if(buf[ii]==' ')
						{
							if(ii-s>0){ cmds.Add(Util.getString(buf, s, ii-s)); }
							while(ii<i){if(buf[ii]!=' ')break; ii++;}
							s=ii;
						}
					}
					if(s<i){ cmds.Add(Util.getString(buf, s, i-s)); }
					if(cmds.Count==0)continue;

					String cmd=(String)cmds[0];
					if(cmd.Equals("quit"))
					{
						c.quit();
						break;
					}
					if(cmd.Equals("exit"))
					{
						c.exit();
						break;
					}
					if(cmd.Equals("rekey"))
					{
						session.rekey();
						continue;
					}
					if(cmd.Equals("compression"))
					{
						if(cmds.Count<2)
						{
							outs.WriteLine("compression level: "+level);
							continue;
						}
						try
						{
							level=int.Parse((String)cmds[1]);
							Hashtable config=new Hashtable();
							if(level==0)
							{
								config.Add("compression.s2c", "none");
								config.Add("compression.c2s", "none");
							}
							else
							{
								config.Add("compression.s2c", "zlib,none");
								config.Add("compression.c2s", "zlib,none");
							}
							session.setConfig(config);
						}
						catch{}//(Exception e){}
						continue;
					}
					if(cmd.Equals("cd") || cmd.Equals("lcd"))
					{
						if(cmds.Count<2) continue;
						String path=(String)cmds[1];
						try
						{
							if(cmd.Equals("cd")) c.cd(path);
							else c.lcd(path);
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir"))
					{
						if(cmds.Count<2) continue;
						String path=(String)cmds[1];
						try
						{
							if(cmd.Equals("rm")) c.rm(path);
							else if(cmd.Equals("rmdir")) c.rmdir(path);
							else c.mkdir(path);
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod"))
					{
						if(cmds.Count!=3) continue;
						String path=(String)cmds[2];
						int foo=0;
						if(cmd.Equals("chmod"))
						{
							byte[] bar=Util.getBytes((String)cmds[1]);
							int k;
							for(int j=0; j<bar.Length; j++)
							{
								k=bar[j];
								if(k<'0'||k>'7'){foo=-1; break;}
								foo<<=3;
								foo|=(k-'0');
							}
							if(foo==-1)continue;
						}
						else
						{
							try{foo=int.Parse((String)cmds[1]);}
							catch{}//(Exception e){continue;}
						}
						try
						{
							if(cmd.Equals("chgrp")){ c.chgrp(foo, path); }
							else if(cmd.Equals("chown")){ c.chown(foo, path); }
							else if(cmd.Equals("chmod")){ c.chmod(foo, path); }
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("pwd") || cmd.Equals("lpwd"))
					{
						str=(cmd.Equals("pwd")?"Remote":"Local");
						str+=" working directory: ";
						if(cmd.Equals("pwd")) str+=c.pwd();
						else str+=c.lpwd();
						outs.WriteLine(str);
						continue;
					}
					if(cmd.Equals("ls") || cmd.Equals("dir"))
					{
						String path=".";
						if(cmds.Count==2) path=(String)cmds[1];
						try
						{
							ArrayList vv=c.ls(path);
							if(vv!=null)
							{
								for(int ii=0; ii<vv.Count; ii++)
								{
									object obj = vv[ii];
									if(obj is ChannelSftp.LsEntry)
										outs.WriteLine(vv[ii]);
								}
							}
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("lls") || cmd.Equals("ldir"))
					{
						String path=".";
						if(cmds.Count==2) path=(String)cmds[1];
						try
						{
							//java.io.File file=new java.io.File(path);
							if(!File.Exists(path))
							{
								outs.WriteLine(path+": No such file or directory");
								continue; 
							}
							if(Directory.Exists(path))
							{
								String[] list=Directory.GetDirectories(path);
								for(int ii=0; ii<list.Length; ii++)
								{
									outs.WriteLine(list[ii]);
								}
								continue;
							}
							outs.WriteLine(path);
						}
						catch(Exception e)
						{
							Console.WriteLine(e);
						}
						continue;
					}
					if(cmd.Equals("get") || 
						cmd.Equals("get-resume") || cmd.Equals("get-append") || 
						cmd.Equals("put") || 
						cmd.Equals("put-resume") || cmd.Equals("put-append")
						)
					{
						if(cmds.Count!=2 && cmds.Count!=3) continue;
						String p1=(String)cmds[1];
						//	  String p2=p1;
						String p2=".";
						if(cmds.Count==3)p2=(String)cmds[2];
						try
						{
							SftpProgressMonitor monitor=new MyProgressMonitor();
							if(cmd.StartsWith("get"))
							{
								int mode=ChannelSftp.OVERWRITE;
								if(cmd.Equals("get-resume")){ mode=ChannelSftp.RESUME; }
								else if(cmd.Equals("get-append")){ mode=ChannelSftp.APPEND; } 
								c.get(p1, p2, monitor, mode);
							}
							else
							{ 
								int mode=ChannelSftp.OVERWRITE;
								if(cmd.Equals("put-resume")){ mode=ChannelSftp.RESUME; }
								else if(cmd.Equals("put-append")){ mode=ChannelSftp.APPEND; } 
								c.put(p1, p2, monitor, mode); 
							}
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename"))
					{
						if(cmds.Count!=3) continue;
						String p1=(String)cmds[1];
						String p2=(String)cmds[2];
						try
						{
							if(cmd.Equals("rename")) c.rename(p1, p2);
							else c.symlink(p1, p2);
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						continue;
					}
					if(cmd.Equals("stat") || cmd.Equals("lstat"))
					{
						if(cmds.Count!=2) continue;
						String p1=(String)cmds[1];
						SftpATTRS attrs=null;
						try
						{
							if(cmd.Equals("stat")) attrs=c.stat(p1);
							else attrs=c.lstat(p1);
						}
						catch(SftpException e)
						{
							Console.WriteLine(e.message);
						}
						if(attrs!=null)
						{
							outs.WriteLine(attrs);
						}
						else
						{
						}
						continue;
					}
					if(cmd.Equals("version"))
					{
						outs.WriteLine("SFTP protocol version "+c.version());
						continue;
					}
					if(cmd.Equals("help") || cmd.Equals("?"))
					{
						outs.WriteLine(help);
						continue;
					}
					outs.WriteLine("unimplemented command: "+cmd);
				}
				session.disconnect();
			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}			
		}
Пример #43
0
        internal IdentityFile(String identity, JSch jsch)
        {
            this.identity = identity;
            this.jsch     = jsch;
            try
            {
                Type c = Type.GetType(jsch.getConfig("3des-cbc"));
                cipher = (Cipher)Activator.CreateInstance(c);
                key    = new byte[cipher.getBlockSize()];              // 24
                iv     = new byte[cipher.getIVSize()];                 // 8
                c      = Type.GetType(jsch.getConfig("md5"));
                hash   = (HASH)(Activator.CreateInstance(c));
                hash.init();
                FileInfo   file = new FileInfo(identity);
                FileStream fis  = File.OpenRead(identity);
                byte[]     buf  = new byte[(int)(file.Length)];
                int        len  = fis.Read(buf, 0, buf.Length);
                fis.Close();

                int i = 0;
                while (i < len)
                {
                    if (buf[i] == 'B' && buf[i + 1] == 'E' && buf[i + 2] == 'G' && buf[i + 3] == 'I')
                    {
                        i += 6;
                        if (buf[i] == 'D' && buf[i + 1] == 'S' && buf[i + 2] == 'A')
                        {
                            type = DSS;
                        }
                        else if (buf[i] == 'R' && buf[i + 1] == 'S' && buf[i + 2] == 'A')
                        {
                            type = RSA;
                        }
                        else if (buf[i] == 'S' && buf[i + 1] == 'S' && buf[i + 2] == 'H')
                        {                         // FSecure
                            type    = UNKNOWN;
                            keytype = FSECURE;
                        }
                        else
                        {
                            //System.out.println("invalid format: "+identity);
                            throw new JSchException("invaid privatekey: " + identity);
                        }
                        i += 3;
                        continue;
                    }
                    if (buf[i] == 'C' && buf[i + 1] == 'B' && buf[i + 2] == 'C' && buf[i + 3] == ',')
                    {
                        i += 4;
                        for (int ii = 0; ii < iv.Length; ii++)
                        {
                            iv[ii] = (byte)(((a2b(buf[i++]) << 4) & 0xf0) +
                                            (a2b(buf[i++]) & 0xf));
                        }
                        continue;
                    }
                    if (buf[i] == 0x0d &&
                        i + 1 < buf.Length && buf[i + 1] == 0x0a)
                    {
                        i++;
                        continue;
                    }
                    if (buf[i] == 0x0a && i + 1 < buf.Length)
                    {
                        if (buf[i + 1] == 0x0a)
                        {
                            i += 2; break;
                        }
                        if (buf[i + 1] == 0x0d &&
                            i + 2 < buf.Length && buf[i + 2] == 0x0a)
                        {
                            i += 3; break;
                        }
                        bool inheader = false;
                        for (int j = i + 1; j < buf.Length; j++)
                        {
                            if (buf[j] == 0x0a)
                            {
                                break;
                            }
                            //if(buf[j]==0x0d) break;
                            if (buf[j] == ':')
                            {
                                inheader = true; break;
                            }
                        }
                        if (!inheader)
                        {
                            i++;
                            encrypted = false;                              // no passphrase
                            break;
                        }
                    }
                    i++;
                }

                if (type == ERROR)
                {
                    throw new JSchException("invaid privatekey: " + identity);
                }

                int start = i;
                while (i < len)
                {
                    if (buf[i] == 0x0a)
                    {
                        bool xd = (buf[i - 1] == 0x0d);
                        Array.Copy(buf, i + 1,
                                   buf,
                                   i - (xd ? 1 : 0),
                                   len - i - 1 - (xd ? 1 : 0)
                                   );
                        if (xd)
                        {
                            len--;
                        }
                        len--;
                        continue;
                    }
                    if (buf[i] == '-')
                    {
                        break;
                    }
                    i++;
                }
                encoded_data = Util.fromBase64(buf, start, i - start);

                if (encoded_data.Length > 4 &&                         // FSecure
                    encoded_data[0] == (byte)0x3f &&
                    encoded_data[1] == (byte)0x6f &&
                    encoded_data[2] == (byte)0xf9 &&
                    encoded_data[3] == (byte)0xeb)
                {
                    Buffer _buf = new Buffer(encoded_data);
                    _buf.getInt();                      // 0x3f6ff9be
                    _buf.getInt();
                    byte[] _type = _buf.getString();
                    //System.out.println("type: "+new String(_type));
                    byte[] _cipher  = _buf.getString();
                    String s_cipher = System.Text.Encoding.Default.GetString(_cipher);
                    //System.out.println("cipher: "+cipher);
                    if (s_cipher.Equals("3des-cbc"))
                    {
                        _buf.getInt();
                        byte[] foo = new byte[encoded_data.Length - _buf.getOffSet()];
                        _buf.getByte(foo);
                        encoded_data = foo;
                        encrypted    = true;
                        throw new JSchException("unknown privatekey format: " + identity);
                    }
                    else if (s_cipher.Equals("none"))
                    {
                        _buf.getInt();
                        //_buf.getInt();

                        encrypted = false;

                        byte[] foo = new byte[encoded_data.Length - _buf.getOffSet()];
                        _buf.getByte(foo);
                        encoded_data = foo;
                    }
                }

                try
                {
                    file = new FileInfo(identity + ".pub");
                    fis  = File.OpenRead(identity + ".pub");
                    buf  = new byte[(int)(file.Length)];
                    len  = fis.Read(buf, 0, buf.Length);
                    fis.Close();
                }
                catch
                {
                    return;
                }

                if (buf.Length > 4 &&                          // FSecure's public key
                    buf[0] == '-' && buf[1] == '-' && buf[2] == '-' && buf[3] == '-')
                {
                    i = 0;
                    do
                    {
                        i++;
                    }while(buf.Length > i && buf[i] != 0x0a);
                    if (buf.Length <= i)
                    {
                        return;
                    }

                    while (true)
                    {
                        if (buf[i] == 0x0a)
                        {
                            bool inheader = false;
                            for (int j = i + 1; j < buf.Length; j++)
                            {
                                if (buf[j] == 0x0a)
                                {
                                    break;
                                }
                                if (buf[j] == ':')
                                {
                                    inheader = true; break;
                                }
                            }
                            if (!inheader)
                            {
                                i++;
                                break;
                            }
                        }
                        i++;
                    }
                    if (buf.Length <= i)
                    {
                        return;
                    }

                    start = i;
                    while (i < len)
                    {
                        if (buf[i] == 0x0a)
                        {
                            Array.Copy(buf, i + 1, buf, i, len - i - 1);
                            len--;
                            continue;
                        }
                        if (buf[i] == '-')
                        {
                            break;
                        }
                        i++;
                    }
                    publickeyblob = Util.fromBase64(buf, start, i - start);

                    if (type == UNKNOWN)
                    {
                        if (publickeyblob[8] == 'd')
                        {
                            type = DSS;
                        }
                        else if (publickeyblob[8] == 'r')
                        {
                            type = RSA;
                        }
                    }
                }
                else
                {
                    if (buf[0] != 's' || buf[1] != 's' || buf[2] != 'h' || buf[3] != '-')
                    {
                        return;
                    }
                    i = 0;
                    while (i < len)
                    {
                        if (buf[i] == ' ')
                        {
                            break;
                        }
                        i++;
                    }
                    i++;
                    if (i >= len)
                    {
                        return;
                    }
                    start = i;
                    while (i < len)
                    {
                        if (buf[i] == ' ')
                        {
                            break;
                        }
                        i++;
                    }
                    publickeyblob = Util.fromBase64(buf, start, i - start);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Identity: " + e);
                if (e is JSchException)
                {
                    throw (JSchException)e;
                }
                throw new JSchException(e.ToString());
            }
        }