The idea of ​​java implementation of ssh mode encryption is shared with everyone.

First, ssh encryption principle

ssh first tells the server a symmetric encrypted password through asymmetric encryption.When verifying the username and password,Encrypt and decrypt using encryption passwords already known to both parties,See below:

Explanation:Why use asymmetric encryption in ssh,Again using symmetric encryption,What's so useful?Is it safe or not?Since symmetric encryption was later used,Why use asymmetric encryption at the beginning?In turn, since asymmetric encryption is used,Why use symmetric encryption again?

Asymmetric encryption,Is to pass the 256-bit random password generated by the client to the server,Then in the process of transmission,Encrypted using a public key,In this way, this 256-bit encrypted password is difficult to be cracked on the network.

Symmetric encryption,Because frequent use of asymmetric encryption is very wasteful of performance,Then ssh uses a 256-bit password as the encryption password for the next pass in the username and passwordThe difficulty of cracking,Everyone knows it,There are 0-9 variations on each bit.

Is this safeI think it's still very good,The specific use is also easy to understand.

Second, my ssh encryption principle

① 、 Use scene

The project I develop is a block futures trading.Mainly serves exchanges,This creates a demand that is,We need to control the period in which our exchange uses our software.In other words, our project has a backdoor,Used to control the cycle of the project,If the cycle of software use by the exchange comes,Then if he does n’t renew the fee,The code of the project is deployed on the server of others,At this point we have a hard time controlling,But with this backdoor,The software will automatically stop after expiration,This way you don't worry about the exchange not giving us money.

② How to use

The item code we give to the transaction contains a backdoor,The backdoor sends a request to the web service through the webservice client.

After the web service receives the request,Return the information needed by the client.

In the above process,Will generate an ssh encrypted request method,Allow me to express it with a poor picture.

Third, my ssh implementation

Now that i want to use a webservice, you need to set up a web service and a web service client. In this regard,I don't want to say too much for the time being,There are many ways,I won't mislead everyone here.I got it through eclipse, refer to the communication between webservices.

Next, I will introduce the code,But given the length of the issue,I will not post some unnecessary code,The key is to explain this principle clearly.

①, service


