私は暗号化されており、このようなファイルに書き込まれているいくつかのアカウント情報があります。暗号化されたテキストをファイルから読み込み、復号化するにはどうすればよいですか?
//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();
}
}
}
}
ので、ファイルの内容は、その間の任意の中断することなく、1つの文字列です。
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
は、暗号化処理のように使用したのと同じであると正常に動作しますが、私は、ファイルから暗号化されたテキストを読みしようとすると:私は、文字列の暗号化を解除したい場合は、私はこれを行うだろうFileReaderのとBufferedReaderを使用して、あなたが任意の復号化を実行しようとする前に、それは
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
これは、リソースを自分で閉じるのではなく、2017、try ** with try-with-resources **です。 –