Android MD5加密

Android MD5加密概述 在网络中传输明文是一件非常危险的事情 所以通常将密码加密后传至服务器 由服务器保存密文在登录判定时只需比较密文是否相同即可 MD5 加密是一种常用的加密算法 全称为 Message Digest Algorithm 5 即消息摘要算法 由 MD2 MD3 MD4 演变过来的 是一种单向加密算法 是一种不可逆的加密方式 MD5 优点 压缩性 任意长度的数据 算出的 MD5 值长度都是固定的

概述

在网络中传输明文是一件非常危险的事情,所以通常将密码加密后传至服务器,由服务器保存密文在登录判定时只需比较密文是否相同即可。

MD5加密是一种常用的加密算法,全称为“Message-Digest Algorithm 5”,即消息摘要算法,由MD2、MD3、MD4演变过来的,是一种单向加密算法,是一种不可逆的加密方式

MD5优点:

压缩性:任意长度的数据,算出的MD5值长度都是固定的。

容易计算:从原数据计算出MD5值很容易。

抗修改性:对原数据进行任何改动,所得到的MD5值都有很大区别。

强抗碰撞:已知原数据和其MD5值,想找到一个相同MD5值得数据是非常困难的。

Android中MD5加密算法实现

1、计算字符串MD5值

    @NonNull
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());
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xff);
if (temp.length() == 1) {
temp = "0" + temp;
}
result.append(temp);
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}

2、计算文件的MD5值

    @NonNull
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加密安全性

虽然MD5加密本身是不可逆的,但并不是不可破译的,常见激活成功教程机制为穷举法,即为俗话说的跑字典,一些常见的密码很容易在大型数据库中匹配到相同的MD5值,所以我们要想办法增加加密安全性。

1、对字符串多次MD5加密

    @NonNull
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);
}

2、MD5加盐

加盐就是使用一个额外的盐值与原字符串一起加密,通常盐值可以使用用户名、string明文的hascode或是随机生成的字符串。

    @NonNull
public static String md5(String string, String slat) {
if (TextUtils.isEmpty(string)) {
return "";
}
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest((string + slat).getBytes());
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xff);
if (temp.length() == 1) {
temp = "0" + temp;
}
result.append(temp);
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}


编程小号
上一篇 2025-02-26 12:27
下一篇 2025-01-29 14:11

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/134427.html