public byte [] request (string param, string resulttype) {
  logger.info ("request parameter:" + param);
  //return object
  keyresult keyresult=new keyresult ();
  try {
    //Get the public key first
    if (resulttype.equals (public_key_result_type)) {
      map<string, object>keymap=rsacoder.initkey ();
      //Generate public and private keys
      privatekey=rsacoder.getprivatekey (keymap);
      keyresult.setkey (rsacoder.getpublickey (keymap));
      logger.info ("Public Key String:" + keyresult.getkey ());
      logger.info ("Private Key String:" + privatekey);
    } else if (resulttype.equals (echostr_result_type)) {
      //Set the client's password information
      byte [] parambyte=new base64decoder (). decodebuffer (param);
      echostr=new string (rsacoder.decryptbyprivatekey (parambyte, privatekey));
    } else {
      //Get the permission information of the exchange through the database.
      //first convert the request to a byte array, and then decrypt it,Finally converted to a string
      exchangeinfo info=exchangeinfo.dao.getinfobyname (new string (cryptutil.decrypt (
          new base64decoder (). decodebuffer (param), echostr.getbytes ())));
      string result="";
      //Get system enable permissions
      if (resulttype.equals (privilege_result_type)) {
        //first determine the use permissions
        //judging the use date
        //Compare the current date and start date of the current login with the login,Then calculate the dates that are still available
        long time=(new date (). gettime ()/1000)-string2dateint (openday);
        //converted to days
        int day=(int) (time/(60 * 60 * 24));
        //days available
        if (usedays-day>0) {
          //can use
        } else {
          //Not available
      keyresult.setresult (cryptutil.encrypt (result.getbytes (), echostr.getbytes ()));
    return jsonutil.objecttobyte (keyresult);
  } catch (exception e) {
    logger.error ("Webservice went wrong !!!");
    logger.error (e.getmessage (), e);
  return null;

To repeat:

The content of the first judgment statement is to generate the public and private keys.And return the public key.

The content of the second judgment statement is to save the random string sent by the client.This step is critical.The random string is first encrypted with the public key,This greatly strengthens the depth of encryption.

The content of the third judgment statement is to encrypt the permissions of the client through a random string.

②, client


public static boolean canrunforexchange (string resulttype) {
  int i=1;
  boolean result=false;
  while (true) {
    try {
      //webservice calling class
      exchangeserviceproxy proxy=new exchangeserviceproxy ();
      base64encoder encoder=new base64encoder ();
      //step1. Get the public key generated by the service
      keyresult keyresult=jsonutil.bytetoobject (proxy.request (null, public_key_result_type),          keyresult.class);
      //step2. Generate a random string,Send to webserivce
      string echostr=strutil.getechostrbylength (10);
      byte [] echobyteparam=rsacoder.encryptbypublickey (echostr.getbytes (), keyresult.getkey ());
      proxy.request (encoder.encode (echobyteparam), echostr_result_type);
      //step3. Encrypt client request information,Then send to webservice
      //First encrypt to byte array and then convert to string
      byte [] results=proxy.request (
          encoder.encode (cryptutil.encrypt (constants.client_type.getbytes (), echostr.getbytes ())),          resulttype);
      keyresult=jsonutil.bytetoobject (results, keyresult.class);
      //step4. Decrypt the server return message by password
      string response=new string (cryptutil.decrypt (keyresult.getresult (), echostr.getbytes ()));
      if (response.equals ("1")) {
    } catch (exception e) {
      logger.debug ("No." + i + "Failed to load webservice");
      i ++;
      logger.error (e.getmessage (), e);
      if (i>= 10) {
  return result;

A little explanation:

The main purpose of the loop is to prevent the service from continuously sending requests when the network is disconnected.A maximum of 10 times is enough.

There are four main steps.What I want to explain in the comments is OK.

③, shared encryption and decryption public class


package com.honzh.socket.util;
import javax.crypto.cipher;
import javax.crypto.secretkey;
import javax.crypto.secretkeyfactory;
import javax.crypto.spec.deskeyspec;
import javax.crypto.spec.ivparameterspec;
public class cryptutil {
  * @title:encrypt
  * @description:encryption
  * @param data
  * @param key
  * @return
  * @throws exception
  * /
  public static byte [] encrypt (byte [] data, byte [] key) throws exception {
    key=get8 (key);
    cipher cipher=cipher.getinstance ("des/cbc/pkcs5padding");
    deskeyspec deskeyspec=new deskeyspec (key);
    secretkeyfactory keyfactory=secretkeyfactory.getinstance ("des");
    secretkey secretkey=keyfactory.generatesecret (deskeyspec);
    ivparameterspec iv=new ivparameterspec (key);
    cipher.init (cipher.encrypt_mode, secretkey, iv);
    return cipher.dofinal (data);
  * @title:decrypt
  * @description:Decrypt
  * @param data
  * @param key
  * @return
  * @throws exception
  * /
  public static byte [] decrypt (byte [] data, byte [] key) throws exception {
    key=get8 (key);
    cipher cipher=cipher.getinstance ("des/cbc/pkcs5padding");
    deskeyspec deskeyspec=new deskeyspec (key);
    secretkeyfactory keyfactory=secretkeyfactory.getinstance ("des");
    secretkey secretkey=keyfactory.generatesecret (deskeyspec);
    ivparameterspec iv=new ivparameterspec (key);
    cipher.init (cipher.decrypt_mode, secretkey, iv);
    return cipher.dofinal (data);
  private static byte [] get8 (byte [] key) {
    byte [] key1=new byte [8];
    for (int i=0;i<8;i ++) {
      key1 [i]=key [i];
    return key1;
  public static string tohexstring (byte [] data) {
    string s="";
    for (int i=0;i<data.length;i ++) {
      s +=integer.tohexstring (data [i]&0xff) + "-";
    return s;

In general,Sha and md5 encryption are enough for us to use!

As for other auxiliary classes, I will not introduce more.There are many resources onlineHope everyone can learn together.

  • Previous Detailed configuration of adding an authentication password for a website or directory in the Nginx server
  • Next jQuery formValidator