0
我一直在嘗試使用AES編寫加密文件,然後使用JCA中提供的密碼流進行解密。但是,在閱讀文件時,我遇到了問題,因爲解密過程很亂。使用CipherInputStream和CipherOutputStream對文件進行加密和解密
public class CipherStreams {
public static void main(String[] args) {
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Key k = keygen.generateKey();
Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes.init(Cipher.ENCRYPT_MODE, k);
FileOutputStream fs = new FileOutputStream("Encrypyed.txt");
CipherOutputStream out = new CipherOutputStream(fs, aes);
out.write("[Hello:Okay]\nOkay".getBytes());
out.close();
Cipher aes2 = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes2.init(Cipher.DECRYPT_MODE, k);
FileInputStream fis = new FileInputStream("Encrypyed.txt");
CipherInputStream in = new CipherInputStream(fis,aes2);
byte[] b = new byte[8];
int i = in.read(b);
while(i!=-1) {
System.out.print((char)i);
i = in.read(b);
}
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException ex) {
Logger.getLogger(CipherStreams.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我收到一個單字節輸出爲5.任何人都可以請幫忙指出這個問題嗎?
這工作。我沒有意識到我正在寫入讀取的字節數。謝謝! –