我有一个java程序,用随机生成的密钥加密文件内容。 该密钥用RSA加密并保存到文本文件中。java - 从字节数组中获取密钥
现在,我有一个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();
总之,我得到了关键的文本文件中的加密密钥和解密,现在我有解密密钥的字节数组,我会怎么做它又是一个关键变量?
我已经生成的关键是这样的:
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();
你能分享你如何生成存储在文件密钥?算法?长度? – Akdeniz
更新了我的文章 – MichBoy
只是要确定!你使用“新生成的”RSA私钥加密你的'aes'键并保存到文件中。但你期望用你的密钥库中的公钥解密它!这对我没有意义。你应该使用keystore中的私钥来使它工作。 – Akdeniz