Criptare e decriptare file in Java
Con Java eseguire operazioni di crypting / decrypting è abbastanza semplice usando il package javax.crypto.
Vediamo un esempio; create un file di testo con dentro quello che volete.
Questo file sarà prima criptato, e poi decriptato in un altro file per vedere il risultato.
Creeremo un metodo che verrà richiamato per entrambe le operazioni.
Questo il codice completo:
import java.io.*;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static void main(String args[]) {
String key = "dfgfdgdfgfdlwerknwkfjewh";
File inputFile = new File("test.txt");
File encryptedFile = new File("test.encrypted");
File decryptedFile = new File("test-decrypted.txt");
execCryptDecrypt(Cipher.ENCRYPT_MODE, key, inputFile, encryptedFile);
execCryptDecrypt(Cipher.DECRYPT_MODE, key, encryptedFile, decryptedFile);
System.out.println("Operazioni eseguite con successo!");
}
private static void execCryptDecrypt(int cipherMode, String key,
File inputFile, File outputFile) {
try {
Key secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(cipherMode, secretKey);
byte[] inputBytes;
try (FileInputStream inputStream = new FileInputStream(inputFile)) {
inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
}
byte[] outputBytes = cipher.doFinal(inputBytes);
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
outputStream.write(outputBytes);
}
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException e) {
e.printStackTrace();
}
}
}
Come vedete il metodo lo chiamiamo due volte, passando due modalità diverse (Cipher.ENCRYPT_MODE e Cipher.DECRYPT_MODE).
La chiave di criptaggio dovete impostarla voi; io ho messo lettere a caso, voi scegliete quella che più vi piace.
Enjoy!
java chiper crypto secretkeyspec aes
Commentami!