Java MD5, base64, AES encryption tools

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang.StringUtils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**

  • ClassName: EncryptUtil
  • @Description: 1. Encryption tools byte [] hex string into various 2.base 64 encode 3.base 64 decode
  •           4.获取byte[]的md5值 5.获取字符串md5值 6.结合base64实现md5加密 7.AES加密
  •           8.AES加密为base 64 code 9.AES解密 10.将base 64 code AES解密
  • @author JornTang
  • @email [email protected]
  • @date 2017 Nian 8 Yue 23 Ri
    * /
    public class EncryptUtil {

    public static String encodePassword(String password) throws UnsupportedEncodingException {
    if (StringUtils.isEmpty(password)) {
    return password;
    }
    return getMD5(password.getBytes("utf-8"));
    }

    getMD5 static String public (byte [] Source) {
    String S = null;
    char hexdigits [] = {// for converting byte hexadecimal character representation to
    '0', '1', '2', ' 3 ',' 4 ',' 5 ',' 6 ',' 7 ',' 8 ',' 9 ',' a ',' b ',' c ',' d ',' e ',' f ' };
    the try {
    the java.security.MessageDigest java.security.MessageDigest.getInstance MD = ( "the MD5");
    md.update (Source);
    byte tmp [] = md.digest (); // MD5 calculation result is a 128 bits long integer,
    // in bytes is 16 bytes,
    char str [] = new char [ 16 * 2]; // hexadecimal representation of each byte words, two characters,
    // Therefore, expressed as hexadecimal characters requires 32
    int k = 0; // represents the conversion result in the corresponding character position
    for (int i = 0; i <16;i ++) {// start from the first byte of each byte of MD5
    // converter 16 is converted into a hexadecimal character
    byte byte0 = tmp [i]; // i take the first byte
    str [k ++] = hexDigits [byte0 >>> 4 & 0xf ]; // get the high byte of the 4-digital conversion,
    // logical shift right >>> to the right with the sign bit
    str [k ++] = hexDigits [ byte0 & 0xf]; // get low byte 4 digitizer
    }
    S = new new String (STR); / results / after changing into a string

     } catch (Exception e) {
         e.printStackTrace();
     }
     return s;

    }

    public final static String MD5 (String inputStr ) {
    character for encryption //
    char md5String [] = { '0 ', '1', '2', '3', '4', '5', '6' , '. 7', '. 8', '. 9', 'A', 'B', 'C', 'D', 'E', 'F.'};
    the try {
    // use this utf-8 character set String encoded as byte sequences, storing the result into a byte array new
    byte [] btInput = inputStr.getBytes ( " utf-8");

         // 信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。
         MessageDigest mdInst = MessageDigest.getInstance("MD5");
    
         // MessageDigest对象通过使用 update方法处理数据, 使用指定的byte数组更新摘要
         mdInst.update(btInput);
    
         // 摘要更新之后,通过调用digest()执行哈希计算,获得密文
         byte[] md = mdInst.digest();
    
         // 把密文转换成十六进制的字符串形式
         int j = md.length;
         char str[] = new char[j * 2];
         int k = 0;
         for (int i = 0; i < j; i++) { // i = 0
             byte byte0 = md[i]; // 95
             str[k++] = md5String[byte0 >>> 4 & 0xf]; // 5
             str[k++] = md5String[byte0 & 0xf]; // F
         }
    
         // 返回经过加密后的字符串
         return new String(str);
    
     } catch (Exception e) {
         return null;
     }

    }

    public static String encryption(String plain) throws UnsupportedEncodingException {
    String re_md5 = new String();
    try {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(plain.getBytes("utf-8"));
    byte b[] = md.digest();

         int i;
    
         StringBuffer buf = new StringBuffer("");
         for (int offset = 0; offset < b.length; offset++) {
             i = b[offset];
             if (i < 0)
                 i += 256;
             if (i < 16)
                 buf.append("0");
             buf.append(Integer.toHexString(i));
         }
    
         re_md5 = buf.toString();
    
     } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
     }
     return re_md5;

    }

    public static String getMD5(String message) {
    String md5 = "";
    try {
    // Create a MD5 instance
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] messageByte = message.getBytes("UTF-8");
    // get md5 byte array
    byte[] md5Byte = md.digest(messageByte);
    // switch to Hex
    md5 = bytesToHex(md5Byte);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return md5;
    }

    /**
    • @param bytes
    • @return
      */
      public static String bytesToHex(byte[] bytes) {
      StringBuffer hexStr = new StringBuffer();
      int num;
      for (int i = 0; i < bytes.length; i++) {
      num = bytes[i];
      if (num < 0) {
      num += 256;
      }
      if (num < 16) {
      hexStr.append("0");
      }
      hexStr.append(Integer.toHexString(num));
      }
      return hexStr.toString().toUpperCase();
      }
    /**
    • The byte [] into a variety of binary string
    • @param bytes
    •        byte[]
    • @param radix
    •        可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制
    • @return the converted string
      * /
      public static String binary (byte [] bytes, the radix int) {
      return new new a BigInteger (1, bytes) .toString (the radix); // here represents a positive number
      }
    /**
    • base 64 encode
    • @param bytes
    •        待编码的byte[]
    • @return 编码后的base 64 code
      */
      public static String base64Encode(byte[] bytes) {
      return new BASE64Encoder().encode(bytes);
      }
    /**
    • base 64 decode
    • @param base64Code
    •        待解码的base 64 code
    • byte [] decoded after @return
    • @throws Exception
      */
      public static byte[] base64Decode(String base64Code) throws Exception {
      return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
      }
    /**
    • Get byte [] value of md5
    • @param bytes
    •        byte[]
    • @return md5
    • @throws Exception
      */
      public static byte[] md5(byte[] bytes) throws Exception {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(bytes);
      return md.digest();
      }
    /**
    • Gets the string value md5
    • @param msg
    • @return md5
    • @throws Exception
      */
      public static byte[] md5(String msg) throws Exception {
      return StringUtils.isEmpty(msg) ? null : md5(msg.getBytes());
      }
    /**
    • Combined to achieve base64 md5 encryption
    • @param msg
    •        待加密字符串
    • After obtaining @return into base64 md5
    • @throws Exception
      */
      public static String md5Encrypt(String msg) throws Exception {
      return StringUtils.isEmpty(msg) ? null : base64Encode(md5(msg));
      }
    /**
    • AES encryption
    • @param content
    •        待加密的内容
    • @param encryptKey
    •        加密密钥
    • Encrypted byte [] @return
    • @throws Exception
      */
      public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
      random.setSeed(encryptKey.getBytes());
      kgen.init(128, random);

      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));

      return cipher.doFinal(content.getBytes("utf-8"));
      }

    /**
    • AES encryption to base 64 code
    • @param content
    •        待加密的内容
    • @param encryptKey
    •        加密密钥
    • @return the base 64 code encryption
    • @throws Exception
      */
      public static String aesEncrypt(String content, String encryptKey) throws Exception {
      return base64Encode(aesEncryptToBytes(content, encryptKey));
      }
    /**
    • AES decryption
    • @param encryptBytes
    •        待解密的byte[]
    • @param decryptKey
    •        解密密钥
    • After the decryption @return String
    • @throws Exception
      */
      public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
      random.setSeed(decryptKey.getBytes());
      kgen.init(128, random);

      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
      byte[] decryptBytes = cipher.doFinal(encryptBytes);

      return new String(decryptBytes);
      }

    /**
    • The base 64 code AES decryption
    • @param encryptStr
    •        待解密的base 64 code
    • @param decryptKey
    •        解密密钥
    • @return string after decryption
    • @throws Exception
      */
      public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
      return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
      }
    /**
    • Randomly generated secret key
      /
      public static String getKey () {
      the try {
      the KeyGenerator kg = KeyGenerator.getInstance ( "the AES");
      kg.init (128);
      // how many bits to be generated, only need to modify this to 128, or 192 256
      a SecretKey kg.generateKey SK = ();
      byte [] sk.getEncoded B = ();
      String byteToHexString S = (B);
      System.out.println (S);
      System.out.println ( "hex-tight key length is "+ s.length ());
      System.out.println (" length of the binary key is "+ s.length ()
      . 4);
      return S;
      } the catch (NoSuchAlgorithmException E) {
      e.printStackTrace () ;
      System.out.println ( "no algorithm.");
      }
      return null;
      }
    /**
    • Generating a string using the specified secret key
      * /
      public static String getKeyByPass (String Pass) {
      // generates a secret key
      the try {
      the KeyGenerator kg = KeyGenerator.getInstance ( "the AES");
      // kg.init (128); // To how many generation, only need to modify here to 128, 192 or 256
      // SecureRandom is to generate secure random number sequence, password.getBytes () is a seed, as long as the same seed sequence is the same, so as to generate a secret key.
      SK = kg.generateKey a SecretKey ();
      a SecureRandom SecureRandom.getInstance = Random ( "SHA1PRNG");
      random.setSeed (pass.getBytes ());
      kg.init (128, Random);
      byte [] B = sk.getEncoded ( );
      String byteToHexString S = (B);
      return S;
      } the catch (NoSuchAlgorithmException E) {
      e.printStackTrace ();
      System.out.println ( "no algorithm.");
      }
      return null;
      }
    /**
    • byte array into a hexadecimal character string
    • @param bytes
    • @return
      */
      public static String byteToHexString(byte[] bytes) {
      StringBuffer sb = new StringBuffer();
      for (int i = 0; i < bytes.length; i++) {
      String strHex = Integer.toHexString(bytes[i]);
      if (strHex.length() > 3) {
      sb.append(strHex.substring(6));
      } else {
      if (strHex.length() < 2) {
      sb.append("0" + strHex);
      } else {
      sb.append(strHex);
      }
      }
      }
      return sb.toString();
      }

    // 得到随机字符
    public static String randomStr(int n) {
    // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
    String str1 = "123456789012345678901234567890";
    String str2 = "";
    int len = str1.length() - 1;
    double r;
    for (int i = 0; i < n; i++) {
    r = (Math.random()) * len;
    str2 = str2 + str1.charAt((int) r);
    }
    return str2;
    }

    // 得到随机密码
    public static String randomForPwd(int n) {
    String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    String str2 = "";
    int len = str1.length() - 1;
    double r;
    for (int i = 0; i < n; i++) {
    r = (Math.random()) * len;
    str2 = str2 + str1.charAt((int) r);
    }
    return str2;
    }

    /**
    • 支持前后端加解密
      */
      public static String encrypt(String encryContent, String encryKey) throws Exception {
      try {
      String data = encryContent;
      String key = encryKey;
      String iv = encryKey;

       Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
       int blockSize = cipher.getBlockSize();
      
       byte[] dataBytes = data.getBytes();
       int plaintextLength = dataBytes.length;
       if (plaintextLength % blockSize != 0) {
           plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
       }
      
       byte[] plaintext = new byte[plaintextLength];
       System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
      
       SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
       IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
      
       cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
       byte[] encrypted = cipher.doFinal(plaintext);
      
       return new sun.misc.BASE64Encoder().encode(encrypted);
      } catch (Exception e) {
      e.printStackTrace();
      return null;
      }
      }
      /**
    • The front and rear ends to support encryption and decryption
      * /
      public static String decryEncrypt (decryContent String, String decryKey) throws Exception {
      the try
      {
      String Data = decryContent;
      String Key = decryKey;
      String = decryKey IV;

       byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
      
       Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
       SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
       IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
      
       cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
      
       byte[] original = cipher.doFinal(encrypted1);
       String originalString = new String(original);
       return originalString;
      }
      catch (Exception e) {
      e.printStackTrace();
      return null;
      }
      }
      public static String sss(String myString){
      String newString=null;
      Pattern CRLF = Pattern.compile("(\r\n|\r|\n|\n\r)");
      Matcher m = CRLF.matcher(myString);
      if (m.find()) {
      newString = m.replaceAll("");
      }
      return newString;
      }
      /**
    • @param args
    • @throws Exception
      /
      public static void main(String[] args) throws Exception {
      /
      • String x = SeqUtil.getUUID (); System.err.println ( "encrypted content:" +
      • "18-1D-EA-A2-DC-F3"); //String y = aesEncrypt(x,
      • "b8d7b4820efb517e460c925f436a60f6");
      • System.err.println (getMD5 ( "18-1D-EA-A2-DC-F3")); //System.err.println ( "decrypted:"
        • aesDecrypt(y, "b8d7b4820efb517e460c925f436a60f6")); // String
      • newStr=sss(aaa); // System.out.println(newStr);
        */ String x = "00-FF-9A-6C-60-B8";
        String md5 = EncryptUtil.getMD5(x);
        System.err.println(md5);
        }
        }

Author: Yun soft Technology - File Management System JornTang (micro letter of the same number)

Guess you like

Origin www.cnblogs.com/jorntang/p/12045165.html