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;
}

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.