我遇到了另一个StackOverflow用户编写的RSA加密/解密的解释,我实现了代码。到目前为止,加密没有问题。我也实现了解密,到目前为止没有出现任何错误。
但是,解密的OutputStream.write
功能不会在目录中保存/写入假定的解密文件。它运行没有错误,但与加密不同,它不返回任何文件。我在写加密文件时使用相同的方法作为解密,但它没有返回任何文件。它运行时也没有错误。
以下是我的解密代码。请注意我使用不同的类加密/解密。与示例不同,我在两个类中都使用loadkey
函数。
链接到我用作参考的答案:Issues in RSA encryption in Java class
我的解密课:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String key=jTextField2.getText();
String cleartextFile = "C:\\keys\\naan.docx";
String ciphertextFile = jTextField1.getText();
loadKey(new File(key), "C:\\keys\\private.key");
decrypt(new File(ciphertextFile), new File("cleartextFile"));
} catch (GeneralSecurityException ex) {
Logger.getLogger(OpenFileDec.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(OpenFileDec.class.getName()).log(Level.SEVERE, null, ex);
}
}
private PrivateKey readPrivateKeyFromFile(String keyFileName) throws Exception {
InputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey pubKey = fact.generatePrivate(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
public void loadKey(File in, String privateKeyFile) throws GeneralSecurityException, IOException {
try {
// read private key to be used to decrypt the AES key
byte[] encodedKey = new byte[(int)privateKeyFile.length()];
new FileInputStream(privateKeyFile).read(encodedKey);
// create private key
//PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
//KeyFactory kf = KeyFactory.getInstance("RSA");
//PrivateKey pk = kf.generatePrivate(privateKeySpec);
PrivateKey pk = this.readPrivateKeyFromFile(privateKeyFile);
// read AES key
pkCipher.init(Cipher.DECRYPT_MODE, pk);
aesKey = new byte[AES_Key_Size/8];
CipherInputStream is = new CipherInputStream(new FileInputStream(in), pkCipher);
is.read(aesKey);
aeskeySpec = new SecretKeySpec(aesKey, "AES");
} catch (Exception e) {
}
}
public void decrypt(File in, File out) throws IOException, InvalidKeyException {
aesCipher.init(Cipher.DECRYPT_MODE, aeskeySpec);
CipherInputStream is = new CipherInputStream(new FileInputStream(in), aesCipher);
FileOutputStream os = new FileOutputStream(out);
copy(is, os);
os.close();
}
private void copy(InputStream is, OutputStream os) throws IOException {
int i;
byte[] b = new byte[1024];
while((i=is.read(b))!=-1) {
os.write(b, 0, i);
new Thread(new thread1()).start(); //Start the thread
}
}
答案 0 :(得分:1)
我猜测新线程的启动引发了异常并且它在loadkey()方法中被捕获,但是在将输出短接到从未关闭的文件之前没有。