Encrypting a String with DES

This example implements a class for encrypting and decrypting strings using DES. The class is created with a key and can be used repeatedly to encrypt and decrypt strings using that key.
public class DesEncrypter {
    Cipher ecipher;
    Cipher dcipher;

    DesEncrypter(SecretKey key) {
        try {
            ecipher = Cipher.getInstance("DES");
            dcipher = Cipher.getInstance("DES");
            ecipher.init(Cipher.ENCRYPT_MODE, key);
            dcipher.init(Cipher.DECRYPT_MODE, key);

        } catch (javax.crypto.NoSuchPaddingException e) {
        } catch (java.security.NoSuchAlgorithmException e) {
        } catch (java.security.InvalidKeyException e) {
        }
    }

    public String encrypt(String str) {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }

    public String decrypt(String str) {
        try {
            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}
Here's an example that uses the class:
try {
    // Generate a temporary key. In practice, you would save this key.
    // See also Encrypting with DES Using a Pass Phrase.
    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // Create encrypter/decrypter class
    DesEncrypter encrypter = new DesEncrypter(key);

    // Encrypt
    String encrypted = encrypter.encrypt("Don't tell anybody!");

    // Decrypt
    String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

Comments

18 Feb 2010 - 3:26am by Allan Dsouza (not verified)

nice code! didnt run on my PC!

3 Mar 2010 - 1:38pm by Nishanth (not verified)

Got it working, thanks for the code

@Allan Dsouzaa: hey just add these import statements at the beginning to get it running.

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.io.*;

16 Mar 2010 - 8:16pm by Navin (not verified)

If you are using Eclipse do the following steps
1. Open project properties.
2. Select Java Build Path node.
3. Select Libraries tab.
4. Remove JRE System Library.
5. Add Library JRE System Library.
6. Select workspace default library

17 Mar 2010 - 8:31am by Gordon (not verified)

Thanks,

This is a brilliant code, but is it possible to amend the code to demostrate how to save the key for future use.

18 Mar 2010 - 1:58am by Prathap (not verified)

I tried this but it shows IlligalBlockSizeException while decrypting it. i used this module in my chat application which uses thread concept. can you help on this issue?.

25 Mar 2010 - 5:14am by rohit (not verified)

Yes i have the same prob of IllegalBlockSize when using in my application which is coded in java swing...

29 Mar 2010 - 9:57am by lastmoh7 (not verified)

Thank you.
can you please post an example of 128 bit encryption

31 Mar 2010 - 8:36am by Anonymous (not verified)

The following is the code I have in my class and iam getting a java.lang.SecurityException: The SunJCE provider may have been tampered. at runtime while executing
the method buildCipher specifically at Cipher.getInstance( "DESede/ECB/PKCS5Padding"); any guidence on why it is so would he very helpful.

FYI: I am using JDK 1.6 and I have the sunjce_provider.jar, jce1_2_2.jar in my WEB-INF/lib folder

public TrippleDESCipher() throws DESCipherException {
init( DEFAULT_KEY );
buildCiphers();
}

private void init( byte[] akey ) throws DESCipherException {

String method = thisClassName + ".init";
Trace.fwInfo( "+" + method );

ByteArrayInputStream keyIn = null;
try {
if ( Security.getProvider( ( TrippleDESCipher.SUNPROVIDER ).getName() ) == null ) {
Security.addProvider( TrippleDESCipher.SUNPROVIDER );
}
keyIn = new ByteArrayInputStream( akey );
ObjectInputStream keyObjectStream = new ObjectInputStream( keyIn );
this.key = ( Key ) keyObjectStream.readObject();
keyIn.close();
}
catch( Exception ex ) {
ex.printStackTrace();
String message = "Unable to convert the byte array into a 'key' object";
Trace.fwError( "-" + method + " - " + message, ex );
throw new DESCipherException( ex, message, thisClassName + ":1001" );
}

//finished
Trace.fwInfo( "-" + method );

}

private void buildCiphers() throws DESCipherException {

String method = thisClassName + ".buildCipher";
Trace.fwInfo( "+" + method );

try {
this.encryptCipher = Cipher.getInstance( "DESede/ECB/PKCS5Padding");
this.encryptCipher.init( Cipher.ENCRYPT_MODE, key );
this.decryptCipher = Cipher.getInstance( "DESede/ECB/PKCS5Padding");
this.decryptCipher.init( Cipher.DECRYPT_MODE, key );
}
catch( Exception ex ) {
String message = "Unable to obtain a cipher instance";
Trace.fwError( "-" + method + " - " + message, ex );
throw new DESCipherException( ex, message, thisClassName + ":1010" );
}

Trace.fwInfo( "-" + method );

}

Exception Stacktrace:
java.lang.SecurityException: The SunJCE provider may have been tampered.
11:22:20,304 ERROR [STDERR] at com.sun.crypto.provider.SunJCE.a(DashoA13*..)
11:22:20,304 ERROR [STDERR] at com.sun.crypto.provider.DESedeCipher.(DashoA13*..)
11:22:20,304 ERROR [STDERR] at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
11:22:20,304 ERROR [STDERR] at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
11:22:20,304 ERROR [STDERR] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
11:22:20,304 ERROR [STDERR] at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
11:22:20,304 ERROR [STDERR] at java.lang.Class.newInstance0(Class.java:355)
11:22:20,304 ERROR [STDERR] at java.lang.Class.newInstance(Class.java:308)
11:22:20,304 ERROR [STDERR] at javax.crypto.Cipher.getCipherImplementation(Cipher.java:166)
11:22:20,304 ERROR [STDERR] at javax.crypto.Cipher.getInstance(Cipher.java:223)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.util.TrippleDESCipher.buildCiphers(TrippleDESCipher.java:93)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.util.TrippleDESCipher.(TrippleDESCipher.java:61)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.util.DataSourcePersistenceManager.getCipher(DataSourcePersistenceManager.java:112)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.util.DataSourcePersistenceManager.decrypt(DataSourcePersistenceManager.java:95)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.bankprofile.BankAcctManagerRoleImplSql.getUserBankAccountInfo(BankAcctManagerRoleImplSql.java:408)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.bankprofile.EpayBankProfileRoleImplSql.getUserBankAccountInfo(EpayBankProfileRoleImplSql.java:249)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.struts.action.MakePaymentPrepareAction.performSecuredAction(MakePaymentPrepareAction.java:147)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.struts.action.SecuredAction.performEpayAction(SecuredAction.java:65)
11:22:20,304 ERROR [STDERR] at com.dcs.ice.epay.struts.action.EpayAction.performAction(EpayAction.java:98)
11:22:20,304 ERROR [STDERR] at com.cfc.ice.struts.action.IceAction.perform(IceAction.java:48)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.processActionPerform(ActionServlet.java:1927)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1691)
11:22:20,304 ERROR [STDERR] at com.cfc.ice.struts.servlet.IceActionServlet.process(IceActionServlet.java:236)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:520)
11:22:20,304 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
11:22:20,304 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:638)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:444)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:382)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:310)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.processActionForward(ActionServlet.java:1896)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1701)
11:22:20,304 ERROR [STDERR] at com.cfc.ice.struts.servlet.IceActionServlet.process(IceActionServlet.java:236)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:520)
11:22:20,304 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
11:22:20,304 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:638)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:444)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:382)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:310)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.processActionForward(ActionServlet.java:1896)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1701)
11:22:20,304 ERROR [STDERR] at com.cfc.ice.struts.servlet.IceActionServlet.process(IceActionServlet.java:236)
11:22:20,304 ERROR [STDERR] at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:520)
11:22:20,304 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
11:22:20,304 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
11:22:20,304 ERROR [STDERR] at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
11:22:20,304 ERROR [STDERR] at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
11:22:20,304 ERROR [STDERR] at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
11:22:20,304 ERROR [STDERR] at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
11:22:20,304 ERROR [STDERR] at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
11:22:20,304 ERROR [STDERR] at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
11:22:20,304 ERROR [STDERR] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
11:22:20,304 ERROR [STDERR] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
11:22:20,304 ERROR [STDERR] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
11:22:20,304 ERROR [STDERR] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
11:22:20,304 ERROR [STDERR] at java.lang.Thread.run(Thread.java:619)

