【发布时间】:2012-12-15 20:40:26
【问题描述】:
我有一个使用随机生成的密钥加密文件内容的 java 程序。 该密钥使用 RSA 加密并保存到文本文件中。
现在,我有一个 java 程序,它给出了文件和存储 RSA 密钥的密钥库,需要先解密加密的密钥,然后用密钥解密文件。
这是我目前所拥有的:
// Fetch the other public key and decrypt the file encryption key
java.security.cert.Certificate cert2 = keystore.getCertificate("keyForSeckeyDecrypt");
Key secKeyPublicKey = cert2.getPublicKey();
Cipher cipher = Cipher.getInstance(secKeyPublicKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secKeyPublicKey);
keyFileFis = new FileInputStream(keyFile);
byte[] encryptedKey = new byte[128];
keyFileFis.read(encryptedKey);
byte[] realFileKey = cipher.doFinal(encryptedKey, 0, encryptedKey.length);
Key realKey = // THE PROBLEM!!!;
keyFileFis.close();
简而言之,我从密钥文本文件中获取加密密钥并对其进行解密,现在我将解密后的密钥作为一个字节数组,我该如何再次将其设为 Key 变量?
我是这样生成密钥的:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
Key secKey = keyGen.generateKey();
cipher.init(Cipher.ENCRYPT_MODE, secKey);
并以这种方式加密:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
PrivateKey privateKey = kp.getPrivate();
Cipher keyCipher = Cipher.getInstance("RSA");
keyCipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] encryptedKey = keyCipher.doFinal(secKey.getEncoded());
FileOutputStream keyStream = new FileOutputStream("key.txt");
keyStream.write(encryptedKey);
keyStream.close();
【问题讨论】:
-
您能分享一下您是如何生成存储在文件中的密钥的吗?算法?长度?
-
只是为了确定!您使用“新生成的”
RSA私钥加密您的aes密钥并将其保存到文件中。但是您希望使用密钥库中的公钥对其进行解密!这对我来说没有意义。您应该使用密钥库中的私钥来使其工作。 -
@Akdeniz,除了从密钥库解密之外,我的密钥是 RSA 公钥,所以我可以拥有 RSA 私钥,所以我可以解密我的 AES 密钥。使用 RSA 加密 AES 密钥是练习的要求之一,如果您有更好的设计方案,我很乐意听到 :)
标签: java public-key cryptoapi