Java中的加密

use*_*041 3 java encryption distribution aes

我有一个文本配置文件.此文件需要加密并随产品一起提供,以便最终用户无法更改值.

我已经研究过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));
    }
}


这是一个好方法吗?我可以将配置文件作为字符串,对其进行编码,将编码的字节写入文件.然后我可以分发编码文件.

但另一方面,我怎么解读呢?如何分发密钥规范以便能够解密?

谢谢

Aas*_*set 5

(将我的评论的略有删节版本作为答案重新发布,因为它获得了多次投票,我相信这就是答案.)

你是否面临同样的问题,为电影和游戏产业,答案是:你能做的最好是使其难以为用户更改文件; 你不能让它变得不可能.解密密钥必须位于代码中的某个位置(或者在硬件中,如果您也生成硬件),可以通过逆向工程获得.您也可以加密密钥,但第二个密钥必须存储在您的代码中,依此类推.如果您决定在代码中存储文件的哈希值并使用它来验证文件是否未被篡改,则会遇到类似的问题,因为有人可能会更改您的可执行文件中的哈希值(编辑:或者只是更改完全跳过哈希检查的代码).

正如@limc所提到的,你可以选择一些中央验证方案,它们会带来所有问题和用户敌意.我认为@Mr雅克的建议是你最好的选择,除非你真的需要100%防黑客(在这种情况下我认为你有一个大问题),因为它会阻止绝大多数用户(直到有人发布一个裂缝,那......)