Java Encryption and Decryption tool (applicable to javase/javaee/android) _java

Source: Internet
Author: User
Tags base64 decrypt md5 md5 digest md5 encryption reflection sha1 stringbuffer

This article for you to share a javase/javaee/android Java encryption and decryption tool for everyone to learn, the details are 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 All Apply * * @author Longshu April 13, 2016 */public class Encryptdecrypt {//No object private Encrypt created Decrypt () {}/** * SHA1 encrypt bit data * @param source byte array * @return encrypted byte array/public static byte[] Sha1bit (b
   Yte[] 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 be encrypted * @return encrypted string/public static string SHA1 (string source) {
 Return Byte2hexstr (Sha1bit (Source.getbytes ())); 
  /** * MD5 Encryption bit data * @param source byte array * @return encrypted byte array/public static byte[] Md5bit (byte[] source) {
   try {//Get the MessageDigest object of the MD5 digest algorithm messagedigest md5digest = messagedigest.getinstance ("MD5");
   Uses the specified byte update digest md5digest.update (source);
  Get ciphertext return md5digest.digest ();
  catch (NoSuchAlgorithmException e) {throw new RuntimeException (e);
  }/** * MD5 encrypted string, 32-bit long * @param source content to encrypt * @return encrypted content/public static string MD5 (String source) {
 Return Byte2hexstr (Md5bit (Source.getbytes ()));  /** * BASE64 Encoding * @param source string to encode * @return encoded string/public static string encodeBASE64 (string source)
  {class<?> clazz = null;
  Method encodemethod = null;
   try {///Use third party library firstClazz = Class.forName ("org.apache.commons.codec.binary.Base64");
   Encodemethod = Clazz.getmethod ("EncodeBase64", Byte[].class);
   System.out.println ("encodebase64-->" + clazz);
   System.out.println ("encodemethod-->" + Encodemethod);
  Reflection method static method execution does not require 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;
  The 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 encoded string/public static string decodeBASE64 (String E Ncodesource) {Class<?> clazz = null;
 
  Method decodemethod = null;
   try {//priority use of third party library 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);
  Reflection method static method execution does not require 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;
  The catch (Exception e) {return null; } * * Android * android.util.Base64//return new//String (Base64.decode (encodesource.getbytes), Base6
 
  4.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 to be encrypted * @param password encryption password * @return/public static byte[] Encryptbitaes (byte[) content, Strin g password) {try {Cipher encryptcipher = cipher.getinstance ("aes/ecb/pkcs5padding");//Create Cipher Encryptcipher.init (
   Cipher.encrypt_mode, Getkey (password));/Initialize 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 to be decrypted * @param password decryption key * @return/public static byte[] Decryptbitaes (
   byte[] Content, String password {try {Cipher decryptcipher = cipher.getinstance ("aes/ecb/pkcs5padding");//Create Cipher Decryptcipher.init (Cipher.decrypt_mode, Getkey (password)//Initialize byte[] result = decryptcipher.dofinal (content); return result;
  Cryptographic results} 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 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 to decrypt contents * @param password decryption key * @return/public static string Decryptaes (
 string content, string password) {return new string (Decryptbitaes (hexstr2bytes (content), password));  /** * Generates a key from the specified string * @param password The string that makes up 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 ();
  Convert key Secretkeyspec key = new Secretkeyspec (Encodeformat, "AES");
 Return key;
  /** * Converts a byte array to a string representing a 16-valued value.
  * such as: byte[]{8,18} converted to: 0812 * and byte[] hexstr2bytes (String strin) mutually reversible conversion process. * @param bytes need to convert byte array * @return converted String */public static string Byte2hexstr (byte[] bytes) {int Byteslen = Byt
  Es.length;
  Each byte can be represented by two characters, so the length of the string is twice times the length of the array stringbuffer hexstring = new StringBuffer (Byteslen * 2); for (int i = 0; i < Byteslen; i++) {//convert each byte to 0xFF and then convert to 10, then convert to 16 String hex with the help of Integer = Integer.tohex
   String (Bytes[i] & 0xFF); if (Hex.length () < 2) {hexstring.append (0);//if 1-bit front complement 0} hexstring.Append (hex);
 return hexstring.tostring ();
  /** * Converts a string representing a 16-to-binary value to a byte array, * and string byte2hexstr (byte[] bytes) mutually reversible conversion processes. * @param bytes * @return converted byte array */public static byte[] Hexstr2bytes (String strin) {byte[] Arrb = strin.getbyt
  ES ();
 
  int ilen = Arrb.length;
  Two characters represent a byte, so the length of the byte array is the string length 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 learn Java program to help you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.