加密:透過演算法將明文變為密文
單向加密:密文無法還原成明文,如 MD5、SHA
雙向加密:密文可以還原成明文
對稱加密(私鑰):加密解密是同一把金鑰,如 DES、AES
非對稱加密(公鑰):公鑰加密私鑰解密、私鑰加密公鑰解密,如 RSA、DSA
單向加密
以雜湊計算出16進位的「摘要」,相當於指紋
即同一資料的摘要會相同
常用於比對資料傳輸的一致性
使用 java.security.MessageDigest 的範例
// "MD2", "MD5", "SHA1", "SHA-256", "SHA-384", "SHA-512"
public static String sumString(String algorithm, String string) throws NoSuchAlgorithmException {
return md(algorithm, string.getBytes());
}
public static String sumFile(String algorithm, String path) throws NoSuchAlgorithmException, IOException {
byte[] input = Files.readAllBytes(Paths.get(path));
return md(algorithm, input);
}
private static String md(String algorithm, byte[] input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(input);
byte[] hash = md.digest();
return DatatypeConverter.printHexBinary(hash);
}
測試
String[] algorithms = new String[] { "MD2", "MD5", "SHA1", "SHA-256", "SHA-384", "SHA-512" };
String[] strings = new String[] { "AAAAAAAAAAA", "BBBBBBBBBBB", "CCCCCCCCCCC" };
String[] files = new String[] { "C:/aaa.txt", "C:/bbb.jpg", "C:/ccc.pdf" };
for (String string : strings) {
System.out.println();
System.out.println("字串: " + string);
for (String algorithm : algorithms) {
System.out.println(algorithm + ": " + sumString(algorithm, string));
}
}
for (String file : files) {
System.out.println();
System.out.println("檔案: " + file);
for (String algorithm : algorithms) {
System.out.println(algorithm + ": " + sumFile(algorithm, file));
}
}
AES 加密
encryption algorithm/operation modes/padding scheme
AES
AES/ECB/NoPadding
AES/ECB/PKCS5Padding
Blowfish/ECB/PKCS5Padding
DES/ECB/PKCS5Padding
AES/CBC/PKCS5Padding
Blowfish/CBC/PKCS5Padding
DES/CBC/PKCS5Padding
AES/CBC/PKCS7Padding
Blowfish/CBC/PKCS7Padding
DES/CBC/PKCS7Padding
RSA/NONE/NoPadding
AES/GCM/NoPadding
RSA/None/OAEPWithSHA-1AndMGF1Padding
RSA/None/OAEPWITHSHA-256ANDMGF1PADDING