Java encryption and decryption tool (for JavaSE and JavaEE and Android)

  • 2020-05-09 18:33:26
  • OfStack

In this paper, we share an Java encryption and decryption tool applicable to JavaSE/JavaEE/Android for everyone to learn, the specific content is as follows


package longshu.utils.security;
 
import java.lang.reflect.Method;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
 
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
 
/**
 * Java Encryption and decryption tool .
 * JavaSE/JavaEE/Android Are applicable 
 * 
 * @author longshu 2016 years 4 month 13 day 
 */
public class EncryptDecrypt {
 //  You don't have to create an object 
 private EncryptDecrypt() {
 }
 
 /**
  * SHA1 encryption Bit data 
  * @param source byte An array of 
  * @return  The encrypted byte An array of 
  */
 public static byte[] SHA1Bit(byte[] source) {
  try {
   MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
   sha1Digest.update(source);
   byte targetDigest[] = sha1Digest.digest();
   return targetDigest;
  } catch (NoSuchAlgorithmException e) {
   throw new RuntimeException(e);
  }
 }
 
 /**
  * SHA1 Encrypted string data 
  * @param source  The string to encrypt 
  * @return  The encrypted string 
  */
 public static String SHA1(String source) {
  return byte2HexStr(SHA1Bit(source.getBytes()));
 }
 
 /**
  * MD5 encryption Bit data 
  * @param source byte An array of 
  * @return  The encrypted byte An array of 
  */
 public static byte[] MD5Bit(byte[] source) {
  try {
   //  To obtain MD5 Abstract algorithmic  MessageDigest object 
   MessageDigest md5Digest = MessageDigest.getInstance("MD5");
   //  Updates the digest with the specified byte 
   md5Digest.update(source);
   //  Obtain ciphertext 
   return md5Digest.digest();
  } catch (NoSuchAlgorithmException e) {
   throw new RuntimeException(e);
  }
 }
 
 /**
  * MD5 Encrypted string ,32 A long 
  * @param source  Content to encrypt 
  * @return  Encrypted content 
  */
 public static String MD5(String source) {
  return byte2HexStr(MD5Bit(source.getBytes()));
 }
 
 /**
  * BASE64 coding 
  * @param source  The string to encode 
  * @return  Encoded string 
  */
 public static String encodeBASE64(String source) {
  Class<?> clazz = null;
  Method encodeMethod = null;
  try {//  Preferential use control 3 Party libraries 
   clazz = Class.forName("org.apache.commons.codec.binary.Base64");
   encodeMethod = clazz.getMethod("encodeBase64", byte[].class);
   System.out.println("encodeBASE64-->" + clazz);
   System.out.println("encodeMethod-->" + encodeMethod);
   //  The reflection method   Static methods execute without an object 
   return new String((byte[]) encodeMethod.invoke(null, source.getBytes()));
  } catch (ClassNotFoundException e) {
   String vm = System.getProperty("java.vm.name");
   System.out.println(vm);
   try {
    if ("Dalvik".equals(vm)) {// Android
     clazz = Class.forName("android.util.Base64");
     // byte[] Base64.encode(byte[] input,int flags)
     encodeMethod = clazz.getMethod("encode", byte[].class, int.class);
     System.out.println("encodeBASE64-->" + clazz);
     System.out.println("encodeMethod-->" + encodeMethod);
     return new String((byte[]) encodeMethod.invoke(null, source.getBytes(), 0));
    } else {// JavaSE/JavaEE
     clazz = Class.forName("sun.misc.BASE64Encoder");
     encodeMethod = clazz.getMethod("encode", byte[].class);
     System.out.println("encodeBASE64-->" + clazz);
     System.out.println("encodeMethod-->" + encodeMethod);
     return (String) encodeMethod.invoke(clazz.newInstance(), source.getBytes());
    }
   } catch (ClassNotFoundException e1) {
    return null;
   } catch (Exception e1) {
    return null;
   }
  } catch (Exception e) {
   return null;
  }
  /*
   * Android
   * android.util.Base64
   */
  // return Base64.encodeToString(source, Base64.DEFAULT);
  // return new String(Base64.encode(source.getBytes(), Base64.DEFAULT));
 
  /*
   * JavaSE/JavaEE
   */
  // sun.misc.BASE64Encoder
  // BASE64Encoder encoder = new BASE64Encoder();
  // return encoder.encode(source.getBytes());
 
  // org.apache.commons.codec.binary.Base64
  // return new String(Base64.encodeBase64(source.getBytes()));
 }
 
