Many times, persistent encryption is required for secret encryption, and 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 tool class (including des encryption and md encryption) * @author mingge * */ public class KeysUtil { privacy e final static String DES = "DES "; private final static String MD = "MD"; private final static String KEY="opeddsaeaddadbcabf"; /** * MD encryption algorithm* @param data * @return */ public st atic 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 ((b ytes[i] & xff) < x ) { bf.append("T"); } bf.append(Long.toString(bytes[i] & xff, )); } return bf.toString(); } /** * Description Encrypts according to 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 Decrypt according to key value* @ param data * @ param key encryption key byte array* @return * @throws IOException * @throws Exception */ public static String desDecrypt(String data, String key) throws IOExc episode, 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.ge tBytes()); return new String( bt); } /** * Description Encrypted according to key value* @param data * @param key Encryption key byte array* @return * @throws Exception */ private static byte[] encrypt(byte[] d ata, byte[] key) throws Exception { // Generate a trusted random number source SecureRandom sr = new SecureRandom(); // Create a DESKeySpec object from the original key data DESKeySpec dks = new DESKeySpec(key); / / Create a key factory, Then use it to convert DESKeySpec to the SecretKey object SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(d ks); // The Cipher object actually completes the encryption operation. Cipher cipher = Cipher.getInstance(DES); // Use Key initialization of the Cipher object 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 random number source SecureRandom sr = new Sec ureRandom(); // From the original Create a DESKeySpec object DESKeySpec dks = new DESKeySpec(key); // Create a key factory, and then use it to convert DESKeySpec into a SecretKey object SecretKeyFactory keyFactory = SecretKe yFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks ); // The Cipher object actually completes the decryption operation Cipher cipher = Cipher.getInstance(DES); // Initialize the Cipher object cipher.init(Cipher.DECRYPT_MODE, securekey, sr); return cipher.do Final(data); } }Below I will introduce a piece of code to implement MD5 encryption and decryption classes in Java
Java implements MD5 encryption and decryption classes, with test classes, see the 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.NoSuc hAlgorithmException; 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 hex string to byte array* @param hex * @return */ p ublic 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 hex string * @param b * @return */ public static String byteToHexString(byte[] b) { StringBuffer hexString = new StringBuffer(); for (in t 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 whether the password is legal* @param password * @param passwordInDb * @return * @throws NoSuchAlgorithmException * @ throws UnsupportedEncodingException */ public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { //Convert the hex string format password into a byte array byte[] pwdInDb = hexStringToByte(password InDb); //Declare the salt variable byte[] salt = new byte[SALT_LENGTH]; // Extract the salt from the password byte array saved in the database System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); //Create the message digest object MessageDigest md = MessageDigest.getInstance("MD5"); //Replace : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : Salt data is passed into the message digest object md.update(salt); //Pass the password data to the message digest object md.update(password.getBytes("UTF-8")); //Create the message digest of the input password byte [] digest = md.digest(); //Declare a variable that holds the message digest of the password in the database byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; //Get the message digest 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)) { //The password correctly returns the password match Message return true; } else { //The password is incorrect and returns the password mismatch message return false; } } /** * Get the encrypted hexadecimal password* @param password * @return * @throws NoSuchAlgorithm Exception * @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(); //Declare salt array variable byte[] salt = new byte[SALT_LENGTH]; //Put random number into the salt variable random.nextBytes(salt); //Declare the message digest object MessageDigest md = null; //Create message digest md = MessageDig est.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 message digest byte[] digest = md.digest(); //Because you want to store salt in the byte array of password, add the byte length of salt pwd = new byte[digest.length + SALT_LENGTH]; //Copy the bytes of the salt to the first 12 bytes of the generated encrypted password byte array, so that the salt System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); // Copy the message digest to the byte array of encrypted password bytes starting from the 13th byte System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); //Convert the password encrypted byte array format to Password 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 log in!!!"); }else{ System.ou t. println("Password error, please re-enter!!!"); } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEn codingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Registered user* * @param userName * @param password */ public static void registerUser(String userName,String pas sword){ String encryptedPwd = null; try { encryptedPwd = MyMD5Util. getEncryptedPwd(password); users.put(userName, encryptedPwd); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.print StackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Verification login* * @param userName * @param password * @return * @throws UnsupportedEncodingException * @throws NoS uchAlgorithmException */ public static boolean loginValid(String userName,String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{ String pwdInDb = (String)users.get(userName); if(null!=pwdInDb){ // This user exists return MyMD5Util.validPassword(pa ssword, pwdInDb); }else{ System.out.println(" does not exist This user! ! ! "); return false; } } }