我有一个文本配置文件。该文件需要加密并随产品一起提供,以便最终用户不能更改这些值。在Java中的加密
我已经看过AES这样做,并遇到这个简单的例子。
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
/**
* This program generates a AES key, retrieves its raw bytes, and
* then reinstantiates a AES key from the key bytes.
* The reinstantiated key is used to initialize a AES cipher for
* encryption and decryption.
*/
public class AES
{
/**
* Turns array of bytes into string
*
* @param buf Array of bytes to convert to hex string
* @return Generated hex string
*/
public static String asHex(byte buf[])
{
StringBuilder strbuf = new StringBuilder(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++)
{
if (((int) buf[i] & 0xff) < 0x10)
{
strbuf.append("0");
}
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static void main(String[] args) throws Exception
{
String message = "This is just an example";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(message.getBytes());
System.out.println("encrypted string: " + asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " + originalString + " " + asHex(original));
}
}
这是一个好方法吗?我可以将配置文件作为字符串进行编码,将编码的字节写入文件。然后我可以分发编码文件。
另一方面,我将如何解读它?如何分发关键规格以便能够被破译?
谢谢
你面临着与电影和游戏行业相同的问题,答案是:你所能做的最好的事情就是让用户修改文件;你不能让它变得不可能。解密密钥必须位于代码中的某处(或者在硬件中,如果您也生产硬件),它可以通过逆向工程获得。您也可以加密密钥,但第二个密钥必须存储在您的代码中,依此类推。如果您决定将文件的散列存储在代码中,并使用它来检查文件是否被篡改,则会出现类似的问题。 – 2011-02-28 17:02:36
我想你有一个选择是每次应用程序联机时在线检查一台机器+文件散列。但你只是提出这个问题,并让它更难一点。 问题是 - 如何确定有人会篡改你的文件?如果你的发行版有限,那么我不会花费太多时间。这也取决于你的观众。 – diagonalbatman 2011-02-28 17:13:01
@diagonalbatman出售经销商在日本。他们对这里的安全非常感兴趣,所以它必须尽可能安全。我们有一个服务器客户端模型,因此应用程序可以访问服务器。 – user489041 2011-02-28 17:15:35