所以我正在为我的 A level 项目创建一个游戏,现在我正处于需要能够加密和解密文本文件的阶段。
我已经找到了在 GCM 模式下使用 AES-256 进行加密的方法,但是我使用随机生成的 key 和 IV 来首先加密数据。所以我想知道,有什么方法可以在不知道 key 和 iv.txt 的情况下解密文本文件。 或者,从下面显示的加密方法中,我是否可以更改任何内容,以便稍后在解密文本时知道 key 和 iv。
注意:我使用 libGDX 库来创建游戏,这就是为什么我没有使用标准方法写入文本文件。
加密方式:
public void encrypt ()
{
byte[] input = w.getSprites().toString().getBytes(); // Data to be encrypted
byte[] encrypted = null; // Encrypted output
Cipher cipher; // Cipher algorithm to be used
try {
// Setup the cipher algorithm to use and select the wanted mode
// AES is the cipher algorithm GCM is the mode
cipher = Cipher.getInstance("AES/GCM/NoPadding");
// Generate a random key for the encryption
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
SecretKey key = keyGenerator.generateKey();
// Generate a random iv for the encryption
SecureRandom randomSecureRandom = new SecureRandom();
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
// Encrypt the data
cipher.init(Cipher.ENCRYPT_MODE, key, randomSecureRandom);
encrypted = new byte[cipher.getOutputSize(input.length)];
int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
enc_len += cipher.doFinal(encrypted, enc_len);
}
catch (NoSuchAlgorithmException |
NoSuchPaddingException |
InvalidKeyException |
ShortBufferException |
IllegalBlockSizeException |
BadPaddingException e) { e.printStackTrace(); }
FileHandle f = Gdx.files.local("bin/default/saves/default/test.txt");
f.writeString(encrypted.toString(), false);
}
预先感谢您的任何答复,我们非常感激。
最佳答案
不,不知道 key 就无法解密。如果任何人都可以在没有 key 的情况下解密消息,那么加密的意义何在?
如果这是为了向本地用户隐藏数据,那么最好的办法就是混淆数据。机器需要知道 key 才能对其进行加密和解密,任何有权访问该机器的人最终都可以找到该 key 并使用它来为自己解密数据。即使您不向磁盘写入任何内容,本地用户也可以查看内存并找到 key 。另请记住,代码可以反编译。
基本上只要记住,任何有物理访问权限的人都是王,你无法真正阻止他们,只能减慢他们的速度。
所以你能做的最好的事情就是让获得 key 的过程尽可能痛苦。类文件或属性文件中的字符串文字很容易阅读,而且一点也不痛苦,因此请避免使用它们。
参见this question了解处理本地安全的相关方法。
还可以考虑使用像 Proguard 这样的工具一般情况下也可以混淆(和优化)您的代码。
关于java - 如何在Java中使用未知的KEY和IV解密AES?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52785410/