java使用AES方式对密码进行加解密代码怎么写?需要什么引用加解密返回结果都要是string
在Java中进行AES加解密需要使用javax.crypto和javax.crypto.spec两个包。
加密代码如下:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtils {
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
public static String encrypt(String key, String data) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String key, String encryptedData) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decrypted);
}
}
其中,encrypt方法用于加密,decrypt方法用于解密。参数key为密钥,data为待加密的数据,encryptedData为加密后的数据。
在加密过程中,使用SecretKeySpec类将密钥转换为一个密钥规范,并传递给Cipher实例进行加密。在解密过程中,同样需要将密钥转换为密钥规范,并将加密后的数据进行Base64解码,然后传递给Cipher实例进行解密。
示例:
public static void main(String[] args) throws Exception {
String key = "1234567890123456";
String data = "hello, world!";
String encryptedData = AESUtils.encrypt(key, data);
System.out.println("encrypted data: " + encryptedData);
String decryptedData = AESUtils.decrypt(key, encryptedData);
System.out.println("decrypted data: " + decryptedData);
}
输出:
encrypted data: s1JtSfM4JY7rSdS+4CQ9Rw==
decrypted data: hello, world!
``
原文地址: https://www.cveoy.top/t/topic/fEpx 著作权归作者所有。请勿转载和采集!