The Kahimyang Project Logo
Primo's Code Blog
Howtos tips and tricks
The Kahimyang Project

Encrypting plain text using Java Cryptography Extension

One way or another your project needs a string encrypter. From encrypting passwords saved in text files to encrypting entire files, this class is a handy companion.



package YOUR-PACKAGE;

import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class Encrypter {

    public Encrypter(String scheme) {
        this(scheme, DEFAULT_ENCRYPTION_KEY);
    }

    public Encrypter(String scheme, String key) {

        if (key == null || 
                key.trim().length() < 24) {
            return;
        }

        try {

            byte keyAsBytes[] = key.getBytes(UNICODE_FORMAT);
            if (scheme.equals(DESEDE_ENCRYPTION_SCHEME)) {
                keySpec = 
                  new DESedeKeySpec(keyAsBytes);
            } else if 
                 (scheme.equals(DES_ENCRYPTION_SCHEME)) {
                keySpec = new DESKeySpec(keyAsBytes);
            } else {
                return; // or throw
            }

            keyFactory = 
                SecretKeyFactory.getInstance(scheme);
            cipher = Cipher.getInstance(scheme);

        } catch (Exception e) {
            // do something
        }
    }

    public String encrypt(String unencrypted) {

        if (unencrypted == null || 
                 unencrypted.trim().length() == 0) {
            return null;
        }

        try {

            javax.crypto.SecretKey key = 
                      keyFactory.generateSecret(keySpec);
            cipher.init(1, key);
            byte cleartext[] = 
                      unencrypted.getBytes(UNICODE_FORMAT);
            
            //
            byte ciphertext[] = cipher.doFinal(cleartext);

            BASE64Encoder base64encoder = new BASE64Encoder();
            return base64encoder.encode(ciphertext);


        } catch (Exception e) {
            return null;
        }
    }

    public String decrypt(String encrypted) {

        if (encrypted == null || 
                encrypted.trim().length() == 0) {
            return null;
        }

        try {

            javax.crypto.SecretKey key = 
                   keyFactory.generateSecret(keySpec);
            cipher.init(2, key);
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte cleartext[] = 
                   base64decoder.decodeBuffer(encrypted);

	    // 
            byte ciphertext[] = cipher.doFinal(cleartext);

            return bytes2String(ciphertext);

        } catch (Exception e) {
            return null;
        }
    }

    private static String bytes2String(byte bytes[]) {

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            stringBuffer.append((char) bytes[i]);
        }

        return stringBuffer.toString();

    }

    public static final String 
            DESEDE_ENCRYPTION_SCHEME = "DESede";
    public static final String 
            DES_ENCRYPTION_SCHEME = "DES";

    // At least 24 characters
    public static final String DEFAULT_ENCRYPTION_KEY =
         "THIS IS YOUR ENCRYPTION KEY, CHANGE TO DESIRED TEXT KEY";
    private KeySpec keySpec;
    private SecretKeyFactory keyFactory;
    private Cipher cipher;
    private static final String UNICODE_FORMAT = "UTF8";


    // Convience for DES scheme
    public static String E(String S) {
        Encrypter e = new Encrypter("DES");
        return e.encrypt(S);
    }

    public static String D(String S) {
        Encrypter e = new Encrypter("DES");
        return e.decrypt(S);
    }
}

How to use the class

   // Encrypt a string
   String e =  Encrypter.E (string-to-encrypt);

   // Decrypt a string
   String d =  Encrypter.D (encrypted-string);

The class is tested to work as expected.

Good luck.

RSS Logo



Comment icon   Comments (Newest first)

Recent posts in Java/JSF category
Blue dot icon Using Rhinoslider with image and youtube content in JSF pages
Blue dot icon A dynamic standard sitemap.xml with Google image extension implemented as a Java Servlet
Blue dot icon Creating a Facebook-like panel with slim scrollbars and infinite scrolling in PrimeFaces
Blue dot icon Generating XML RSS 2 feeds with JDOM 2 with a servlet
Blue dot icon Building a page with infinite scroll in PrimeFaces using Waypoints jQuery plugin
Blue dot icon Implementing a collapsible ui:repeat rows in JSF
Blue dot icon Validating an email address in PrimeFaces p:inputText field with p:ajax





Most popular articles
Blue dot icon Using Expect script to automate SSH logins and do routine tasks accross multiple hosts   (15359)
Blue dot icon How to setup Tomcat 7 as your primary webserver on Debian Squeeze    (14073)
Blue dot icon How to setup FLV streaming with crtmpserver C++ RTMP server   (9836)
Blue dot icon A Java class for sending multipart Email messages through your Gmail account    (6975)
Blue dot icon How to use Google Translate's Text to Speech (TTS) services in your web page using Servlet   (5669)
Blue dot icon Speed up Primefaces page load with p:remoteCommand partial update   (5484)
Blue dot icon Building a mobile website with JSF 2 core and JQuery Mobile 1.0   (5319)
Blue dot icon Google Map-Adding markers, info window, circle, small control, and events in Javascript    (5221)