Home>

Many times, the secret is encrypted persistently,The encryption at this time uses md5. When using symmetric encryption, the des method is used

import java.io.ioexception;
  import java.security.messagedigest;
  import java.security.securerandom;
  import javax.crypto.cipher;
  import javax.crypto.secretkey;
  import javax.crypto.secretkeyfactory;
  import javax.crypto.spec.deskeyspec;
 import sun.misc.basedecoder;
 import sun.misc.baseencoder;
 /**
  * Key tools (including des encryption and md encryption)
  * @author mingge
  *
  * /
 public class keysutil {
     private final static string des="des";
     private final static string md="md";
     private final static string key="opeddsaeaddadbcabf";
     /**
      * md encryption algorithm
      * @param data
      * @return
      * /
     public static string mdencrypt (string data) {
       string resultstring=null;
       try {
         resultstring=new string (data);
         messagedigest md=messagedigest.getinstance (md);
         resultstring=bytehexstring (md.digest (resultstring.getbytes ()));
       } catch (exception ex) {
       }
       return resultstring;
     }
     private static string bytehexstring (byte [] bytes) {
       stringbuffer bf=new stringbuffer (bytes.length *);
       for (int i =;i<bytes.length;i ++) {
         if ((bytes [i]&xff)&x;{
           bf.append ("t");
         }
         bf.append (long.tostring (bytes [i]&xff,));
       }
       return bf.tostring ();
     }
     /**
      * description is encrypted based on key value
      * @param data
      * @param key encryption key byte array
      * @return
      * @throws exception
      * /
     public static string desencrypt (string data, string key) throws exception {
       if (key == null) {
         key=key;
       }
       byte [] bt=encrypt (data.getbytes (), key.getbytes ());
       string strs=new baseencoder (). encode (bt);
       return strs;
     }
     /**
      * description decryption based on key value
      * @param data
      * @param key encryption key byte array
      * @return
      * @throws ioexception
      * @throws exception
      * /
     public static string desdecrypt (string data, string key) throws ioexception,         exception {
       if (data == null) {
         return null;
       }
       if (key == null) {
         key=key;
       }
       basedecoder decoder=new basedecoder ();
       byte [] buf=decoder.decodebuffer (data);
       byte [] bt=decrypt (buf, key.getbytes ());
       return new string (bt);
     }
     /**
      * description is encrypted based on key value
      * @param data
      * @param key encryption key byte array
      * @return
      * @throws exception
      * /
     private static byte [] encrypt (byte [] data, byte [] key) throws exception {
       //generate a trusted source of random numbers
       securerandom sr=new securerandom ();
       //create deskeyspec object from raw key data
       deskeyspec dks=new deskeyspec (key);
       //create a key factory,Then use it to convert the deskeyspec into a secretkey object
       secretkeyfactory keyfactory=secretkeyfactory.getinstance (des);
       secretkey securekey=keyfactory.generatesecret (dks);
       //The cipher object actually completes the encryption operation
       cipher cipher=cipher.getinstance (des);
       //initialize the cipher object with the key
       cipher.init (cipher.encrypt_mode, securekey, sr);
       return cipher.dofinal (data);
     }
     /**
     * description decryption based on key value
     * @param data
     * @param key encryption key byte array
     * @return
     * @throws exception
     * /
     private static byte [] decrypt (byte [] data, byte [] key) throws exception {
       //generate a trusted source of random numbers
       securerandom sr=new securerandom ();
       //create deskeyspec object from raw key data
       deskeyspec dks=new deskeyspec (key);
       //create a key factory,Then use it to convert the deskeyspec into a secretkey object
       secretkeyfactory keyfactory=secretkeyfactory.getinstance (des);
       secretkey securekey=keyfactory.generatesecret (dks);
       //The cipher object actually completes the decryption operation
       cipher cipher=cipher.getinstance (des);
       //initialize the cipher object with the key
       cipher.init (cipher.decrypt_mode, securekey, sr);
       return cipher.dofinal (data);
     }
 }

The following introduces a piece of code for java to implement md5 encryption and decryption class

java implements md5 encryption and decryption classes,With test class,See code for details.

md5 encryption and decryption class-mymd5util, the code is as follows:

package com.zyg.security.md5;
import java.io.unsupportedencodingexception;
import java.security.messagedigest;
import java.security.nosuchalgorithmexception;
import java.security.securerandom;
import java.util.arrays;
public class mymd5util {
  private static final string hex_nums_str="0123456789abcdef";
  private static final integer salt_length=12;
  /**
   * Convert hexadecimal string to byte array
   * @param hex
   * @return
   * /
  public static byte [] hexstringtobyte (string hex) {
    int len ​​= (hex.length ()/2);
    byte [] result=new byte [len];
    char [] hexchars=hex.tochararray ();
    for (int i=0;i<len;i ++) {
      int pos=i * 2;
      result [i]=(byte) (hex_nums_str.indexof (hexchars [pos])<<4
              | hex_nums_str.indexof (hexchars [pos + 1]));
    }
    return result;
  }
  /**
   * Convert the specified byte array into a hexadecimal string
   * @param b
   * @return
   * /
  public static string bytetohexstring (byte [] b) {
    stringbuffer hexstring=new stringbuffer ();
    for (int i=0;i<b.length;i ++) {
      string hex=integer.tohexstring (b [i]&0xff);
      if (hex.length () == 1) {
        hex="0" + hex;
      }
      hexstring.append (hex.touppercase ());
    }
    return hexstring.tostring ();
  }
  /**
   * Verify password is valid
   * @param password
   * @param passwordindb
   * @return
   * @throws nosuchalgorithmexception
   * @throws unsupportedencodingexception
   * /
  public static boolean validpassword (string password, string passwordindb)
      throws nosuchalgorithmexception, unsupportedencodingexception {
    //Convert password in hex string format into byte array
    byte [] pwdindb=hexstringtobyte (passwordindb);
    //Declaring the salt variable
    byte [] salt=new byte [salt_length];
    //Extract the salt from the password byte array stored in the database
    system.arraycopy (pwdindb, 0, salt, 0, salt_length);
    //Create a message summary object
    messagedigest md=messagedigest.getinstance ("md5");
    //Pass salt data into the message digest object
    md.update (salt);
    //Pass the password data to the message digest object
    md.update (password.getbytes ("utf-8"));
    //Generate a message digest for the entered password
    byte [] digest=md.digest ();
    //Declare a variable that holds the password message digest in the database
    byte [] digestindb=new byte [pwdindb.length-salt_length];
    //Get the message summary of the password in the database
    system.arraycopy (pwdindb, salt_length, digestindb, 0, digestindb.length);
    //Compare whether the message digest generated based on the input password is the same as the message digest in the database
    if (arrays.equals (digest, digestindb)) {
      //Password returns password match message correctly
      return true;
    } else {
      //Password is incorrect. Password mismatch is returned.
      return false;
    }
  }
  /**
   * Get encrypted hexadecimal password
   * @param password
   * @return
   * @throws nosuchalgorithmexception
   * @throws unsupportedencodingexception
   * /
  public static string getencryptedpwd (string password)
      throws nosuchalgorithmexception, unsupportedencodingexception {
    //Declare the encrypted password array variable
    byte [] pwd=null;
    //random number generator
    securerandom random=new securerandom ();
    //Declaring a salt array variable
    byte [] salt=new byte [salt_length];
    //Put a random number into a salt variable
    random.nextbytes (salt);
    //Declaration message summary object
    messagedigest md=null;
    //Create a message summary
    md=messagedigest.getinstance ("md5");
    //Pass salt data into the message digest object
    md.update (salt);
    //Pass the password data to the message digest object
    md.update (password.getbytes ("utf-8"));
    //Get the byte array of the message summary
    byte [] digest=md.digest ();
    //Because i want to store the salt in the byte array of the password,So add the byte length of the salt
    pwd=new byte [digest.length + salt_length];
    //Copy the bytes of salt to the first 12 bytes of the generated encrypted password byte array, in order to remove the salt when verifying the password
    system.arraycopy (salt, 0, pwd, 0, salt_length);
    //Copy the message digest to the byte of the encrypted password byte array starting from the 13th byte
    system.arraycopy (digest, 0, pwd, salt_length, digest.length);
    //Convert the password encrypted in byte array format into a password in hexadecimal string format
    return bytetohexstring (pwd);
  }
}

Test class-client, the code is as follows:

package com.zyg.security.md5;
import java.io.unsupportedencodingexception;
import java.security.nosuchalgorithmexception;
import java.util.hashmap;
import java.util.map;
public class client {
  private static map users=new hashmap ();
  public static void main (string [] args) {
    string username="zyg";
    string password="123";
    registeruser (username, password);
    username="changong";
    password="456";
    registeruser (username, password);
    string loginuserid="zyg";
    string pwd="1232";
    try {
      if (loginvalid (loginuserid, pwd)) {
        system.out.println ("Welcome to login !!!");
      } else {
        system.out.println ("Password error,please enter again! !! !! ");
      }
    } catch (nosuchalgorithmexception e) {
      //todo auto-generated catch block
      e.printstacktrace ();
    } catch (unsupportedencodingexception e) {
      //todo auto-generated catch block
      e.printstacktrace ();
    }
  }
  /**
   * registered user
   *
   * @param username
   * @param password
   * /
  public static void registeruser (string username, string password) {
    string encryptedpwd=null;
    try {
      encryptedpwd=mymd5util.getencryptedpwd (password);
      users.put (username, encryptedpwd);
    } catch (nosuchalgorithmexception e) {
      //todo auto-generated catch block
      e.printstacktrace ();
    } catch (unsupportedencodingexception e) {
      //todo auto-generated catch block
      e.printstacktrace ();
    }
  }
  /**
   * Verify login
   *
   * @param username
   * @param password
   * @return
   * @throws unsupportedencodingexception
   * @throws nosuchalgorithmexception
   * /
  public static boolean loginvalid (string username, string password)
        throws nosuchalgorithmexception, unsupportedencodingexception {
    string pwdindb=(string) users.get (username);
    if (null!=pwdindb) {//the user exists
        return mymd5util.validpassword (password, pwdindb);
    } else {
      system.out.println ("The user does not exist !!!");
      return false;
    }
  }
}
  • Previous Thinkphp unlimited classification code
  • Next Javascript send SMS verification code implementation code