[英]How can I read an encrypted text from a file and decrypt it?
我有一些帳戶信息正在加密並寫入到這樣的文件中:
//imports here
public class Main
public static void main(String[] args) {
try {
String text = "this text will be encrypted";
String key = "Bar12345Bar12345";
//Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
//encrypt text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
write(new String(encrypted));
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
}
public static void write(String message) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
String data = message;
File file = new File(FILENAME);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
因此,文件的內容是一個字符串,之間沒有任何中斷。 如果我想解密字符串,可以這樣做:
String key = "Bar12345Bar12345";
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
byte[] encrypted = text.getBytes();
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
System.err.println(decrypted);
只要byte[] encrypted
與加密過程中使用的byte[] encrypted
相同,它就可以正常工作,但是當我嘗試使用FileReader和BufferedReader從文件中讀取加密的文本並使用lines.getByte()
將其更改為字節時lines.getByte()
它引發異常
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
在嘗試進行任何解密之前,請將加密過程中的密文與lines.getByte()中的密文進行比較。 它們很可能不同。 解密之前,請先嘗試將整個文件讀取為byte []。 對稱密碼需要在相同大小的塊(在這種情況下為16個字節)上進行工作。
如果我不對某些較差的協議選擇發表評論,我也會感到失落。
加密很難自行解決。 考慮以其他方式解決問題。
您正在嘗試將encrypted
數組內容視為(平台編碼的)文本,而不是(由隨機字節組成)。
您要么需要通過直接將encrypted
內容寫入二進制文件來創建一個二進制文件。 您也可以通過首先encrypted
為base64的編碼來創建文本文件。
當前,您正在嘗試讀取行,但沒有任何行。 並且如果其中有一些行尾,則可以從密文中刪除它們,然后才能解密這些字節。
如果執行new String(encrypted)
,則還可能會丟失部分數據,因為會從字符串中刪除不支持的編碼而不會發出警告。
請注意,“密文”一詞有點誤導; 諸如AES之類的現代密碼處理二進制數據,而不是文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.