我相信我正在做這個權利。我怎麼看解密與RSA文件:RSA解密打印NULL
- 讀取該文件的每一行作爲
String
- 設置
cipher.init(Cipher.DECRYPT_MODE, privateKey)
- 字符串轉換爲
char[]
使用Hex.decodeHex(String.toCharArray())
- 最後做
cipher.doFinal(x)
聽起來來嗎?我正在這樣做,但它不起作用,DecryptedFile.txt
只是兩行「null」。
我能夠使用幾乎相同的確切過程進行加密,但顯然與cipher.init(Cipher.ENCRYPT_MODE, publicKey)
。
這裏是我的代碼
try {
BufferedReader inStream = new BufferedReader (new FileReader(cryptoFile));
int k = 0;
fileContents.add(inStream.readLine());
while(fileContents.get(k) != null) {
k++;
fileContents.add(inStream.readLine());
}
inStream.close();
try {
PrivateKey privateKey = kp.getPrivate();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int j = 0;
while(fileContents.get(j) != null) {
String text = fileContents.get(j);
try {
x = Hex.decodeHex(text.toCharArray());
y = cipher.doFinal(x);
} catch (DecoderException ex) {
Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
}
try (PrintWriter file = new PrintWriter(
new BufferedWriter(
new FileWriter("DecryptedFile.txt", true)))) {
file.println(y);
} catch (IOException e) {
System.err.println("IOERROR: " + e.getMessage() + "\n");
}
j++;
}
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException e) {
System.err.println("IOERROR: File NOT Found: " + cryptoFile + "\n");
} catch (IOException e) {
System.err.println("IOERROR: " + e.getMessage() + "\n");
} finally {
messagePane.setText(messagePane.getText() + "\n\n"
+ cryptoFile + "is done being decrypted.");
messagePane.setText(messagePane.getText() + "\n"
+ "Decrypted file saved to \'DecryptedFile.txt\'.");
cryptoFile = "";
pathTextField.setText(cryptoFile);
encryptButton.setEnabled(false);
decryptButton.setEnabled(false);
}
RSA實際上是一個緩慢的算法 - 通常你不會用它來加密文件,而是用AES加密文件,然後用RSA加密AES密鑰。 – 2013-04-25 01:26:44
@ Zim-ZamO'Pootertoot我必須爲我班的最終項目編寫我選擇的程序,並且我們被告知必須在其中使用RSA。 – pattmorter 2013-04-25 01:29:46
嘿,在這種情況下,不用擔心 - 只是不要在生產代碼 – 2013-04-25 01:30:22