Encrypt and decrypt files in Java using Cipher class and RSA asymmetric key pairs: public key encryption and private key decryption.
In this JavaAnt guide, we walk through encrypting and decrypting files in Java using the Cipher class and the RSA algorithm.
Overview
Using Java's Cipher class and the RSA algorithm, we can securely encrypt and decrypt files.
- Cipher Class: Part of
javax.crypto, this class provides cryptographic encryption and decryption functionality. - RSA Algorithm: An asymmetric cryptographic algorithm that uses two keys. For encryption we use the public key, and for decryption we use the private key. The public key can be shared, while the private key must be kept secret.
Implementation
package com.javaant;
import java.io.File;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import org.apache.commons.io.FileUtils;
class MyRSACipher {
public static KeyPair getRSAKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
return kpg.generateKeyPair();
}
public static byte[] encryptFile(byte[] inputBytes, PublicKey key, String xform) throws Exception {
Cipher cipher = Cipher.getInstance(xform);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(inputBytes);
}
public static byte[] decryptFile(byte[] inputBytes, PrivateKey key, String xform) throws Exception {
Cipher cipher = Cipher.getInstance(xform);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(inputBytes);
}
}
public class EncryptDecryptFileRSA {
public static void main(String[] args) throws Exception {
String fileToEncrypt = "original-file.txt";
String encryptedFile = "file-after-encryption.bin";
String decryptedFile = "file-after-decryption.txt";
// Generate RSA key pair
KeyPair keyPair = MyRSACipher.getRSAKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
File file = new File(fileToEncrypt);
byte[] dataBytes = FileUtils.readFileToByteArray(file);
// Encrypt the file
String algo = "RSA/ECB/PKCS1Padding";
byte[] encryptedBytes = MyRSACipher.encryptFile(dataBytes, publicKey, algo);
FileUtils.writeByteArrayToFile(new File(encryptedFile), encryptedBytes);
System.out.println("Encrypted file: " + encryptedFile);
// Decrypt the file
byte[] decryptedBytes = MyRSACipher.decryptFile(encryptedBytes, privateKey, algo);
FileUtils.writeByteArrayToFile(new File(decryptedFile), decryptedBytes);
System.out.println("Decrypted file: " + decryptedFile);
}
}For symmetric AES encryption with GCM authentication mode, see our AES encryption tutorial.