DES3 Encryption example in JDK1.4

  • 18 years ago

    Since DES3 has used more and more popular, here I show how to perform DES3 encryption. It compiled in JDK1.4, works


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


    public class DES3Encryption {
       public static void main(String[] args) throws Exception {
               Security.addProvider(new com.sun.crypto.provider.SunJCE());


               DESKeySpec keySpec        = new DESKeySpec("24characterpassword12345".getBytes());
               SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
           Key key            = keyFactory.generateSecret(keySpec);


               Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");


               byte[] data = "Hello World!    ".getBytes();
               System.out.println("Original data : " + new String(data));


               cipher.init(Cipher.ENCRYPT_MODE, key);
               byte[] result = cipher.doFinal(data);
               System.out.println("Encrypted data: " + toByteArrayString(result));


               cipher.init(Cipher.DECRYPT_MODE, key);
         
               byte[] original = cipher.doFinal(result);
               System.out.println("Decrypted data: " + new String(original));
         
       }


       public static String toByteArrayString(byte bBuf[]) {
       StringBuffer buf = new StringBuffer();


       for (int i = 0; i < bBuf.length; i++) {
           buf.append(to2Digit(bBuf));
       }
       return buf.toString();
       }
       public static String to2Digit(byte b) {
       String s = "0" + Integer.toHexString(b);
       return s.substring(s.length() - 2, s.length());
       }
    }

Post a reply

No one has replied yet! Why not be the first?

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In order to understand recursion, one must first understand recursion.”