how to encypt a .txt file and how to decrypt a same .txt file when i need
843810Sep 7 2003 — edited Sep 17 2003My requirement is i want to encrypt a .txt file and
keep it in some folder. In that file we put database connection
information. when ever we need that file we have to access it and decrypt
it. with that decrypted values we have make connection with database.
i am sending a code in which i wrote both encyption and decrytion in same file, but i want to do it separately.
Please help me regarding this.
package com.businessobjects;
import java.io.*;
import java.security.*;
import javax.crypto.*;
public class EncryptDecrypt
{
public static void EncodeIt()
{
try
{
// generate Cipher objects for encoding and decoding
Cipher itsocipher1 = Cipher.getInstance("DES");
Cipher itsocipher2 = Cipher.getInstance("DES");
// generate a KeyGenerator object
KeyGenerator KG = KeyGenerator.getInstance("DES");
System.out.println("Using algorithm " + KG.getAlgorithm());
// generate a DES key
Key mykey = KG.generateKey();
// initialize the Cipher objects
System.out.println("Initializing ciphers...");
itsocipher1.init(Cipher.ENCRYPT_MODE, mykey);
itsocipher2.init(Cipher.DECRYPT_MODE, mykey);
// creating the encrypting cipher stream
//System.out.println("Creating the encrypting cipher stream...");
/*FileInputStream fis = new FileInputStream("Original.txt");
FileOutputStream fos = new FileOutputStream("Encypt.txt");
CipherInputStream cis1 = new CipherInputStream(fis, itsocipher1);
// creating the decrypting cipher stream
//System.out.println("Creating the decrypting cipher stream...");
byte[] b1 = new byte[8];
int i1 = cis1.read(b1);
while (i1 != -1)
{
fos.write(b1, 0, i1);
i1 = cis1.read(b1);
}
fis.close();
fos.close();*/
// writing the decrypted data to output file
FileInputStream fis1 = new FileInputStream("Encypt.txt");
FileOutputStream fos1 = new FileOutputStream(Decypt.txt");
CipherInputStream cis2 = new CipherInputStream(fis1, itsocipher2);
byte[] b2 = new byte[8];
int i2 = cis2.read(b2);
while (i2 != -1)
{
fos1.write(b2, 0, i2);
i2 = cis2.read(b2);
}
fis1.close();
fos1.close();
//cis1.close();
cis2.close();
}
catch (Exception e)
{
System.out.println("Caught exception: " + e);
}
}
}
With regards
Pavankumar.