最近接触jsch这个包,发现在默认情况下,jsch登录ssh的时候,协商的加密算法和mac算法都不是最高优先级的,这个时候需要手动配置一下算法列表,将强度高的调整在算法列表的前面,这样ssh链接的时候,如果双方都,就会协商成高优先级算法。代码参数jsch的示例,只是添加了一个配置文件,通过wireshark抓包来观测配置前后的变化。
官方说明参考下面的网址,这里面有些算法列表和最新版本实际可支持算法不一致,通过wireshark查看jsch发出的消息,遍可以得到完整的算法列表:
http://epaul.github.io/jsch-documentation/javadoc/com/jcraft/jsch/JSch.html#config-others
测试结果:
默认不配置:
配置算法列表:
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import java.io.InputStream; import java.util.Properties; import com.jcraft.jsch.*; public class jschSample { public static void main(String[] args) { // TODO Auto-generated method stub Properties p = new Properties(); p.setProperty("cipher.s2c", "aes256-ctr,aes192-ctr,aes128-ctr"); p.setProperty("cipher.c2s", "aes256-ctr,aes192-ctr,aes128-ctr"); p.setProperty("mac.s2c", "hmac-sha2,hmac-sha1"); p.setProperty("mac.c2s", "hmac-sha2,hmac-sha1"); p.setProperty("kex", "ecdh-sha2-nistp256"); p.setProperty("StrictHostKeyChecking", "no"); try { JSch jsch=new JSch(); Session session=jsch.getSession("pi", "192.168.1.7", 22); session.setConfig(p); session.setPassword("raspberry"); session.connect(); Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand("pwd"); channel.setInputStream(null); InputStream in=channel.getInputStream(); channel.connect(); byte[] tmp=new byte[1024]; while(true){ while(in.available()>0){ int i=in.read(tmp, 0, 1024); if(i<0)break; System.out.print(new String(tmp, 0, i)); } if(channel.isClosed()){ if(in.available()>0) continue; System.out.println("exit-status: "+channel.getExitStatus()); break; } try{Thread.sleep(1000);}catch(Exception ee){} } channel.disconnect(); session.disconnect(); } catch(Exception e) { System.out.println(e); } } } |
捕获到的jsch0.1.55版本消息算法列表如下(encryption_algorithms/mac_algorithms算法s2c和c2s是一样的):
kex_algorithms string:
ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
server_host_key_algorithms string:
ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
encryption_algorithms_client_to_server string:
aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
mac_algorithms_client_to_server string:
hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96