protected byte[] encryptMD5(byte[] input) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(input);
return md5.digest(); // 16 bytes (128 bits)
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 not supported", e);
}
}
常見用法:儲存密碼雜湊驗證 (建議加鹽 Salt)、檔案校驗和。
protected byte[] encryptSHA(byte[] input) {
try {
MessageDigest sha = MessageDigest.getInstance("SHA"); // SHA-1, 160 bits
sha.update(input);
return sha.digest();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA not supported", e);
}
}
SHA 系列含 SHA-1、SHA-256、SHA-384、SHA-512,安全性遞增。新專案建議用 SHA-256 以上。
import java.security.*;
import java.security.interfaces.*;
import javax.crypto.Cipher;
public class RSAEncrypt {
public static void main(String[] args) throws Exception {
RSAEncrypt rsa = new RSAEncrypt();
String plainText = "encryptText";
// 1. 生成金鑰對 (1024 bits 以上,建議 2048)
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
// 2. 公鑰加密
byte[] encrypted = rsa.encrypt(publicKey, plainText.getBytes("UTF-8"));
System.out.println("Encrypted (Base64): " + Base64.getEncoder().encodeToString(encrypted));
// 3. 私鑰解密
byte[] decrypted = rsa.decrypt(privateKey, encrypted);
System.out.println("Decrypted: " + new String(decrypted, "UTF-8"));
}
/** 公鑰加密 */
protected byte[] encrypt(RSAPublicKey publicKey, byte[] data) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception e) {
throw new RuntimeException("RSA encrypt failed", e);
}
}
/** 私鑰解密 */
protected byte[] decrypt(RSAPrivateKey privateKey, byte[] data) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (Exception e) {
throw new RuntimeException("RSA decrypt failed", e);
}
}
}
RSA/ECB/PKCS1Padding,明確指定避免預設差異。