Hi all, i'm trying to encrypt and decript a file using a user specified key. I managed to generate a random key using keygenerator. But how do I encrypt a file using a user specified passphrase?
Also, is it possible to encrypt objects instead of simply encripting a file?
Here's my code:
thank you in advance.
Also, is it possible to encrypt objects instead of simply encripting a file?
Here's my code:
thank you in advance.
Code:
import java.io.*;
import java.security.*;
import javax.crypto.*;
import java.security.AlgorithmParameters;
import java.util.*;
public class endecrypt implements Serializable{
public static void main(String argv[]) throws Exception { //main function
FileInputStream fis; //file to be encrypted
FileOutputStream fos; //encrypted file
CipherOutputStream cos; // cipher to encrypt file
//generate key with DES algorithim
KeyGenerator keygen = KeyGenerator.getInstance("DES");
SecretKey desKey = keygen.generateKey();
//Cipher
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES");
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, desKey);
//Encryption
fis = new FileInputStream("STUDENTDATA.txt"); // bring in the file to be
encrypted
fos = new FileOutputStream("ENSTUDENTDATA.txt");
cos = new CipherOutputStream(fos, desCipher);
byte[] b = new byte[8];
int i = fis.read(b);
while (i != -1) {
cos.write(b, 0, i);
i = fis.read(b);
}
cos.flush();
System.out.println("Encrypted file!!!");
// Create the cipher
desCipher = Cipher.getInstance("DES");
// Initialize the cipher for encryption
desCipher.init(Cipher.DECRYPT_MODE, desKey);
//Decrypt
fis = new FileInputStream("ENSTUDENTDATA.txt"); // bring in the file to be encrypted
fos = new FileOutputStream("DYSTUDENTDATA.txt");
cos = new CipherOutputStream(fos, desCipher);
b = new byte[8];
i = fis.read(b);
while (i != -1) {
cos.write(b, 0, i);
i = fis.read(b);
}
cos.flush();
System.out.println("Decrypted File!!!");
}
}