如何使用Java函数来实现加密和解密算法?
实现加密和解密算法可以使用Java函数来完成,下面将介绍一种常见的加密算法AES(Advanced Encryption Standard)和 RSA(Rivest-Shamir-Adleman)的实现。
1. AES加密和解密算法的实现:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
public static String encrypt(String plainText, String password) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String password) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
在上面的代码中,encrypt方法通过指定密码生成SecretKeySpec,然后获取Cipher实例,设置为AES/ECB/PKCS5Padding模式,并使用生成的密钥进行初始化。然后将明文转换为字节数组,调用cipher.doFinal方法进行加密,最后将加密结果使用Base64编码返回。decrypt方法与encrypt方法类似,只是将加密结果进行Base64解码后再进行解密,并将解密结果转换为字符串返回。
2. RSA加密和解密算法的实现:
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
public class RSAUtil {
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // 使用2048位RSA密钥对生成密钥对
return keyPairGenerator.generateKeyPair();
}
public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
在上述代码中,generateKeyPair方法使用KeyPairGenerator生成RSA密钥对,指定2048位长度。encrypt方法使用Cipher.getInstance获取RSA加密算法的实例,然后使用公钥进行初始化,将明文转换为字节数组,调用cipher.doFinal方法进行加密,最后将加密结果使用Base64编码返回。decrypt方法与encrypt方法类似,只是将加密结果进行Base64解码后再进行解密,并将解密结果转换为字符串返回。
使用Java函数可以方便地实现加密和解密算法,上述示例提供了AES和RSA两种常见算法的实现方式,可以根据具体需求选择合适的算法,并根据实际情况做适当的调整。
