Java加密解密工具类通常用于实现数据的加密和解密操作,以保护数据的安全性和隐私性。以下是一个简单的Java加密解密工具类的示例,使用了常见的加密算法如AES(高级加密标准)。
常见的加密算法包括:
以下是一个使用AES算法进行加密和解密的Java工具类示例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
// 生成密钥
public static SecretKey generateKey(int n) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(n);
return keyGenerator.generateKey();
}
// 加密
public static String encrypt(String data, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密
public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
}
public static void main(String[] args) {
try {
// 生成密钥
SecretKey secretKey = generateKey(128);
// 加密数据
String originalData = "Hello, World!";
String encryptedData = encrypt(originalData, secretKey);
System.out.println("Encrypted Data: " + encryptedData);
// 解密数据
String decryptedData = decrypt(encryptedData, secretKey);
System.out.println("Decrypted Data: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过以上示例和解释,您可以了解Java加密解密工具类的基本概念、优势、类型、应用场景以及常见问题的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云