Recent

How to encrypt or decrypt a file in java



EncryDecry.java:




/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.techzoop.games;

/**
 *
 * @author Arpan
 */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class EncryDecry {

public static void main(String[] ar) {
try {
String key_txt = "techzoop"; // needs to be at least 8 characters for DES

FileInputStream fis = new FileInputStream("C:\\Users\\USER\\Desktop\\export\\1.jpg");
FileOutputStream fos = new FileOutputStream("C:\\Users\\USER\\Desktop\\export\\encrypted_file.jpg");
func_encrypt(key_txt, fis, fos);

FileInputStream fis2 = new FileInputStream("C:\\Users\\USER\\Desktop\\export\\encrypted_file.jpg");
FileOutputStream fos2 = new FileOutputStream("C:\\Users\\USER\\Desktop\\export\\decrypted_file.jpg");
func_decrypt(key_txt, fis2, fos2);
} catch (Throwable e) {
e.printStackTrace();
}
}

public static void func_encrypt(String key_txt, InputStream is, OutputStream os) throws Throwable {
encrypt_Decrypt(key_txt, Cipher.ENCRYPT_MODE, is, os);
}

public static void func_decrypt(String key_txt, InputStream is, OutputStream os) throws Throwable {
encrypt_Decrypt(key_txt, Cipher.DECRYPT_MODE, is, os);
}

public static void encrypt_Decrypt(String key_txt, int mode, InputStream is, OutputStream os) throws Throwable {

DESKeySpec dks = new DESKeySpec(key_txt.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE

if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}

public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}

}




***If you are facing any issues, then feel free to ask us.





Share on Google Plus

About Techzoop

    Google+ Comment
    Facebook Comment

2 comments:

  1. Nice work admin...

    I was searching this problem and I just found this...
    thank you

    ReplyDelete