ファイル暗号化および復号化の Java 実装
Javaでファイルの暗号化と復号を実装するには、さまざまな暗号化アルゴリズムとIOストリームを使用できます。以下は、AES対称暗号化アルゴリズムとファイルIOストリームを使用してファイルの暗号化と復号を実装するためのサンプルコードです。
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
public class FileEncryption {
public static void encrypt(String key, File inputFile, File outputFile) throws Exception {
doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
}
public static void decrypt(String key, File inputFile, File outputFile) throws Exception {
doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
}
private static void doCrypto(int cipherMode, String key, File inputFile, File outputFile) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
if (cipherMode == Cipher.ENCRYPT_MODE) {
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
writeBytes(inputStream, cipherOutputStream);
cipherOutputStream.close();
} else if (cipherMode == Cipher.DECRYPT_MODE) {
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
writeBytes(cipherInputStream, outputStream);
cipherInputStream.close();
}
inputStream.close();
outputStream.close();
}
private static void writeBytes(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
File encryptedFile = new File("encrypted.txt");
File decryptedFile = new File("decrypted.txt");
String key = "ThisIsASecretKey";
encrypt(key, inputFile, encryptedFile);
System.out.println("File encrypted successfully.");
decrypt(key, encryptedFile, decryptedFile);
System.out.println("File decrypted successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
上記のコードでは、暗号化と復号化のためのencryptメソッド、decryptメソッドの2つを定義しています。doCryptoメソッドではAES暗号化アルゴリズムのCipherオブジェクトを作成し、鍵で初期化します。そして、暗号化と復号化のどちらのモードかによって、CipherInputStreamやCipherOutputStreamを使用してファイル内容の読み取りと書き込みを行います。暗号化と復号化で使用する鍵の長さは16、24、32バイトでなければならないので、SecretKeySpecオブジェクトを作成する際に鍵のバイト配列を使用します。
mainメソッドで、入力ファイル、暗号化後ファイル、復号化後ファイルへのパスを定義し、キーを指定しました。次に、暗号化メソッドを呼び出して入力ファイルを暗号化し、復号化メソッドを呼び出して暗号化されたファイルを復号化しました。
なお、これは単純な例示ですので、実際の利用時は個別要件に応じて最適化やセキュリティの考慮が必要です。