我試圖通過這種方式來我的文件加密:無法解密加密文件?
加密:
static void encrypt(String strInput , String strOutput) throws IOException,
NoSuchAlgorithmException,NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(strInput);
FileOutputStream fos = new FileOutputStream(strOutput);
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}
和解密回:
解密:
static String decrypt(String strInput) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(strInput);
int endFile = strInput.length() - 4;
String strOut = strInput.substring(0, endFile) + "xx.jpg";
FileOutputStream fos = new FileOutputStream(strOut);
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
return strOut;
}
然而,結果文件的大小是0 kb,當我嘗試t時roubleshoot b = cis.read(d)
在解密,總是返回-1,也cis.available()
總是返回0.任何人都可以告訴我我的代碼哪部分是錯誤的?
注:我可以確保將要解密的文件始終存在。
這段代碼實際上在我的機器上工作。我們可以看到你調用的加密和解密代碼嗎?也許你打電話解密與錯誤的參數? – Francis
嗯,不這麼認爲,因爲我只通過filePath加密和解密方法.. – Rendy
Btw @Francis你也試過圖片嗎? – Rendy