Java中的加密与解密函数使用方法详解
发布时间:2023-06-09 03:29:30
Java 中的加密和解密是开发者们常用的功能,能够帮助保护程序和数据的安全性。本文将会带你了解 Java 中常用的加密解密函数,以及它们的具体使用方法。
Java 中常用的加密解密函数:
1. Base64 编解码
Base64 是一种用于表示二进制数据的编码方法,可以将二进制数据转化为 ASCII 码文本,使得它能够在网络传输中被识别和使用。Base64 编码可以用于在传输时避免数据失去有效性,还可以用于加密混淆系统信息。
使用方法:
Base64 编码:
String encodedString = Base64.getEncoder().encodeToString(stringToEncode.getBytes());
Base64 解码:
byte[] decodedBytes = Base64.getDecoder().decode(encodedString); String decodedString = new String(decodedBytes);
2. MD5 加密
MD5 加密是一种常用的消息摘要算法,可以将任意长度的消息转换成固定长度的 128 位消息摘要。可以对密码进行加密和摘要。
使用方法:
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashInBytes = md.digest(password.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashInBytes) {
sb.append(String.format("%02x", b));
}
String generatedPassword = sb.toString();
3. RSA 非对称加密
RSA 是一种常用的非对称加密算法,可以用于数据的加密和解密。RSA 加密和解密的过程中,需要生成公钥和私钥。
使用方法:
生成 RSA 密钥对:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
RSA 加密:
String plainText = "This is the text to be encrypted.";
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
RSA 解密:
Cipher cipherDecrypt = Cipher.getInstance("RSA");
cipherDecrypt.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipherDecrypt.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);
System.out.println(decryptedText);
4. AES 对称加密
AES 是一种高级加密标准,是一种常用的对称加密算法。对称加密需要使用相同的密钥进行加密和解密。AES 是目前被广泛应用于数据加密的算法之一。
使用方法:
生成 AES 密钥:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
AES 加密:
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
AES 解密:
Cipher cipherDecrypt = Cipher.getInstance("AES");
cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipherDecrypt.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);
总结
上述是 Java 中常用的加密解密函数使用方法的详细讲解,从 Base64 编码到 RSA 非对称加密和 AES 对称加密。开发者们可以根据项目需求选择一种或多种加密解密方式来保证程序和数据的安全性。