1 Jun 2010 - 12:14pm by shreyas.me (not verified)

Nice example. I have extended this further to save/retrieve the SecretKeys. Hope this helps:

private static void saveKeyToFile(SecretKey key) throws FileNotFoundException, IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(".des"));
oos.writeObject(key);
oos.close();
}

private static SecretKey getKeyFromFile() throws IOException, ClassNotFoundException {
SecretKey key = null;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(".des"));
key = (SecretKey) ois.readObject();
ois.close();

return key;
}

5 Sep 2010 - 7:18pm by Anonymous (not verified)

Excellent example. Many thanks!

27 Dec 2010 - 10:12pm by Yuki (not verified)

Hello anybody can show me how to decrypt data from file with saved SecretKey earlier using method from shreyas.me??

thank you

20 Jan 2011 - 8:18am by Bouma (not verified)

Thanks mate!

1 Mar 2011 - 1:04pm by Francesco Trillini (not verified)

Why for decrypting you've used Base64 and not DES?

6 Mar 2011 - 11:28pm by VInod Puliyadi (not verified)

I am using this encryption for url parameter and i am getting a back slash on encrypted string, is there any way i can escape those html characters.

7 Mar 2011 - 1:08am by Ratheesh Nair (not verified)

Try out this short cut,

/**
* From a base 64 representation, returns the corresponding byte[]
*
* @param data String The base64 representation
* @return byte[] - converted value as byte []
* @throws IOException
*/
public byte[] base64URLSafeStringToByte(String data) throws IOException {
return org.apache.commons.codec.binary.Base64.decodeBase64(data);
}
/**
* From a byte[] returns a base 64 representation
*
* @param data byte[]
* @return String - Base 64 string representation of specified byte []
* @throws IOException
*/
public String byteToBase64URLSafeString(byte[] data){
return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(data);
}

9 Jul 2011 - 8:08pm by Sombra7 (not verified)

de gran ayuda.. thanks

20 Sep 2011 - 1:42am by Anonymous (not verified)

Hey nice code and very useful. For a research work on key I need to do some thing like this.
Key must be static. Means as here each time key has been generated randomly, I want it in that way that I can set a proper key like key = 0xffff.

I am facing problem with converting a string "0xffff" into SecretKey so it can be passed properly and can work as same the above excellent code.

Thank you.

30 Nov 2011 - 3:33am by Arvind (not verified)

can the above example be done with a shared key?

16 Dec 2011 - 3:30am by Anonymous (not verified)

hi

29 Jan 2012 - 2:17am by Justice (not verified)

That's not just the best asnewr. It's the bestest answer!

28 Mar 2012 - 11:28am by HP (not verified)

Excellent jobs!!!! Really help for quick fix.

5 Apr 2012 - 2:20am by Zen (not verified)

works perfect -> thanx milions!!!

7 May 2012 - 6:14am by Anonymous (not verified)

java.lang.InstantiationException: com.trial.phonegap.plugin.directorylisting.DirectoryListPlugin....
please help me....

7 May 2012 - 11:55pm by riya (not verified)

Runs perfectly fine on my pc.
Really helpful.
Thanks.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.