在Java中实现智能加密,你可以使用对称加密算法(如AES)和非对称加密算法(如RSA)的组合
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public static SecretKey generateAesKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
return keyGenerator.generateKey();
}
public static IvParameterSpec generateIv() {
byte[] iv = new byte[16];
return new IvParameterSpec(iv);
}
public static String encrypt(String plainText, SecretKey aesKey, IvParameterSpec iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, aesKey, iv);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, SecretKey aesKey, IvParameterSpec iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKey, iv);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static String encryptRsaKey(SecretKey aesKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, generateRsaKey());
byte[] encryptedBytes = cipher.doFinal(aesKey.getEncoded());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static SecretKey decryptRsaKey(String encryptedAesKey, SecretKey rsaKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, rsaKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedAesKey);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new SecretKeySpec(decryptedBytes, "AES");
}
public static SecretKey generateRsaKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("RSA");
keyGenerator.init(2048);
return keyGenerator.generateKey();
}
现在你可以使用这些方法来实现智能加密和解密。首先,生成一个RSA密钥对,然后使用RSA公钥加密AES密钥,接着使用AES密钥加密明文。最后,使用AES密钥解密加密后的数据。这样就实现了智能加密。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。