gpt4 book ai didi

Java对称加密方法

转载 作者:行者123 更新时间:2023-12-01 18:33:01 25 4
gpt4 key购买 nike

我有一个用 Java 编写的 RESTful API,我想保护该 API 的外部配置文件。

我尝试使用以下对称加密方法来保护它:

private final static String passPhrase = "My Super Ultra Passphrase";
private final static byte[] salt = "My Super Ultra Salt".getBytes();
private final static int iterations = 8192;
private static String strIv = "";

private static String encryptText(String text) {
String result = "";
try {
// create the key for encryption
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey secret = factory.generateSecret(
new PBEKeySpec(passPhrase.toCharArray(), salt, iterations, 128));
SecretKeySpec key = new SecretKeySpec(secret.getEncoded(), "AES");

// encrypts the text
Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
aes.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = aes.doFinal(text.getBytes());
byte[] iv = aes.getIV();

result = new String(Base64.encode(cipherText));
strIv = new String(Base64.encode(iv));

} catch (NoSuchAlgorithmException
| InvalidKeySpecException
| NoSuchPaddingException
| InvalidKeyException
| IllegalBlockSizeException
| BadPaddingException e) {
e.printStackTrace();
}
return result;
}

private static String decryptText(String text) {
String result = "";
try {
// create the key for decryption
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey secret = factory.generateSecret(
new PBEKeySpec(passPhrase.toCharArray(), salt, iterations, 128));
SecretKeySpec key = new SecretKeySpec(secret.getEncoded(), "AES");

byte[] iv = Base64.decode(strIv);
byte[] cipherText = Base64.decode(text);

// decrypt the text
Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
aes.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
result = new String(aes.doFinal(cipherText));

} catch (NoSuchAlgorithmException
| InvalidKeySpecException
| NoSuchPaddingException
| InvalidKeyException
| IllegalBlockSizeException
| BadPaddingException
| InvalidAlgorithmParameterException
| Base64DecodingException e) {
e.printStackTrace();
}
return result;
}

我的问题是:这段代码相当强大吗?

最佳答案

您到底想针对哪种攻击场景进行防御?我将做出一些假设来回答,如果我错了,请纠正。

如果您想保护配置文件,那么您正在尝试防御已经获得服务器文件读取权限的攻击者。在这种情况下,攻击者也可以下载程序本身并使用调试器提取 key ,因为它是硬编码的。这是一个额外的防御层,可能会让一些攻击者放弃,但只会拖延其他攻击者。

希望有帮助。

关于Java对称加密方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23293180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com