[英]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.