java 加密 解密 工具类
时间: 2025-06-21 08:28:28 浏览: 5
### Java 加密解密工具类示例
#### EncryptUtils 类实现
`EncryptUtils` 是一个自定义的 Java 工具类,用于封装常见的加密和解密算法,如 MD5、SHA-1、SHA-256、AES 和 DES 等。该工具类提供了简单易用的接口,使开发者能够方便地进行数据的加密、解密、签名和验证操作。
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;
public class EncryptUtils {
private static final String ALGORITHM_AES = "AES";
private static final int KEY_SIZE = 128; // Key size can be 128, 192 or 256 bits depending on the algorithm and environment.
/**
* Generate a new secret key for AES encryption.
*/
public static SecretKey generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM_AES);
keyGen.init(KEY_SIZE);
return keyGen.generateKey();
}
/**
* Convert string to Base64 encoded string using given key.
*/
public static String encrypt(String data, SecretKey secret) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM_AES);
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}
/**
* Decrypt Base64 encoded string back into original string using given key.
*/
public static String decrypt(String encryptedData, SecretKey secret) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM_AES);
cipher.init(Cipher.DECRYPT_MODE, secret);
byte[] decodedValue = Base64.getDecoder().decode(encryptedData);
byte[] decryptedData = cipher.doFinal(decodedValue);
return new String(decryptedData);
}
}
```
此代码片段展示了如何创建 `EncryptUtils` 类并实现了基本的 AES 加密/解密功能[^2]。
#### 使用示例
下面是如何使用上述工具类来进行字符串的加密与解密:
```java
try {
// Step 1: Create an instance of SecretKey (only once per application lifecycle).
SecretKey mySecretKey = EncryptUtils.generateKey();
// Store this somewhere safe as you will need it later for decryption!
// Step 2: Use your generated key to perform encryption operations.
String messageToBeEncrypted = "This is a test.";
System.out.println("Original Message : " + messageToBeEncrypted);
String encryptedMessage = EncryptUtils.encrypt(messageToBeEncrypted, mySecretKey);
System.out.println("Encrypted Message: " + encryptedMessage);
// Step 3: When needed, use the same key to reverse the process by performing decryption operation.
String decryptedMessage = EncryptUtils.decrypt(encryptedMessage, mySecretKey);
System.out.println("Decrypted Message: " + decryptedMessage);
} catch (Exception e) {
e.printStackTrace();
}
```
这段程序首先生成了一个新的秘密钥,接着利用它对消息进行了加密处理,并最终成功恢复了原始的消息内容。
阅读全文
相关推荐















