AES 暗号化/復号化メソッドを作成しようとしていますが、AES/ECB/NoPadding を使用しないと元の入力を取得できないようです。現在、AES/CBC/PKCS7Padding を使用しようとしています。ファイルへのバイトの読み書きが正常に動作することを確認しました。PKCS7 パディングを使用すると、BadPaddingException が発生します
cipher.doFinal(encrypted)
復号化メソッドで。パディングなしでも例外はありませんが、出力はスクランブルされます。このまったく同じ問題について他の投稿に時間を費やしましたが、私の問題に合った解決策が見つからないようです。
その出力のスクランブルを解除するにはどうすればよいですか?
protected boolean encrypt(String place, String encrypt) {
try {
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(encrypt.getBytes());
Context context = HomeViewActivity.hva.getApplicationContext();
FileOutputStream writer = context.openFileOutput(file_name.get(place.toUpperCase()), Context.MODE_PRIVATE);
writer.write(encrypted);
writer.close();
return true; //successfully wrote encrypted string to file
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
protected String decrypt(String place){
String decrypted = null;
try{
Context context = HomeViewActivity.hva.getApplicationContext();
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
FileInputStream reader = context.openFileInput(file_name.get(place.toUpperCase()));
byte[] encrypted = new byte[reader.available()];
reader.read(encrypted);
reader.close();
decrypted= new String(cipher.doFinal(encrypted));
}catch(FileNotFoundException e){return null;}
catch(IllegalBlockSizeException |
BadPaddingException |
InvalidKeyException |
NoSuchAlgorithmException |
IOException |
NoSuchPaddingException e){e.printStackTrace();}
return decrypted;
}
編集 1: ファイルから読み取った暗号化された配列を適切なサイズにしました
編集 2: 各メソッドの代わりにコンストラクターで初期化されたキーと暗号