Skip to main content

encry/the file by password in JAVA

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
chuikingman
Offline
Joined: 2012-07-26
Points: 0

Hi,
Any example.sample java program that use AES/DES for encry/decry the file with hardcoded password( text or bytes) ??
I need encry/decry the file , not string .

Thank

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
mohana_sundaram
Offline
Joined: 2012-08-02
Points: 0

Just Try This....

package pack;
import java.io.*; 
import javax.crypto.*; 
import javax.crypto.spec.*; 
import java.io.File; 
import java.io.FileInputStream; 
import javax.crypto.CipherInputStream; 
import javax.crypto.Cipher; 
 
 
public class Encryptfile { 
     public static void main(String args[]) { 
     
     if (args.length < 1) { 
          System.out.println("Usage: java EncryptFile <file name>"); 
          System.exit(-1); 
     } 
 
     try  { 
     File desFile = new File("encrypt.des"); 
      FileInputStream fis=null; 
     FileOutputStream fos; 
     CipherInputStream cis; 
 
     // Creation of Secret key 
    byte key[] = "abcdEFGH".getBytes();  
    SecretKeySpec secretKey = new SecretKeySpec(key,"DES"); 
 
     // Creation of Cipher objects 
  Cipher encrypt =  Cipher.getInstance("DES/ECB/PKCS5Padding"); 
  encrypt.init(Cipher.ENCRYPT_MODE, secretKey); 
 
     // Open the Plaintext file 
     try { 
         
         fis = new FileInputStream(args[0]); 
        fis = new FileInputStream(args[0]); 
     } catch(IOException err) { 
          System.out.println("Cannot open file!"); 
          System.exit(-1); 
     } 
     
     
     // Write to the Encrypted file 
      //AT THIS PLACE ERROR IS COMING  fis variable might not have been initalized 
      cis = new CipherInputStream(fis,encrypt); 
      fos = new FileOutputStream(desFile); 
      byte[] b = new byte[8]; 
      int i = cis.read(b); 
      while (i != -1) { 
          fos.write(b, 0, i); 
          i = cis.read(b); 
     } 
     fos.flush(); 
     fos.close(); 
     cis.close(); 
     fis.close(); 
     } catch(Exception e){ 
          e.printStackTrace(); 
     } 
     } 
}