您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,可以使用Java Cryptography Extension (JCE)框架来实现数据的加密和解密。JCE提供了一系列的加密算法,如AES、DES、RSA等,以及相关的工具类和接口。以下是使用AES算法进行数据加密和解密的示例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
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);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey;
}
// 加密数据
public static String encrypt(String data, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedData);
}
// 解密数据
public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData, StandardCharsets.UTF_8);
}
}
public class Main {
public static void main(String[] args) {
try {
// 生成密钥
SecretKey secretKey = AESUtil.generateKey(128);
// 待加密数据
String data = "Hello, World!";
// 加密数据
String encryptedData = AESUtil.encrypt(data, secretKey);
System.out.println("Encrypted data: " + encryptedData);
// 解密数据
String decryptedData = AESUtil.decrypt(encryptedData, secretKey);
System.out.println("Decrypted data: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:在实际应用中,密钥的管理和存储非常重要。上述示例仅用于演示目的,实际项目中需要考虑更多的安全因素。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。