当前位置: 移动技术网 > IT编程>开发语言>Java > Java加密解密工具(适用于JavaSE/JavaEE/Android)

Java加密解密工具(适用于JavaSE/JavaEE/Android)

2019年07月22日  | 移动技术网IT编程  | 我要评论

废柴兄弟第三季,共享论坛,长江代孕网

本文实例为大家分享了一个适用于javase/javaee/android的java加密解密工具,供大家学习,具体内容如下

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加密解密工具.
 * javase/javaee/android都适用
 * 
 * @author longshu 2016年4月13日
 */
public class encryptdecrypt {
 // 无需创建对象
 private encryptdecrypt() {
 }
 
 /**
  * sha1加密bit数据
  * @param source byte数组
  * @return 加密后的byte数组
  */
 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加密字符串数据
  * @param source 要加密的字符串
  * @return 加密后的字符串
  */
 public static string sha1(string source) {
  return byte2hexstr(sha1bit(source.getbytes()));
 }
 
 /**
  * md5加密bit数据
  * @param source byte数组
  * @return 加密后的byte数组
  */
 public static byte[] md5bit(byte[] source) {
  try {
   // 获得md5摘要算法的 messagedigest对象
   messagedigest md5digest = messagedigest.getinstance("md5");
   // 使用指定的字节更新摘要
   md5digest.update(source);
   // 获得密文
   return md5digest.digest();
  } catch (nosuchalgorithmexception e) {
   throw new runtimeexception(e);
  }
 }
 
 /**
  * md5加密字符串,32位长
  * @param source 要加密的内容
  * @return 加密后的内容
  */
 public static string md5(string source) {
  return byte2hexstr(md5bit(source.getbytes()));
 }
 
 /**
  * base64编码
  * @param source 要编码的字符串
  * @return 编码过的字符串
  */
 public static string encodebase64(string source) {
  class<?> clazz = null;
  method encodemethod = null;
  try {// 优先使用第三方库
   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);
   // 反射方法 静态方法执行无需对象
   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解码
  * @param encodesource 编码过的字符串
  * @return 编码前的字符串
  */
 public static string decodebase64(string encodesource) {
  class<?> clazz = null;
  method decodemethod = null;
 
  try {// 优先使用第三方库
   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);
   // 反射方法 静态方法执行无需对象
   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加密
  * @param content 待加密的内容
  * @param password 加密密码
  * @return
  */
 public static byte[] encryptbitaes(byte[] content, string password) {
  try {
   cipher encryptcipher = cipher.getinstance("aes/ecb/pkcs5padding");// 创建密码器
   encryptcipher.init(cipher.encrypt_mode, getkey(password));// 初始化
   byte[] result = encryptcipher.dofinal(content);
   return result; // 加密
  } 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解密
  * @param content 待解密内容
  * @param password 解密密钥
  * @return
  */
 public static byte[] decryptbitaes(byte[] content, string password) {
  try {
   cipher decryptcipher = cipher.getinstance("aes/ecb/pkcs5padding");// 创建密码器
   decryptcipher.init(cipher.decrypt_mode, getkey(password));// 初始化
   byte[] result = decryptcipher.dofinal(content);
   return 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字符串加密
  * @param content 待加密的内容
  * @param password 加密密码
  * @return
  */
 public static string encryptaes(string content, string password) {
  return byte2hexstr(encryptbitaes(content.getbytes(), password));
 }
 
 /**
  * aes字符串解密
  * @param content 待解密内容
  * @param password 解密密钥
  * @return
  */
 public static string decryptaes(string content, string password) {
  return new string(decryptbitaes(hexstr2bytes(content), password));
 }
 
 /**
  * 从指定字符串生成密钥
  * @param password 构成该秘钥的字符串
  * @return 生成的密钥
  * @throws nosuchalgorithmexception
  */
 private static key getkey(string password) throws nosuchalgorithmexception {
  securerandom securerandom = new securerandom(password.getbytes());
  // 生成key
  keygenerator kgen = keygenerator.getinstance("aes");
  kgen.init(128, securerandom);
  secretkey secretkey = kgen.generatekey();
  byte[] encodeformat = secretkey.getencoded();
  // 转换key
  secretkeyspec key = new secretkeyspec(encodeformat, "aes");
  return key;
 }
 
 /**
  * 将byte数组转换为表示16进制值的字符串.
  * 如:byte[]{8,18}转换为:0812 
  * 和 byte[] hexstr2bytes(string strin) 互为可逆的转换过程.
  * @param bytes 需要转换的byte数组
  * @return 转换后的字符串
  */
 public static string byte2hexstr(byte[] bytes) {
  int byteslen = bytes.length;
  // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
  stringbuffer hexstring = new stringbuffer(byteslen * 2);
  for (int i = 0; i < byteslen; i++) {
   // 将每个字节与0xff进行与运算,然后转化为10进制,然后借助于integer再转化为16进制
   string hex = integer.tohexstring(bytes[i] & 0xff);
   if (hex.length() < 2) {
    hexstring.append(0);// 如果为1位 前面补个0
   }
   hexstring.append(hex);
  }
  return hexstring.tostring();
 }
 
 /**
  * 将表示16进制值的字符串转换为byte数组,
  * 和 string byte2hexstr(byte[] bytes) 互为可逆的转换过程.
  * @param bytes
  * @return 转换后的byte数组
  */
 public static byte[] hexstr2bytes(string strin) {
  byte[] arrb = strin.getbytes();
  int ilen = arrb.length;
 
  // 两个字符表示一个字节,所以字节数组长度是字符串长度除以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;
 }
 
}

以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网