一、摘要算法
MD5
public static String getmd5(String path) {
String pathName = path;
String md5 = "";
try {
File file = new File(pathName);
FileInputStream ins = new FileInputStream(file);
FileChannel ch = ins.getChannel();
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(byteBuffer);
ins.close();
md5 = toHexString(md.digest());
} catch (Exception e) {
e.printStackTrace();
}
return md5;
}
final static char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static String toHexString(byte[] tmp) {
String s;
char str[] = new char[tmp.length * 2];
int k = 0;
for (int i = 0; i < tmp.length; i++) {
byte byte0 = tmp[i];
str[k++] = hex[byte0 >>> 4 & 0xf];
str[k++] = hex[byte0 & 0xf];
}
s = new String(str);
return s;
}
SHA1
public static String getsha1(String path) {
String pathName = path;
String sha1 = "";
try {
File file = new File(pathName);
FileInputStream ins = new FileInputStream(file);
FileChannel ch = ins.getChannel();
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sha.update(byteBuffer);
ins.close();
sha1 = Encryption.toHexString(sha.digest());
} catch (Exception e) {
e.printStackTrace();
}
return sha1;
}
二、对称加密算法
public static byte[] aesEncrypt(String str, String key) throws Exception {
if (str == null || key == null) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
return bytes;
}
public static String aesDecrypt(byte[] bytes, String key) throws Exception {
if (bytes == null || key == null) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
bytes = cipher.doFinal(bytes);
return new String(bytes, "utf-8");
}
三、非对称加密
RSA