Java implementation of DES encryption and decryption md5 encryption and Java implementation of md5 encryption decryption class

  • 2020-04-01 04:20:26
  • OfStack

A lot of time to the secret to persist the encryption, the use of md5 encryption. The use of symmetric encryption when the use of DES method


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;
 
 public class KeysUtil {
     private final static String DES = "DES";
     private final static String MD = "MD";
     private final static String KEY="opeddsaeaddadbcabf";
     
     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();
     }
     
     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;
     }
     
     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);
     }
     
     private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
       //Generate a trusted random number source
       SecureRandom sr = new SecureRandom();
       //Create the DESKeySpec object from the original key data
       DESKeySpec dks = new DESKeySpec(key);
       //Create a key factory and use it to transform the DESKeySpec into a SecretKey object
       SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
       SecretKey securekey = keyFactory.generateSecret(dks);
       //A Cipher object actually does the encryption
       Cipher cipher = Cipher.getInstance(DES);
       //Initializes a Cipher object with a key
       cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
       return cipher.doFinal(data);
     }
     
     private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
       //Generate a trusted random number source
       SecureRandom sr = new SecureRandom();
       //Create the DESKeySpec object from the original key data
       DESKeySpec dks = new DESKeySpec(key);
       //Create a key factory and use it to transform the DESKeySpec into a SecretKey object
       SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
       SecretKey securekey = keyFactory.generateSecret(dks);
       //A Cipher object actually does the decryption
       Cipher cipher = Cipher.getInstance(DES);
       //Initializes a Cipher object with a key
       cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
       return cipher.doFinal(data);
     }
 }

The following is to introduce a section of code about the Java implementation of MD5 encryption decryption class

Java to achieve MD5 encryption and decryption class, with a test class, see the code.

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; 
   
  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; 
  } 
   
  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(); 
  } 
   
  public static boolean validPassword(String password, String passwordInDb) 
      throws NoSuchAlgorithmException, UnsupportedEncodingException { 
    //Converts a password in hexadecimal string format into a byte array
    byte[] pwdInDb = hexStringToByte(passwordInDb); 
    //Declare 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 digest object
    MessageDigest md = MessageDigest.getInstance("MD5"); 
    //Pass the salt data into the message digest object
    md.update(salt); 
    //Passes the password data to the message digest object
    md.update(password.getBytes("UTF-8")); 
    //Generates a message digest for the input password
    byte[] digest = md.digest(); 
    //Declare a variable that holds a digest of password messages in the database
    byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; 
    //Gets the message digest for 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 correctly returns a password matching message
      return true; 
    } else { 
      //Incorrect password returns a password mismatch message
      return false; 
    } 
  } 
   
  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(); 
    //Declare the salt array variable
    byte[] salt = new byte[SALT_LENGTH]; 
    //Put the random number into the salt variable
    random.nextBytes(salt); 
    //Declare the message digest object
    MessageDigest md = null; 
    //Create message digest
    md = MessageDigest.getInstance("MD5"); 
    //Pass the salt data into the message digest object
    md.update(salt); 
    //Passes the password data to the message digest object
    md.update(password.getBytes("UTF-8")); 
    //Gets an array of bytes for the message digest
    byte[] digest = md.digest(); 
    //Because you want to store salt in the password's byte array, add the length of the salt bytes
    pwd = new byte[digest.length + SALT_LENGTH]; 
    //Copy the bytes of the salt into the first 12 bytes of the generated array of encrypted password bytes to remove the salt when the password is validated
    System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); 
    //Copies the message digest into the encrypted password byte array starting at byte 13
    System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); 
    //Converts an encrypted password in byte array format to a password in hexadecimal string format
    return byteToHexString(pwd); 
  } 
} 

The 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(); 
    }  
  } 
   
  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(); 
    } 
  } 
   
  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(" This user does not exist!! "); 
      return false; 
    } 
  } 
} 

Related articles: