Sample program which uses Des3Cipher.java

Hi All,

I am supposed to encrypt and decrypt the password using Des3 algorithm. I do have Des3Cipher.java downloaded from acme.crypto site.

Plz can anyone provide me with a sample code which uses  Des3Cipher.java using two keys.

I need it on a urgent basis.

Regards

Nikhil Bansal
LVL 1
nikhilbansalAsked:
Who is Participating?
 
objectsCommented:
try something like:

Des3Cipher dec = new Des3Cipher(key1);
Des3Cipher enc = new Des3Cipher(key2);

then for each block do, increement off by 8 for each block

enc.encrypt(clear, off, encryted, off);
dec.decrypt(encrypted, off, clear, off);
enc.encrypt(clear, off, encryted, off);
0
 
CEHJCommented:
0
 
nikhilbansalAuthor Commented:
Hi Objects and CEHJ,

To be honest I am just a beginner to java.The requirement is such tht I do need to use Java in my application.

I've been handed certain java files from Acme.crypto (DES3Cipher.java)

I need a java program wherein I can encrypt and decrypt my password (min 2 characters to max 48 characters).

If possible, do provide the code for the same.Shall be extremely grateful.

Regards

Nikhil Bansal





////////////////////////////////////////Des3Cipher .java///////////////////////////////////////////


package Acme.Crypto;

import java.io.*;

public class Des3Cipher extends BlockCipher
    {

    /// Constructor, string key.
    public Des3Cipher( String keyStr )
      {
      super( 16, 8 );
      setKey( keyStr );
      }

    /// Constructor, byte-array key.
    public Des3Cipher( byte[] key )
      {
      super( 16, 8 );
      setKey( key );
      }


    // Key routines.

    private byte[] keyA = new byte[8];
    private byte[] keyB = new byte[8];

    private DesCipher desA;
    private DesCipher desB;

    /// Set the key.
    public void setKey( byte[] key )
      {
      System.arraycopy( key, 0, keyA, 0, 8 );
      System.arraycopy( key, 8, keyB, 0, 8 );
      desA = new DesCipher( keyA );
      desB = new DesCipher( keyB );
      }


    // Block encryption routines.

    byte[] temp1 = new byte[8];
    byte[] temp2 = new byte[8];

    /// Encrypt a block of eight bytes.
    public void encrypt( byte[] clearText, int clearOff, byte[] cipherText, int cipherOff )
      {
      desA.encrypt( clearText, clearOff, temp1, 0 );
      desB.decrypt( temp1, 0, temp2, 0 );
      desA.encrypt( temp2, 0, cipherText, cipherOff );
      }

    /// Decrypt a block of eight bytes.
    public void decrypt( byte[] cipherText, int cipherOff, byte[] clearText, int clearOff )
      {
      desA.decrypt( cipherText, cipherOff, temp1, 0 );
      desB.encrypt( temp1, 0, temp2, 0 );
      desA.decrypt( temp2, 0, clearText, clearOff );
      }

    }



////////////////////////////////////////BlockCipher.java///////////////////////////////////////////

// BlockCipher - a block encryption template
// Visit the ACME Labs Java page for up-to-date versions of this and other
// fine Java utilities: http://www.acme.com/java/

package Acme.Crypto;

import java.io.*;

/// A block encryption template.
// <P>
// <A HREF="/resources/classes/Acme/Crypto/BlockCipher.java">Fetch the software.</A><BR>
// <A HREF="/resources/classes/Acme.tar.gz">Fetch the entire Acme package.</A>
// <P>
// @see Cipher
// @see StreamCipher
// @see EncryptedOutputStream
// @see EncryptedInputStream
// @see DesCipher
// @see CbcBlockCipher

public abstract class BlockCipher extends Cipher
    {

    /// Constructor.
    public BlockCipher( int keySize, int blockSize )
      {
      super( keySize );
      this.blockSize = blockSize;
      }

    /// How big a block is.
    public int blockSize;

    /// Return how big a block is.
    public int blockSize()
      {
      return blockSize;
      }

    /// Encrypt a block of bytes.
    public abstract void encrypt( byte[] clearText, int clearOff, byte[] cipherText, int cipherOff );

    /// Decrypt a block of bytes.
    public abstract void decrypt( byte[] cipherText, int cipherOff, byte[] clearText, int clearOff );

    /// Encrypt a block of bytes.
    public void encrypt( byte[] clearText, byte[] cipherText )
      {
      encrypt( clearText, 0, cipherText, 0 );
      }

    /// Decrypt a block of bytes.
    public void decrypt( byte[] cipherText, byte[] clearText )
      {
      decrypt( cipherText, 0, clearText, 0 );
      }

    }


//////////////////////////////////////////////Cipher.java///////////////////////////////////////////


// Cipher - an encryption template

package Acme.Crypto;

import java.io.*;

/// An encryption template.
// <P>
// <A HREF="/resources/classes/Acme/Crypto/Cipher.java">Fetch the software.</A><BR>
// <A HREF="/resources/classes/Acme.tar.gz">Fetch the entire Acme package.</A>
// <P>
// @see StreamCipher
// @see BlockCipher
// @see EncryptedOutputStream
// @see EncryptedInputStream

public abstract class Cipher extends CryptoUtils
    {

    /// Constructor.
    public Cipher( int keySize )
      {
      this.keySize = keySize;
      }

    /// How big a key is.  Keyless ciphers use 0.  Variable-length-key ciphers
    // also use 0.
    public int keySize;

    /// Return how big a key is.
    public int keySize()
      {
      return keySize;
      }

    /// Set the key from a block of bytes.
    public abstract void setKey( byte[] key );


    // Utility routines.

    /// Utility routine to set the key from a string.
    public void setKey( String keyStr )
      {
      setKey( makeKey( keyStr ) );
      }

    /// Utility routine to turn a string into a key of the right length.
    public byte[] makeKey( String keyStr )
      {
        byte[] key;
      if ( keySize == 0 )
          key = new byte[keyStr.length()];
      else
          key = new byte[keySize];
        int i, j;

        for ( j = 0; j < key.length; ++j )
            key[j] = 0;

        for ( i = 0, j = 0; i < keyStr.length(); ++i, j = (j+1) % key.length )
            key[j] ^= (byte) keyStr.charAt( i );

      return key;
      }

    }

0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
objectsCommented:
I posted you the basics of what you need already.
you just need to add a loop to perform that for every 8 bytes (ie. increment offset by 8 each loop)
0
 
nikhilbansalAuthor Commented:
Hi objects,

I've tried the code as suggested.

However, there seems to some problem.

For eg : when I give the password as nikhil then encryption - decryption is proper.(Password length is specified as 48).

But when I give passowrd as nikhilbansal then after decrytion I get o/p as nikhilba‹ƒ¬¹tŒ
(which is not proper) .

There are few other instances where decryption is not proper

Input password                   Decrypted Output (not matching with input password)
--------------------------------------------------------------------------------------------------

      test123                 ---  „ŽF/‘€òÕ
     java_pro               ---  H?Eòî½åÈ0Ìí…åÈ0Ìí…åÈ0Ìí…åÈ0Ìí…UÊ–:P‘—
    _++testcase_         ---  &©sase_


0
 
objectsCommented:
can u post your code
0
 
nikhilbansalAuthor Commented:
Hi Objects,

Sending you the code.Let me know if you can fugure out something. Des3Cipher,BlockCipher and Cipher.java I've already posted in my previous queries.

Regards

Nikhil

/*
 * Created on Apr 4, 2006
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package EncryptTest;



/**
 * @author 160775
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.util.*;
import java.io.*;
import EncryptTest.Des3Cipher;

public class Encryption {

      public static final String plainTxtPassword      =      "10";
      public static final int         passwordLength      =      48;      
      
      public static void main(String[] args) {
            
            try
            {
                  String encryptedPassword1 =      encryptString(plainTxtPassword,passwordLength);
                  System.out.println("encryptedPassword1::1stKey::"+encryptedPassword1);
                  
                  String decryptedPassword2 =      decryptWithSecondKey(encryptedPassword1,passwordLength);
                  System.out.println("decryptedPassword2::2ndKey::"+decryptedPassword2);
                  
                  String encryptedPassword2 =      encryptString(decryptedPassword2,passwordLength);
                  System.out.println("encryptedPassword2::1stKey::"+encryptedPassword2);
                  
                  String decryptedPassword1 = decrypt(encryptedPassword2,passwordLength);
                  System.out.println("decryptedPassword1::1stKey::"+decryptedPassword1);
                  
                  String encryptedPassword3 =      encryptStringWithSecondKey(decryptedPassword1,passwordLength);
                  System.out.println("encryptedPassword3::2ndKey::"+encryptedPassword3);
                  
                  String decryptedPassword3 = decrypt(encryptedPassword3,passwordLength);
                  System.out.println("decryptedPassword1::1stKey::"+decryptedPassword3);
                  
                  String encryptedPassword4 =      encryptString(decryptedPassword3,passwordLength);
                  System.out.println("encryptedPassword4::2ndKey::"+encryptedPassword4);
                                          
            }
            catch(Exception e)
            {
                  System.out.println("Exception::"+e.getMessage());
            }
            
            
      }
      
      
      
        private static final String ENCRYPTION_KEY  = "1FASTDOG";
        private static final String ENCRYPTION_KEY2 = "2FASTDOG";


         public static final int NO_MATCH = 0;
         public static final int PLAIN_TEXT_MATCH = 1;
         public static final int ENCRYPTED_MATCH = 2;

         /**
          * Encrypts a string, and returns a hex string.
          * @param fsPlainText  String to be encrypted
          * @return  Encrypted hex string
          */
         public static String encryptString(String fsPlainText, int fiTextMaxLength)
         {
            
               System.out.println(ENCRYPTION_KEY);
                 byte lbEncryptedString[] = new byte[fiTextMaxLength];
            byte lbFromString[];
            byte lbPlainText[] = new byte[fiTextMaxLength];
            Des3Cipher loCipher = new Des3Cipher(ENCRYPTION_KEY);
            int liByteIndex;
            int liHexFragLength;
            int liPlainTextLength;
            String lsHexFragment;
            StringBuffer lsbHexString;

            lbFromString = fsPlainText.getBytes();
            liPlainTextLength = fsPlainText.length();

            // Copy bytes into encryption array
            for(liByteIndex = 0;
               liByteIndex < liPlainTextLength;
               liByteIndex++)
            {
               lbPlainText[liByteIndex] = lbFromString[liByteIndex];
            }

            // Append trailing spaces as necessary
            for(liByteIndex = liPlainTextLength;
               liByteIndex < fiTextMaxLength;
               liByteIndex++)
            {
               lbPlainText[liByteIndex] = (byte)' ';
            }

            // Encrypt the 8 bytes blocks
            for(int liBlockStart = 0; liBlockStart < fiTextMaxLength;
               liBlockStart += 8)
            {
               loCipher.encrypt(lbPlainText, liBlockStart,
                  lbEncryptedString, liBlockStart);
            }

            // Convert the encrypted bytes to a hex string
            lsbHexString = new StringBuffer(fiTextMaxLength * 2);
            for(liByteIndex = 0; liByteIndex < fiTextMaxLength; liByteIndex++)
            {
               lsHexFragment = Integer.toHexString(lbEncryptedString[liByteIndex]);
               liHexFragLength = lsHexFragment.length();

               // If fragment is a single digit, add leading 0
               if(liHexFragLength == 1)
               {
                  lsHexFragment = "0" + lsHexFragment;
                  liHexFragLength = 2;
               }

               // Accumulate into string, removing leading 'f's from
               // negative numbers.
               lsbHexString.append(lsHexFragment.substring(liHexFragLength - 2));
            }
            return lsbHexString.toString();
         }
        
         public static String encryptStringWithSecondKey(String fsPlainText, int fiTextMaxLength)
         {
            byte lbEncryptedString[] = new byte[fiTextMaxLength];
            byte lbFromString[];
            byte lbPlainText[] = new byte[fiTextMaxLength];
            Des3Cipher loCipher = new Des3Cipher(ENCRYPTION_KEY2);
            int liByteIndex;
            int liHexFragLength;
            int liPlainTextLength;
            String lsHexFragment;
            StringBuffer lsbHexString;

            lbFromString = fsPlainText.getBytes();
            liPlainTextLength = fsPlainText.length();

            // Copy bytes into encryption array
            for(liByteIndex = 0;
               liByteIndex < liPlainTextLength;
               liByteIndex++)
            {
               lbPlainText[liByteIndex] = lbFromString[liByteIndex];
            }

            // Append trailing spaces as necessary
            for(liByteIndex = liPlainTextLength;
               liByteIndex < fiTextMaxLength;
               liByteIndex++)
            {
               lbPlainText[liByteIndex] = (byte)' ';
            }

            // Encrypt the 8 bytes blocks
            for(int liBlockStart = 0; liBlockStart < fiTextMaxLength;
               liBlockStart += 8)
            {
               loCipher.encrypt(lbPlainText, liBlockStart,
                  lbEncryptedString, liBlockStart);
            }

            // Convert the encrypted bytes to a hex string
            lsbHexString = new StringBuffer(fiTextMaxLength * 2);
            for(liByteIndex = 0; liByteIndex < fiTextMaxLength; liByteIndex++)
            {
               lsHexFragment = Integer.toHexString(lbEncryptedString[liByteIndex]);
               liHexFragLength = lsHexFragment.length();

               // If fragment is a single digit, add leading 0
               if(liHexFragLength == 1)
               {
                  lsHexFragment = "0" + lsHexFragment;
                  liHexFragLength = 2;
               }

               // Accumulate into string, removing leading 'f's from
               // negative numbers.
               lsbHexString.append(lsHexFragment.substring(liHexFragLength - 2));
            }
                 return lsbHexString.toString();
         }
        
        
        
        
         public static String decryptWithSecondKey(
              String fsDatabasePassword,
              int fiTextMaxLength)
           {
              byte lbDecryptedPassword[] = new byte[fiTextMaxLength];
              byte lbEncryptedPassword[] = new byte[fiTextMaxLength];
              Des3Cipher loCipher = new Des3Cipher(ENCRYPTION_KEY2);
              int liByteIndex;

              // Convert the password from a hex string to a byte array
              for(liByteIndex = 0; liByteIndex < fiTextMaxLength;
                 liByteIndex++)
              {
                 lbEncryptedPassword[liByteIndex] = (byte)Integer.parseInt(
                    fsDatabasePassword.substring(liByteIndex * 2,
                       liByteIndex * 2 + 2), 16/* the base of the number */);
              }
              for(int liBlockStart = 0; liBlockStart < fiTextMaxLength;
                 liBlockStart += 8)
              {
                 loCipher.decrypt(lbEncryptedPassword, liBlockStart,
                    lbDecryptedPassword, liBlockStart);
              }
              return (new String(lbDecryptedPassword));
           }
        
        
         public static String decrypt(
            String fsDatabasePassword,
            int fiTextMaxLength)
         {
            byte lbDecryptedPassword[] = new byte[fiTextMaxLength];
            byte lbEncryptedPassword[] = new byte[fiTextMaxLength];
            Des3Cipher loCipher = new Des3Cipher(ENCRYPTION_KEY);
            int liByteIndex;

            // Convert the password from a hex string to a byte array
            for(liByteIndex = 0; liByteIndex < fiTextMaxLength;
               liByteIndex++)
            {
               lbEncryptedPassword[liByteIndex] = (byte)Integer.parseInt(
                  fsDatabasePassword.substring(liByteIndex * 2,
                     liByteIndex * 2 + 2), 16/* the base of the number */);
            }
            for(int liBlockStart = 0; liBlockStart < fiTextMaxLength;
               liBlockStart += 8)
            {
               loCipher.decrypt(lbEncryptedPassword, liBlockStart,
                  lbDecryptedPassword, liBlockStart);
            }
            return (new String(lbDecryptedPassword)).trim();
         }

         /**
          * Compares a password from the database to a password entered by a user.
          * @param fsDatabasePassword  Either an encrypted password in the form of
          * a hex string, or a plain text password (this allows a developer to
          * create a user with a plain text password; the return value from the
          * method indicates to the caller that the database password needs to be
          * encrypted)
          * @param fsEnteredPassword  Plain text password entered by the user.
          * @param fiTextMaxLength  The maximum length of the plain text password.
          * @return NO_MATCH if the passwords don't match, PLAIN_TEXT_MATCH if the
          * passwords matched when fsDatabasePassword was treated as plain text,
          * ENCRYPTED_MATCH if the passwords matched when fsDatabasePassword was
          * treated as an encrypted hex string.
          */
         public static int comparePasswords(
            String fsDatabasePassword,
            String fsEnteredPassword,
            int fiTextMaxLength)
         {
            boolean lboolPasswordMatch = false;
            boolean lboolPlainText = false;
            String lsDecryptedPassword;

            try
            {
               //System.err.println("Inside BOSEncryption, Password Length = " + fiTextMaxLength);
               lsDecryptedPassword = decrypt(fsDatabasePassword, fiTextMaxLength);
               // If the decrypted password matches the password the
               // user entered
               if(fsEnteredPassword.equals(lsDecryptedPassword))
               {
                  return(ENCRYPTED_MATCH);
               }
               else
               {
                  // Assume it's plain text
                  lboolPlainText = true;
               }
            }
            catch(NumberFormatException e)
            {
               // Assume the password is plain text
               lboolPlainText = true;
            }
            catch(StringIndexOutOfBoundsException e)
            {
               // Assume the password is plain text
               lboolPlainText = true;
            }

            if(lboolPlainText)
            {
               // If the entered password matches the database password
               if(fsDatabasePassword.equalsIgnoreCase(fsEnteredPassword))
               {
                  return(PLAIN_TEXT_MATCH);
               }
            }
            return NO_MATCH;
         }
      
      
}
0
 
nikhilbansalAuthor Commented:
Hi CEHJ,

I've gone through the link tht u have provided.You've asked me to use DES3 instead of DES.I think instead of DES3 it should be DESede to be specified as a algorithm name(specifying DES3 is invalid).

Correct me if I am wrong.

Regards

Nikhil
0
 
CEHJCommented:
>>I think instead of DES3 it should be DESede to be specified as a algorithm name(specifying DES3 is invalid).

Ah yes, i think you're right. Personally i wouldn't use any code that's not come through Sun
0
 
nikhilbansalAuthor Commented:
Hi CEHJ,

I've gone through the javax.crypto API.

Is there a way where in I can specify my own key without using SecretKey class.

Regards

Nikhil

0
 
CEHJCommented:
This shows how to create a key with your own passphrase (password) if that's your requirement:

http://javaalmanac.com/egs/javax.crypto/PassKey.html
0
 
objectsCommented:
What exactly is your requirement?
0
 
nikhilbansalAuthor Commented:
I need to encrypt and decrypt a password using DES3 algorithm.Earlier I tried using Des3Cipher.java defined by Acme software.However it doesn't seem to give 100% correct results. When I give certain passwords like

nikhilbansal
devendra_rane

then the decryption is giving some junk characters.There seems to be some memory leak.

So I felt like using javax.crypto API specified by sun.

The example which CEHJ gave at  http://javaalmanac.com/egs/javax.crypto/DesString.html
is working fine.But here there are no user defined keys.Pair of SecretKeys are being generated for the algorithm DES3.

My application requires that the keys should be user defined.

Let me see the link given by CEHJ  

http://javaalmanac.com/egs/javax.crypto/PassKey.html

Hope it should work.

Objects

if you can figure out the problem of memory leak in my code  posted earlier then Encryption.java, I shall be grateful to you.

Regards

Nikhil
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.