如何将IvParameterSpec写入文件?

时间:2013-10-08 10:54:44

标签: java cryptography aes secret-key

我使用以下代码将SecretKey写入文件。同样,我必须将我的ivParameterSpec写入另一个文件。我怎么能这样做?

SecretKey key = KeyGenerator.getInstance("AES").generateKey();
ObjectOutputStream secretkeyOS = new ObjectOutputStream(new FileOutputStream("publicKeyFile"));
secretkeyOS.writeObject(key);
secretkeyOS.close();

AlgorithmParameterSpec paramSpec1 = new IvParameterSpec(iv);
session.setAttribute("secParam", paramSpec1);
ObjectOutputStream paramOS = new ObjectOutputStream(new FileOutputStream("paramFile"));
paramOS.writeObject(paramSpec1);
paramOS.close();

1 个答案:

答案 0 :(得分:2)

不要尝试存储IvParameterSpec对象。它不可序列化,因为它不打算存储。 IV是重要的部分。存储此内容并从IV创建新的IvSpec。我已将here的示例代码更改为AES加密以存储IV并使用加载的IV解密密文,以便您可以看到可能的工作流程。

请注意,这是一个很小的例子。在真实的用例中,您也可以存储和加载密钥,并且还应该重新考虑异常处理:-D

public class Test {
    public static void main(String[] args) throws Exception {
        String message = "This string contains a secret message.";

        // generate a key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(128);
        byte[] key = keygen.generateKey().getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

        byte[] iv = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);

        // initialize the cipher for encrypt mode
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);

        // encrypt the message
        byte[] encrypted = cipher.doFinal(message.getBytes());
        System.out.println("Ciphertext: " + hexEncode(encrypted) + "\n");

        // Write IV
        FileOutputStream fs = new FileOutputStream(new File("paramFile"));
        BufferedOutputStream bos = new BufferedOutputStream(fs);
        bos.write(iv);
        bos.close();

        // Read IV
        byte[] fileData = new byte[16];
        DataInputStream dis = null;

        dis = new DataInputStream(new FileInputStream(new File("paramFile")));
        dis.readFully(fileData);
        if (dis != null) {
            dis.close();
        }

        // reinitialize the cipher for decryption
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(fileData));

        // decrypt the message
        byte[] decrypted = cipher.doFinal(encrypted);
        System.out.println("Plaintext: " + new String(decrypted) + "\n");
    }

    [...]
}