使用密码在Java中加密XML文件

时间:2014-03-06 16:59:06

标签: java xml encryption sha256 des

我正在为客户做这个项目,而我目前停留的部分涉及采用XML字符串并加密它 - 这不需要是最先进的,它只需要加密它并解密它使用密码。

到目前为止,用户输入了我使用SHA-256进行过哈希处理的密码,然后尝试加密它:

public static String encryptString(String password, String source, String fileName, String fileDir) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, FileNotFoundException, IOException {
    FileOutputStream fos = null;
    CipherInputStream cis;

    byte key[] = password.getBytes();
    SecretKeySpec secretKey = new SecretKeySpec(key, "DES");

    Cipher encrypt = Cipher.getInstance("DES/ECB/PKCS5Padding");
    encrypt.init(Cipher.ENCRYPT_MODE, secretKey);

    InputStream fileInputStream = new ByteArrayInputStream(source.getBytes());//Here I am getting file data as byte array. You can convert your file data to InputStream  by other way too.

    File dataFile = new File(fileDir, fileName); //dataDir is location where my file is stored
    if (!dataFile.exists()) {
        cis = new CipherInputStream(fileInputStream, encrypt);
        try {
            fos = new FileOutputStream(dataFile);
            byte[] b = new byte[32];
            int i;
            while ((i = cis.read(b)) != -1) {
                fos.write(b, 0, i);
            }
            return fileName;
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
                cis.close();
                fileInputStream.close();
            } catch (IOException e) {
                //IOException
            }
        }
    }
    return "";
}

传入的密码是哈希密码 - 从这里我尝试运行它,但我得到了一个:

java.security.InvalidKeyException:密钥长度无效:64字节异常。

有人可以帮忙吗?

或者告诉我一个用密码加密XML文件的更好方法?

由于

1 个答案:

答案 0 :(得分:0)

来自文档。

  

如果此密码需要任何不能的算法参数   从给定密钥派生,底层密码实现是   应该自己生成所需的参数(使用   如果正在初始化,则提供者特定的默认值或随机值)   用于加密或密钥包装,引发InvalidKeyException(如果它)   正在初始化以进行解密或密钥解包。生成的   可以使用getParameters或getIV检索参数(如果是   参数是IV)。

一种非常简单的加密方法是将哈希值与文件中的字节进行异或运算(一次256位)。这是一种低级方法,但您不需要调试API。您应该能够用非常少的代码实现它。