MD5加密是一种单向加密算法,是不可逆的一种的加密方式 MD5的特点: 压缩性:任意长度的数据,包括文件加密得出来的长度都是32位的固定长度。 抗修改性:对数据的加密是无规律的,所得到的MD5值都有很大区别。 强抗碰撞:已知原数据和其MD5值,想找到一个具有相同MD5值的数据是非常困难的。 /** * Created by ztz on 2018/1/30. */ public class MD5Utils { /** * MD5的字符串加密方式 * @param string * @return */ public static String md5(String string) { if (TextUtils.isEmpty(string)) { return ""; } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); byte[] bytes = md5.digest(string.getBytes()); String result = ""; for (byte b : bytes) { String temp = Integer.toHexString(b & 0xff); if (temp.length() == 1) { temp = "0" + temp; } result += temp; } return result; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } /** * MD5的文件加密 * @param file * @return */ public static String md5(File file) { if (file == null || !file.isFile() || !file.exists()) { return ""; } FileInputStream in = null; String result = ""; byte buffer[] = new byte[8192]; int len; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { md5.update(buffer, 0, len); } byte[] bytes = md5.digest(); for (byte b : bytes) { String temp = Integer.toHexString(b & 0xff); if (temp.length() == 1) { temp = "0" + temp; } result += temp; } } catch (Exception e) { e.printStackTrace(); }finally { if(null!=in){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * MD5进行多次字符串加密 * @param string * @param times * @return */ public static String md5(String string, int times) { if (TextUtils.isEmpty(string)) { return ""; } String md5 = md5(string); for (int i = 0; i < times - 1; i++) { md5 = md5(md5); } return md5(md5); } }
Android中MD5加密方式工具类
最新推荐文章于 2022-10-27 17:42:56 发布