Quantcast
Channel: DiKnows. » Uncategorized
Viewing all articles
Browse latest Browse all 10

Java Encryption Class Example

$
0
0

Encryption is a weird and hard topic. I have never liked it, yet its essential to know the encryption algorithms and have their implementation in the programming language we use.

So far, I have never get to code anything related to encryption. But, lately I had to get my hands dirty with some encryption related code.
So, I created a POC ( Proof Of Concept ) Maven project, that make use of DES encryption.
So, Cutting to the chace, here is the class :


package com.diknows.ccencryption;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;

/**
*
* @author dino
*/
public class EncryptionUtil implements Serializable {

private Key key;
private static final String fileName = "diknows.com.keys";
private byte[] iv;

public EncryptionUtil() {
try {
KeyGenerator kg = KeyGenerator.getInstance("DES");
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");

this.key = kg.generateKey();
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}

public String decrypt(byte[] encryptedInput) {
try {
saveKeyOnce(fileName, this.key);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
IvParameterSpec dpss = new IvParameterSpec(iv);
c.init(Cipher.DECRYPT_MODE, this.key, dpss);
byte[] decrypted = c.doFinal(encryptedInput);
return new String(decrypted);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return "";
}

public byte[] encrypt(String str) {
try {
saveKeyOnce(fileName, this.key);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, this.key);
this.iv = c.getIV();
IvParameterSpec dpss = new IvParameterSpec(iv);
byte[] b = c.doFinal(str.getBytes());
return b;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(EncryptionUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return new byte[0];
}

private void saveKeyOnce(String fileName, Object key) {
if (!(new File(fileName).exists())) {
try {
CommonFileUtils.instance().saveToFile(fileName, key);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

}

And a helping Utility class that I used :


package com.diknows.ccencryption;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
* Common File Utils .. That are used commonly with lots of subjects
* @author dino
*/
public class CommonFileUtils {

public static CommonFileUtils instance;

/**
* Holds one instance for caching facilities.
* @return The common object.
*/
public static CommonFileUtils instance(){
if(instance==null)
instance= new CommonFileUtils();
return instance;
}

/**
* @param fileName The file name to read object from
* @return The object read from the file
* @throws IOException
*/
public Object readFromFile(String fileName) throws IOException {
InputStream in = new FileInputStream(fileName);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
return oin.readObject();
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}

/**
* Saves an object into a file
* @param fileName The file name to save to
* @param obj The object to be saved
* @throws IOException
*/
public void saveToFile(String fileName, Object obj) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oout.writeObject(obj);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
oout.close();
}
}

/**
* Deserialize an object from byte array
* @param byteArr The byte array holding the object
* @return The object after deserialization
* @throws java.io.IOException
* @throws ClassNotFoundException
*/
public Object getObjectFromByteArr(byte[] byteArr) throws
java.io.IOException, ClassNotFoundException {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(byteArr));
Object obj = in.readObject();
in.close();
return obj;
}
/**
* Converts an object into byte array
* @param obj The object to convert
* @return The byte array holding the object
* @throws java.io.IOException
*/
public byte[] getBlobFromObject(Object obj) throws
java.io.IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(obj);
byte[] bytes = out.toByteArray();
objOut.close();
return bytes;
}
}

and the main class is just like that :


package com.diknows.ccencryption;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* Hello world!
*
*/
public class App {
static String dpsFileName = "diknows.com.enc";

public static void main(String[] args) {
try {
EncryptionUtil enc = new EncryptionUtil();
// Encryption
byte[] encrypted = enc.encrypt("Hello World");
CommonFileUtils.instance().saveToFile(dpsFileName, enc);
// Before Decryption
EncryptionUtil encs = (EncryptionUtil) CommonFileUtils.instance().readFromFile(dpsFileName);
String s = encs.decrypt(encrypted);
System.out.println("After Decription : " + s);
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

And that is it … I really can’t explain it all, but something I had to do, is storing the EncryptionUtil object for each encryption with the encrypted value, That was the only way I could do it. I will research more about encryption, and hopfully I will post another post that make a better usage of encryption implementations.
Please, if you have any suggestion, or better implementation please share.

The Downloadable File is : Encryption Maven Project File.


Viewing all articles
Browse latest Browse all 10

Trending Articles