Android Base64
加密解密
public void encrypt(String userId) {
//加密
byte[] encode=Base64.encode(userId.getBytes(),Base64.DEFAULT);
String dataKey=new String (encode);
Log.i(TAG, "encrypt: "+dataKey);
//解密
byte[] decode=Base64.decode(dataKey.getBytes(),Base64.DEFAULT);
String initData=new String (decode);
Log.i(TAG, "encrypt: "+initData);
}
encrypt("123");
encrypt2("yourData");
查看打印信息
Android MD5
用MessageDigest类来操作
A MessageDigest object starts out initialized. The data is processed through it using the update
methods. At any point reset
can be called to reset the digest. Once all the data to be updated has been updated, one of the digest
methods should be called to complete the hash computation.
简单来说就是update()进行数据处理,reset()可以重置数据,数据update完成之后,用digest()完成哈希计算加密
示例代码:字符串MD5加密
public String stringMD5(String str){
try {
MessageDigest messageDigest=MessageDigest.getInstance("MD5");
messageDigest.update(str.getBytes());
byte[] bytes=messageDigest.digest();
StringBuilder stringBuilder=new StringBuilder();
for (byte b:bytes){
String temp = Integer.toHexString(b & 0xff);
if (temp.length() == 1) {
stringBuilder.append('0');
}
stringBuilder.append(temp);
}
String result=stringBuilder.toString();
System.out.println(result);
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "error";
}
}
b & 0xff是为了将int型的高24位置0,Integer.toHexString()是将int值转16进制表示的字符串
现在MD5破解方法是穷举法,应对方法有很多
1.对字符串进行2次或多次MD5加密
2.字符串+盐再进行MD5加密
3.字符串第一次MD5的结果作为盐,再结合字符串进行第二次MD5加密
示例代码:文件的MD5加密
public static String md5(File file) {
if (file == null || !file.isFile() || !file.exists()) {
return "";
}
FileInputStream in = null;
StringBuilder stringBuilder=new StringBuilder();
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) {
stringBuilder.append('0');
}
stringBuilder.append(temp);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(null!=in){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String result=stringBuilder.toString();
System.out.println(result);
return result;
}
同样的道理,将文件的所有byte都进行了数据处理,再统一哈希计算完成加密