 /**
  * BASE64 decoding 
  * @param encodeSource  Encoded string 
  * @return  The string before encoding 
  */
 public static String decodeBASE64(String encodeSource) {
  Class<?> clazz = null;
  Method decodeMethod = null;
 
  try {//  Preferential use control 3 Party libraries 
   clazz = Class.forName("org.apache.commons.codec.binary.Base64");
   decodeMethod = clazz.getMethod("decodeBase64", byte[].class);
   System.out.println("decodeBASE64-->" + clazz);
   System.out.println("decodeMethod-->" + decodeMethod);
   //  The reflection method   Static methods execute without an object 
   return new String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes()));
  } catch (ClassNotFoundException e) {
   String vm = System.getProperty("java.vm.name");
   System.out.println(vm);
   try {
    if ("Dalvik".equals(vm)) {// Android
     clazz = Class.forName("android.util.Base64");
     // byte[] Base64.decode(byte[] input, int flags)
     decodeMethod = clazz.getMethod("decode", byte[].class, int.class);
     System.out.println("decodeBASE64-->" + clazz);
     System.out.println("decodeMethod-->" + decodeMethod);
     return new String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes(), 0));
    } else { // JavaSE/JavaEE
     clazz = Class.forName("sun.misc.BASE64Decoder");
     decodeMethod = clazz.getMethod("decodeBuffer", String.class);
     System.out.println("decodeBASE64-->" + clazz);
     System.out.println("decodeMethod-->" + decodeMethod);
     return new String((byte[]) decodeMethod.invoke(clazz.newInstance(), encodeSource));
    }
   } catch (ClassNotFoundException e1) {
    return null;
   } catch (Exception e1) {
    return null;
   }
  } catch (Exception e) {
   return null;
  }
  /*
   * Android
   * android.util.Base64
   */
  // return new
  // String(Base64.decode(encodeSource.getBytes(),Base64.DEFAULT));
 
  /*
   * JavaSE/JavaEE
   */
  // sun.misc.BASE64Decoder
  // try {
  // BASE64Decoder decoder = new BASE64Decoder();
  // return new String(decoder.decodeBuffer(encodeSource));
  // } catch (IOException e) {
  // throw new RuntimeException(e);
  // }
 
  // org.apache.commons.codec.binary.Base64
  // return new String(Base64.decodeBase64(encodeSource.getBytes()));
 }
 
 /**
  * AES encryption 
  * @param content  Content to be encrypted 
  * @param password  Encrypted password 
  * @return
  */
 public static byte[] encryptBitAES(byte[] content, String password) {
  try {
   Cipher encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//  Create password 
   encryptCipher.init(Cipher.ENCRYPT_MODE, getKey(password));//  Initialize the 
   byte[] result = encryptCipher.doFinal(content);
   return result; //  encryption 
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (NoSuchPaddingException e) {
   e.printStackTrace();
  } catch (InvalidKeyException e) {
   e.printStackTrace();
  } catch (IllegalBlockSizeException e) {
   e.printStackTrace();
  } catch (BadPaddingException e) {
   e.printStackTrace();
  }
  return null;
 }
 
 /**
  * AES decryption 
  * @param content  Content to be decrypted 
  * @param password  The decryption key 
  * @return
  */
 public static byte[] decryptBitAES(byte[] content, String password) {
  try {
   Cipher decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//  Create password 
   decryptCipher.init(Cipher.DECRYPT_MODE, getKey(password));//  Initialize the 
   byte[] result = decryptCipher.doFinal(content);
   return result; //  Encryption result 
  } catch (InvalidKeyException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (NoSuchPaddingException e) {
   e.printStackTrace();
  } catch (IllegalBlockSizeException e) {
   e.printStackTrace();
  } catch (BadPaddingException e) {
   e.printStackTrace();
  }
  return null;
 }
 
 /**
  * AES String encryption 
  * @param content  Content to be encrypted 
  * @param password  Encrypted password 
  * @return
  */
 public static String encryptAES(String content, String password) {
  return byte2HexStr(encryptBitAES(content.getBytes(), password));
 }
 
 /**
  * AES String decryption 
  * @param content  Content to be decrypted 
  * @param password  The decryption key 
  * @return
  */
 public static String decryptAES(String content, String password) {
  return new String(decryptBitAES(hexStr2Bytes(content), password));
 }
 
 /**
  *  Generates the key from the specified string 
  * @param password  The string that constitutes the secret key 
  * @return  Generated key 
  * @throws NoSuchAlgorithmException
  */
 private static Key getKey(String password) throws NoSuchAlgorithmException {
  SecureRandom secureRandom = new SecureRandom(password.getBytes());
  //  generate KEY
  KeyGenerator kgen = KeyGenerator.getInstance("AES");
  kgen.init(128, secureRandom);
  SecretKey secretKey = kgen.generateKey();
  byte[] enCodeFormat = secretKey.getEncoded();
  //  conversion KEY
  SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  return key;
 }
 
 /**
  *  will byte The array is converted to a representation 16 A string of base values .
  *  Such as: byte[]{8,18} To: 0812 
  *  and  byte[] hexStr2Bytes(String strIn)  It's reversible to each other .
  * @param bytes  transformable byte An array of 
  * @return  The converted string 
  */
 public static String byte2HexStr(byte[] bytes) {
  int bytesLen = bytes.length;
  //  each byte It takes two characters to represent, so the length of the string is twice the length of the array 
  StringBuffer hexString = new StringBuffer(bytesLen * 2);
  for (int i = 0; i < bytesLen; i++) {
   //  Associate each byte with 0xFF You do alpha and beta, and then you convert to alpha 10 Base, and then with the help of Integer Again into 16 Into the system 
   String hex = Integer.toHexString(bytes[i] & 0xFF);
   if (hex.length() < 2) {
    hexString.append(0);//  If it is 1 position   Fill in front of a 0
   }
   hexString.append(hex);
  }
  return hexString.toString();
 }
 
 /**
  *  Will say 16 The string of the base value is converted to byte An array of ,
  *  and  String byte2HexStr(byte[] bytes)  It's reversible to each other .
  * @param bytes
  * @return  The transformed byte An array of 
  */
 public static byte[] hexStr2Bytes(String strIn) {
  byte[] arrB = strIn.getBytes();
  int iLen = arrB.length;
 
  //  Two character representation 1 So the length of the byte array is the length of the string divided by 2
  byte[] arrOut = new byte[iLen / 2];
  for (int i = 0; i < iLen; i = i + 2) {
   String strTmp = new String(arrB, i, 2);
   arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
  }
  return arrOut;
 }
 
}

The above is the entire content of this article, I hope to help you learn java programming.


Related articles: