Tuesday, January 22, 2013

Program for file encryption-decryption using RSA

The following code is written in java for encrypting-decrypting a text file named "main.txt".

Code for RSAfile.java:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
public class RSAfile {
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA");
kpg.initialize(1024);
KeyPair keyPair = kpg.generateKeyPair();
PrivateKey privKey = keyPair.getPrivate();
PublicKey pubKey = keyPair.getPublic();
// Encrypt
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String cleartextFile = "main.txt";
String ciphertextFile = "ciphertextRSA.txt";
FileInputStream fis = new FileInputStream(cleartextFile);
FileOutputStream fos = new FileOutputStream(ciphertextFile);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
byte[] block = new byte[32];
int i;
while ((i = fis.read(block)) != -1) {cos.write(block, 0, i);}
cos.close();
// Decrypt
String cleartextAgainFile = "decrypt.txt";
cipher.init(Cipher.DECRYPT_MODE, privKey);
fis = new FileInputStream(ciphertextFile);
CipherInputStream cis = new CipherInputStream(fis, cipher);
fos = new FileOutputStream(cleartextAgainFile);
while ((i = cis.read(block)) != -1) { fos.write(block, 0, i);}
fos.close();
}
}


Make three text files named main.txt , ciphertextRSA.txt & decrypt.txt and save it in the same folder as the java code or else specify the path of the file in the code.

Compile the RSAfile.java


Then open the the files and see the change!