可以使用 Apache Commons-Codec 计算:
- 字符串的 MD5 (SHA)
- 文件的 MD5 (SHA)
- Base64 编码
- Base64 解码
Gradle 依赖
1
| compile 'commons-codec:commons-codec:1.10'
|
计算字符串的 MD5
1 2 3 4 5 6 7
| import org.apache.commons.codec.digest.DigestUtils;
public class Test { public static void main(String[] args) { System.out.println(DigestUtils.md5Hex("Hello")); } }
|
计算文件的 MD5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import org.apache.commons.codec.digest.DigestUtils;
import java.io.FileInputStream; import java.io.IOException;
public class Test { public static String fileMd5(String path) { try { return DigestUtils.md5Hex(new FileInputStream(path)); } catch (IOException e) { e.printStackTrace(); }
return ""; }
public static void main(String[] args) { System.out.println(fileMd5("/Users/Biao/Desktop/biao.png")); } }
|
Base64 编码解码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import org.apache.commons.codec.binary.Base64;
public class Test { public static void main(String[] args) throws Exception { Base64 base64 = new Base64();
String result = base64.encodeToString("Hello".getBytes("UTF-8")); System.out.println(result);
result = new String(base64.decode(result)); System.out.println(result); } }
|