在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

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

2016-7-29 15:37| 发布者: zhangjf| 查看: 642| 评论: 0

摘要: 本文实例为大家分享了一个适用于JavaSE/JavaEE/Android的Java加密解密工具,供大家学习,具体内容如下 package longshu.utils.security; import java.lang.reflect.Method;import java.security.InvalidKeyException ...

本文实例为大家分享了一个适用于JavaSE/JavaEE/Android的Java加密解密工具,供大家学习,具体内容如下

  1. package longshu.utils.security;
  2. import java.lang.reflect.Method;
  3. import java.security.InvalidKeyException;
  4. import java.security.Key;
  5. import java.security.MessageDigest;
  6. import java.security.NoSuchAlgorithmException;
  7. import java.security.SecureRandom;
  8. import javax.crypto.BadPaddingException;
  9. import javax.crypto.Cipher;
  10. import javax.crypto.IllegalBlockSizeException;
  11. import javax.crypto.KeyGenerator;
  12. import javax.crypto.NoSuchPaddingException;
  13. import javax.crypto.SecretKey;
  14. import javax.crypto.spec.SecretKeySpec;
  15. /**
  16. * Java加密解密工具.
  17. * JavaSE/JavaEE/Android都适用
  18. *
  19. * @author longshu 2016年4月13日
  20. */
  21. public class EncryptDecrypt {
  22. // 无需创建对象
  23. private EncryptDecrypt() {
  24. }
  25. /**
  26. * SHA1加密Bit数据
  27. * @param source byte数组
  28. * @return 加密后的byte数组
  29. */
  30. public static byte[] SHA1Bit(byte[] source) {
  31. try {
  32. MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
  33. sha1Digest.update(source);
  34. byte targetDigest[] = sha1Digest.digest();
  35. return targetDigest;
  36. } catch (NoSuchAlgorithmException e) {
  37. throw new RuntimeException(e);
  38. }
  39. }
  40. /**
  41. * SHA1加密字符串数据
  42. * @param source 要加密的字符串
  43. * @return 加密后的字符串
  44. */
  45. public static String SHA1(String source) {
  46. return byte2HexStr(SHA1Bit(source.getBytes()));
  47. }
  48. /**
  49. * MD5加密Bit数据
  50. * @param source byte数组
  51. * @return 加密后的byte数组
  52. */
  53. public static byte[] MD5Bit(byte[] source) {
  54. try {
  55. // 获得MD5摘要算法的 MessageDigest对象
  56. MessageDigest md5Digest = MessageDigest.getInstance("MD5");
  57. // 使用指定的字节更新摘要
  58. md5Digest.update(source);
  59. // 获得密文
  60. return md5Digest.digest();
  61. } catch (NoSuchAlgorithmException e) {
  62. throw new RuntimeException(e);
  63. }
  64. }
  65. /**
  66. * MD5加密字符串,32位长
  67. * @param source 要加密的内容
  68. * @return 加密后的内容
  69. */
  70. public static String MD5(String source) {
  71. return byte2HexStr(MD5Bit(source.getBytes()));
  72. }
  73. /**
  74. * BASE64编码
  75. * @param source 要编码的字符串
  76. * @return 编码过的字符串
  77. */
  78. public static String encodeBASE64(String source) {
  79. Class<?> clazz = null;
  80. Method encodeMethod = null;
  81. try {// 优先使用第三方库
  82. clazz = Class.forName("org.apache.commons.codec.binary.Base64");
  83. encodeMethod = clazz.getMethod("encodeBase64", byte[].class);
  84. System.out.println("encodeBASE64-->" + clazz);
  85. System.out.println("encodeMethod-->" + encodeMethod);
  86. // 反射方法 静态方法执行无需对象
  87. return new String((byte[]) encodeMethod.invoke(null, source.getBytes()));
  88. } catch (ClassNotFoundException e) {
  89. String vm = System.getProperty("java.vm.name");
  90. System.out.println(vm);
  91. try {
  92. if ("Dalvik".equals(vm)) {// Android
  93. clazz = Class.forName("android.util.Base64");
  94. // byte[] Base64.encode(byte[] input,int flags)
  95. encodeMethod = clazz.getMethod("encode", byte[].class, int.class);
  96. System.out.println("encodeBASE64-->" + clazz);
  97. System.out.println("encodeMethod-->" + encodeMethod);
  98. return new String((byte[]) encodeMethod.invoke(null, source.getBytes(), 0));
  99. } else {// JavaSE/JavaEE
  100. clazz = Class.forName("sun.misc.BASE64Encoder");
  101. encodeMethod = clazz.getMethod("encode", byte[].class);
  102. System.out.println("encodeBASE64-->" + clazz);
  103. System.out.println("encodeMethod-->" + encodeMethod);
  104. return (String) encodeMethod.invoke(clazz.newInstance(), source.getBytes());
  105. }
  106. } catch (ClassNotFoundException e1) {
  107. return null;
  108. } catch (Exception e1) {
  109. return null;
  110. }
  111. } catch (Exception e) {
  112. return null;
  113. }
  114. /*
  115. * Android
  116. * android.util.Base64
  117. */
  118. // return Base64.encodeToString(source, Base64.DEFAULT);
  119. // return new String(Base64.encode(source.getBytes(), Base64.DEFAULT));
  120. /*
  121. * JavaSE/JavaEE
  122. */
  123. // sun.misc.BASE64Encoder
  124. // BASE64Encoder encoder = new BASE64Encoder();
  125. // return encoder.encode(source.getBytes());
  126. // org.apache.commons.codec.binary.Base64
  127. // return new String(Base64.encodeBase64(source.getBytes()));
  128. }
  129. /**
  130. * BASE64解码
  131. * @param encodeSource 编码过的字符串
  132. * @return 编码前的字符串
  133. */
  134. public static String decodeBASE64(String encodeSource) {
  135. Class<?> clazz = null;
  136. Method decodeMethod = null;
  137. try {// 优先使用第三方库
  138. clazz = Class.forName("org.apache.commons.codec.binary.Base64");
  139. decodeMethod = clazz.getMethod("decodeBase64", byte[].class);
  140. System.out.println("decodeBASE64-->" + clazz);
  141. System.out.println("decodeMethod-->" + decodeMethod);
  142. // 反射方法 静态方法执行无需对象
  143. return new String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes()));
  144. } catch (ClassNotFoundException e) {
  145. String vm = System.getProperty("java.vm.name");
  146. System.out.println(vm);
  147. try {
  148. if ("Dalvik".equals(vm)) {// Android
  149. clazz = Class.forName("android.util.Base64");
  150. // byte[] Base64.decode(byte[] input, int flags)
  151. decodeMethod = clazz.getMethod("decode", byte[].class, int.class);
  152. System.out.println("decodeBASE64-->" + clazz);
  153. System.out.println("decodeMethod-->" + decodeMethod);
  154. return new String((byte[]) decodeMethod.invoke(null, encodeSource.getBytes(), 0));
  155. } else { // JavaSE/JavaEE
  156. clazz = Class.forName("sun.misc.BASE64Decoder");
  157. decodeMethod = clazz.getMethod("decodeBuffer", String.class);
  158. System.out.println("decodeBASE64-->" + clazz);
  159. System.out.println("decodeMethod-->" + decodeMethod);
  160. return new String((byte[]) decodeMethod.invoke(clazz.newInstance(), encodeSource));
  161. }
  162. } catch (ClassNotFoundException e1) {
  163. return null;
  164. } catch (Exception e1) {
  165. return null;
  166. }
  167. } catch (Exception e) {
  168. return null;
  169. }
  170. /*
  171. * Android
  172. * android.util.Base64
  173. */
  174. // return new
  175. // String(Base64.decode(encodeSource.getBytes(),Base64.DEFAULT));
  176. /*
  177. * JavaSE/JavaEE
  178. */
  179. // sun.misc.BASE64Decoder
  180. // try {
  181. // BASE64Decoder decoder = new BASE64Decoder();
  182. // return new String(decoder.decodeBuffer(encodeSource));
  183. // } catch (IOException e) {
  184. // throw new RuntimeException(e);
  185. // }
  186. // org.apache.commons.codec.binary.Base64
  187. // return new String(Base64.decodeBase64(encodeSource.getBytes()));
  188. }
  189. /**
  190. * AES加密
  191. * @param content 待加密的内容
  192. * @param password 加密密码
  193. * @return
  194. */
  195. public static byte[] encryptBitAES(byte[] content, String password) {
  196. try {
  197. Cipher encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
  198. encryptCipher.init(Cipher.ENCRYPT_MODE, getKey(password));// 初始化
  199. byte[] result = encryptCipher.doFinal(content);
  200. return result; // 加密
  201. } catch (NoSuchAlgorithmException e) {
  202. e.printStackTrace();
  203. } catch (NoSuchPaddingException e) {
  204. e.printStackTrace();
  205. } catch (InvalidKeyException e) {
  206. e.printStackTrace();
  207. } catch (IllegalBlockSizeException e) {
  208. e.printStackTrace();
  209. } catch (BadPaddingException e) {
  210. e.printStackTrace();
  211. }
  212. return null;
  213. }
  214. /**
  215. * AES解密
  216. * @param content 待解密内容
  217. * @param password 解密密钥
  218. * @return
  219. */
  220. public static byte[] decryptBitAES(byte[] content, String password) {
  221. try {
  222. Cipher decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
  223. decryptCipher.init(Cipher.DECRYPT_MODE, getKey(password));// 初始化
  224. byte[] result = decryptCipher.doFinal(content);
  225. return result; // 加密结果
  226. } catch (InvalidKeyException e) {
  227. e.printStackTrace();
  228. } catch (NoSuchAlgorithmException e) {
  229. e.printStackTrace();
  230. } catch (NoSuchPaddingException e) {
  231. e.printStackTrace();
  232. } catch (IllegalBlockSizeException e) {
  233. e.printStackTrace();
  234. } catch (BadPaddingException e) {
  235. e.printStackTrace();
  236. }
  237. return null;
  238. }
  239. /**
  240. * AES字符串加密
  241. * @param content 待加密的内容
  242. * @param password 加密密码
  243. * @return
  244. */
  245. public static String encryptAES(String content, String password) {
  246. return byte2HexStr(encryptBitAES(content.getBytes(), password));
  247. }
  248. /**
  249. * AES字符串解密
  250. * @param content 待解密内容
  251. * @param password 解密密钥
  252. * @return
  253. */
  254. public static String decryptAES(String content, String password) {
  255. return new String(decryptBitAES(hexStr2Bytes(content), password));
  256. }
  257. /**
  258. * 从指定字符串生成密钥
  259. * @param password 构成该秘钥的字符串
  260. * @return 生成的密钥
  261. * @throws NoSuchAlgorithmException
  262. */
  263. private static Key getKey(String password) throws NoSuchAlgorithmException {
  264. SecureRandom secureRandom = new SecureRandom(password.getBytes());
  265. // 生成KEY
  266. KeyGenerator kgen = KeyGenerator.getInstance("AES");
  267. kgen.init(128, secureRandom);
  268. SecretKey secretKey = kgen.generateKey();
  269. byte[] enCodeFormat = secretKey.getEncoded();
  270. // 转换KEY
  271. SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  272. return key;
  273. }
  274. /**
  275. * 将byte数组转换为表示16进制值的字符串.
  276. * 如:byte[]{8,18}转换为:0812
  277. * 和 byte[] hexStr2Bytes(String strIn) 互为可逆的转换过程.
  278. * @param bytes 需要转换的byte数组
  279. * @return 转换后的字符串
  280. */
  281. public static String byte2HexStr(byte[] bytes) {
  282. int bytesLen = bytes.length;
  283. // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
  284. StringBuffer hexString = new StringBuffer(bytesLen * 2);
  285. for (int i = 0; i < bytesLen; i++) {
  286. // 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制
  287. String hex = Integer.toHexString(bytes[i] & 0xFF);
  288. if (hex.length() < 2) {
  289. hexString.append(0);// 如果为1位 前面补个0
  290. }
  291. hexString.append(hex);
  292. }
  293. return hexString.toString();
  294. }
  295. /**
  296. * 将表示16进制值的字符串转换为byte数组,
  297. * 和 String byte2HexStr(byte[] bytes) 互为可逆的转换过程.
  298. * @param bytes
  299. * @return 转换后的byte数组
  300. */
  301. public static byte[] hexStr2Bytes(String strIn) {
  302. byte[] arrB = strIn.getBytes();
  303. int iLen = arrB.length;
  304. // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
  305. byte[] arrOut = new byte[iLen / 2];
  306. for (int i = 0; i < iLen; i = i + 2) {
  307. String strTmp = new String(arrB, i, 2);
  308. arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
  309. }
  310. return arrOut;
  311. }
  312. }
复制代码

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

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-8 01:17

Copyright 2015-2025 djqfx

返回顶部