Java Encryption using Triple DES Algo..

Hi guys..
Coud anybody help me with this..
I want something like this..

I have a URL :
NAME= ABC & ACCOUNT NO = 123

I want to pass this to my Java code..
encrypt it using a Triple DES function..

and get decrypt it .. using the same function and get back the same value..

Please can somebody send me some sample code and tips how to implement this.. This is the first time I am trying Encryption .. So I have no idea about this if anybody can please help me with tthis...

Regards
rnarang2000Asked:
Who is Participating?
 
mbormannConnect With a Mentor Commented:
have sent the file to both Jod and narrav.
Bye

>>>>>Trying to do lots of research on a tricky problem today and it is proving to be a bit of a nightmare...

am in same boat man ,a particularly a silly bug which has willy nilly crept up.
0
 
JodCommented:
Here is an implementation of this algorithm:

// Des3Cipher - the triple-DES encryption method
//
// Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>.  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
// 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.*;

/// The triple-DES encryption method.
// <P>
// This is a fairly standard way of increasing the security of DES.
// You run each block through DES three times, first encrypting with
// key A, then decrypting with key B, then encrypting again with key A
// again.
// <P>
// <A HREF="/resources/classes/Acme/Crypto/Des3Cipher.java">Fetch the software.</A><BR>
// <A HREF="/resources/classes/Acme.tar.Z">Fetch the entire Acme package.</A>
// <P>
// @see DesCipher
// @see EncryptedOutputStream
// @see EncryptedInputStream

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

    }

you will need to download the support libraries from

http://www.acme.com/java/

to get it working.

I can post further info if you need it...
0
Cloud Class® Course: C++ 11 Fundamentals

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

 
JodCommented:
The acme link appears to be currently broken, but you can find the underlying algorithm class here:

  http://www.tiap.org/chartmakers/Acme/Crypto/DesCipher.java

This gives you the simple(?) DES algorithm.
0
 
mbormannCommented:
pls note ::::: name of file is Acme.tar.gz

Jod, if u have time ,why not write this fully end to end and will post points for u, thru my friend's account?

thx
0
 
rnarang2000Author Commented:
Thanx for reply.. I got DesCipher.. But could you please tell me..
Do I need some package to make it working? I tried using JCE2.0.. But I have no idea how to make it work.. Its a zipped file.. I unzipped it.. and it gave me some package javax.. Your code .. How to implement and make it work for my problem if you caN furthur help me with this...

Regards

0
 
rnarang2000Author Commented:
Hi again.. there is nothing like DesCipher.class in this ....
0
 
mbormannCommented:
if u want to i have placed the file at
http://www.geocities.com/mbormann0/Code/Acme.zip

just rename it to the name i said earlier.

Bye
0
 
JodCommented:
Finding the time...I will see if I can find some time.

Basically, descipher encrypts blocks of data. DES3cipher sits on top of DEScipher to to do Triple DES algorithm by passing data in three times.

Then the ACME utility classes provide encrypted input and output streams to make it all easier to use.

The package all this sits in is package Acme.Crypto which is what you have downloaded. The other parts plug into this to use the provided utility classes.


No time to put an example together today, but will try later...MB has the files you need to download.
0
 
rnarang2000Author Commented:
Do I need to put anything in my classpath??? and after that Shud I just compile DesCipher.java?? and After that what???
0
 
rnarang2000Author Commented:
Cannot I open this Acme.zip file??
0
 
rnarang2000Author Commented:
Adjusted points to 75
0
 
rnarang2000Author Commented:
Okay I have got complied DesCipher.. Now How to use it if you caN help me with this plsss
0
 
JodCommented:
Ideally, you need to put all the files in the acme package into a sub directory called

acme/crypto

and this must be in your class path or specified in order for Java to link to and find it. You can then see all the files in the package and how they work.

Then you add DEScipher to this package, saving, compiling and running it from the same DIR if you wish. It uses classes from acme so it needs to know where they are.
0
 
mbormannCommented:
>>>>>Finding the time...I will see if I can find some time.

http://www.cyber-nation.com/victory/quotations/subjects/quotes_timeandtimemanagement.html

:-)

send me ur EMail ID quickly ,i go hoem in 10 mins,so i can mail u the file
0
 
rnarang2000Author Commented:
Thanx .. I got it.. I got complied DESCipher.. Now how to use this to encrypt my URL thing.. If you can help me with sample code pls
0
 
JodCommented:
Example of this given by mb before, is:

If u have a String of unencrypted data.

String marshiaStr = new String();
marshiaStr+= "This is unencrypted";

use it like
byte [] encyptedData = new byte[marshiaStr.length()];

encrypt(marshiaStr.getBytes() , 0 , encyptedData ,0);

0
 
rnarang2000Author Commented:
Is this for me MBormann?? are you asking my emailid.. But anyway.. it is rnarang2000@hotmail.com
0
 
mbormannCommented:
see the encrypt () in the original question.likewise do it for decrypt()
0
 
rnarang2000Author Commented:
And How to get this encrypted data Jod.. since encrypt method doesn't return anything.. I want to see what do it get after encryption and after decryption...

0
 
JodCommented:
It puts the encypted data in the second of the two byte arrays, overwritng the data in there already, in the above case the encrypted cersion of mashiStr appears in encryptedData.

After that, the next stage is to build a stream around it to [rocess more than eight bytes at a time. This is in the acme package already
0
 
mbormannCommented:
i sent u the file by mail,r u a begginer? if u have a problem reading docs then wait a day and if possible i will also try to do it .

Jod has already said that he would try.
dont be angry ,it is a stage all of us pass thru
0
 
JodCommented:
Just need more time mb...time management is to put off the inevitable

Trying to do lots of research on a tricky problem today and it is proving to be a bit of a nightmare...

john.odonovan@bbc.co.uk
0
 
rnarang2000Author Commented:
I didn't got any file.. well.. seems some problem with this email accnt.. can u pls send me again at narrav@hotmail.com..

Regards
0
 
rnarang2000Author Commented:
I treid to compile code..
my code looks like..

import Acme.Crypto.*;

public class EnTest
{
public static void main (String args[]){

String marshiaStr = new String();
marshiaStr+= "This is unencrypted";
byte [] encyptedData = new byte[marshiaStr.length()];

DesCipher.encrypt(marshiaStr.getBytes() , 0 , encyptedData ,0);

}
}


when I compile it.. I get error like:
EnTest.java:12: Can't make static reference to method void encrypt(byte[], int,
byte[], int) in class Acme.Crypto.DesCipher.
DesCipher.encrypt(marshiaStr.getBytes() , 0 , encyptedData ,0);



If you can pls help me with this ....

I really appreciate your help..

Regards

0
 
mbormannCommented:
Oops ,
sorry i did NOT mean to propose.

anyway FYI we have implemented a triple DES but i can't send it to u.will try to code using the Acme code ,though i can say this for sure that our present code is faster thab that.

again sorry,will try when i have time and if Jod does not answer first.
bye ,I also want to do this for encypting EMail for personal use.
0
 
rnarang2000Author Commented:
Okay One last question.
It just encrypts 8 bits of data.. I want to extend it to may be more..

example..
I encrypted...

"Ravi Narang"

and decrypted it back..

It just displays..

Ravi Nar

Just this last question and lemme close the question then....

Regards
0
 
mbormannCommented:
ravi,
here's some unfinsged code ,go alonfa that track,
luck will post later when i have time

import Acme.Crypto.*;

public class EncTest
{
static byte zeroes[] = {0,0,0,0,0,0,0,0};
static byte in[] = new byte[8];
static byte out[] = new byte[8];
      
public static void main(String[] args)
{
      String unencryptedDataString = "This is unencrypted data String";
            
    byte [] UNENCRYPTED_DATA = unencryptedDataString.getBytes();
            
      byte [] encryptedData = new byte[unencryptedDataString.length()];
      byte [] decryptedData = new byte[unencryptedDataString.length()];

      Des3Cipher cipher= new Des3Cipher("0123456789abcdef");
      for(int i=0;i<UNENCRYPTED_DATA.length;i+=8 )
      {
            in=smartCopy(UNENCRYPTED_DATA,i,in,0,8);
            cipher.encrypt(in , 0 , encryptedData ,0);
            System.out.println(new String(encryptedData));
            //to ensure that in[] is cleared out
            System.arraycopy(zeroes,0,in,0,8);
      }

      System.out.println("\n\n\n");

      for(int j=0;j<encryptedData.length;j+=8 )
      {
            out=smartCopy(encryptedData,j,out,0,8);
            cipher.decrypt(out , 0 , decryptedData ,0);
            System.out.println(new String(decryptedData));
            //to ensure that out[] is cleared out
            System.arraycopy(zeroes,0,out,0,8);
      }
}
      
private static final byte[] smartCopy(byte [] src,int src_pos,byte [] dst,int dst_pos,int len)
{
      int len_of_arr=src.length;
      if((src_pos+len) > len_of_arr)
            System.arraycopy(src,src_pos,dst,0,len_of_arr - src_pos);
      else
            System.arraycopy(src,src_pos,dst,0,len);
      return dst;
}
}
0
 
mbormannCommented:
Final working code,
Ravi because of you i got to complete this,thanks
P.s:- can u increase points?
:-)

import Acme.Crypto.*;

/* This program is dedicated to Ashish Kulkarni,my brother and fellow programmer
Well bro ,we did this ,so take over and do the next step by urself.
   
For this to work ,download the freely available Acme Crypto package at
http://www.acme.com/java/software/
if u want it please mail me at amitkulkarni@mailandnews.com,
and i will try to respond under 15 days.
*/

public class EncryptionTest
{
 private static final int ENC_SIZE = 8;
 private static byte zeroes[] = {0,0,0,0,0,0,0,0};
 private static byte in[] = new byte[ENC_SIZE];
 private static byte out[] = new byte[ENC_SIZE];
 private static byte tempArr[] = new byte[ENC_SIZE];
      
 static
 {
       zeroes = new byte[ENC_SIZE];
       for(int i=zeroes.length;--i >= 0;)
       {
             zeroes[i]=0;
       }
 }
      
 public static void main(String[] args) throws Exception
 {
       String unencryptedDataString = "This is unencrypted data String man,testing this out,savvy?";
     byte [] unencrypted_data = unencryptedDataString.getBytes();
       int unencryptLen = unencryptedDataString.length();

       //since 8 is the size of encrypt/decrypt methods
       //of Des3Cipher,we need to pad the original
       //unencrypted byte array

       unencryptLen += (ENC_SIZE-(unencryptLen%ENC_SIZE));
       byte [] encryptedData = new byte[unencryptLen];
       byte [] decryptedData = new byte[unencryptLen];

       //instantiate Des3Cipher with some fixed key
       Des3Cipher cipher= new Des3Cipher("0123456789abcdef");
       for(int eIndx=0;eIndx<unencrypted_data.length;eIndx+=ENC_SIZE )
       {
             in=smartCopy(unencrypted_data,eIndx,in,0,ENC_SIZE);
             cipher.encrypt(in , 0 , tempArr ,0);
             //flush
             smartCopy(tempArr,0,encryptedData,eIndx,ENC_SIZE);
             System.arraycopy(zeroes,0,in,0,ENC_SIZE);
             System.arraycopy(zeroes,0,tempArr,0,ENC_SIZE);
       }

       //This proves that at one side u encrypt with a special key
       //at other u use the same one to decrypt,
       //Uh-Oh ,u gotta keep da key in a Seeeecure place man.
       cipher=null;
       cipher= new Des3Cipher("0123456789abcdef");
            
       for(int dIndx=encryptedData.length;dIndx>=0;dIndx-=ENC_SIZE )
       {
             out=smartCopy(encryptedData,dIndx,out,0,ENC_SIZE);
             cipher.decrypt(out , 0 ,tempArr  ,0);
             smartCopy(tempArr,0,decryptedData,dIndx,ENC_SIZE);
             //flush
             System.arraycopy(zeroes,0,out,0,ENC_SIZE);
             System.arraycopy(zeroes,0,tempArr,0,ENC_SIZE);
       }
            
       //to do a trim is very IMPORTANT,since we havta remove padded spaces.
       System.out.println("\nFINALLY decryptedData='"+new String(decryptedData).trim()+"'");
 }
      
 private static final byte[] smartCopy(byte [] src,int srcPos,byte [] dst,int dstPos,int len)
 {
       int lenSrcArr=src.length;
       int lenDstArr=dst.length ;
       //encryption
       if(lenSrcArr > lenDstArr)
       {
             if((srcPos+len) > lenSrcArr)
                   System.arraycopy(src,srcPos,dst,0,lenSrcArr - srcPos);
             else
                   System.arraycopy(src,srcPos,dst,0,len);
       }
       else
       //decryption
       {
             if((dstPos+len) > lenDstArr)
                   System.arraycopy(src,0,dst,dstPos,lenDstArr - dstPos);
             else
                   System.arraycopy(src,0,dst,dstPos,len);
       }
       return dst;
 }
}
0
 
rnarang2000Author Commented:
Thanks alot MB..Because of me.. you were able to complete the code..i deserve some credit for this though..:)

Ok I will increase points to 100.. before I close this.. after my last question.. but atleast help me understand this code...

atleast write little details about this code for these 10 points..
what is this smartCopy function? whats the significance of zeroes array?
wat actually is happening here in this code??

Just a last question pls.. i know dats too irritating.. but for 10 points hope u can bear this last irritation..
Regards
0
 
mbormannCommented:
Our Mail server was down so got this a bit late.
Oki man ,but can u gimme a 'A' grade ,thanks.

Actually this code can be optimized further .....

what is this smartCopy function? whats the significance of zeroes array?

well for smartCopy() as u can see it's just a System.arrayCopy() ,when u have a case when the unencrypted string is say 49 bytes which is 1 more than the neasrest multiple of 8 which is 48,then as the encrypt() does encryption for 8 bytes you HAVE to pad 7 zeroes after the 1 true byte remaining.

same stuff goes for decrypting ,only difference is that if u don't do it ,either a ArrayIndexOutOfBounds exception is thrown or a garbage is there at the end.

zeroed arrays:-
and u have to ensure that the arrays are flushed out and don't contain any previously remembered 'value', this also pads up the remaining elements of array with '0' automatically when the last encrypt()/decrypt() is being exceuted.

look at the smartCopy() in detail.also look at statr when we keep the original length of encrypted /decrypted array as a multiple of 8.

in real life u can't allocate 3 arrays like this.coz of OutOfMemoryEror which java is notorious for,u will no of it in good time.

something else has to be done.ccan u think of it?if u can then that's a start ,train urself to think.and the battel is half won.

click on my profile too.

Regards
Amit
0
 
JodCommented:
Amit:

did you have a look at using the Encryptedinputstream and encryptedoutputstream in Acme tools.

They may be able to optimise access to the encyption routines.

I'm afraid I'm still too busy to sit down and battle with this at the moment....
0
 
rnarang2000Author Commented:
Thanx alot Amit.. I really appreciate your help.. I am increasing the points here.. But I am not closing the question.. Cuz of problems with This code .. May be I am doing something rong.. But atleast I am really bugged with this Encryption Stuff..

i try to encode BASE64.. the encrypted data which I get from your code, decode it back, decrypt it.. and it fails..

Just a question here.. Does JCE also encrypts the data 8 bytes at one time.. I know its from TRIPLE DES algorithm encrypting the data 8 bytes at a time.. But does JCE takes care of that.. or we have to do the same thing with JCE also.. Let me send you the exact code I am having problem with..

Regards
0
 
rnarang2000Author Commented:
This is what I am trying to do.. which is messing up everything..


import java.net.URLEncoder;
import sun.misc.*;
public class EncryptionTestbk
{
 private static final int ENC_SIZE = 8;
 private static byte zeroes[] = {0,0,0,0,0,0,0,0};
 private static byte in[] = new byte[ENC_SIZE];
 private static byte out[] = new byte[ENC_SIZE];
 private static byte tempArr[] = new byte[ENC_SIZE];

 //static
 //{
  //zeroes = new byte[ENC_SIZE];
  //for(int i=zeroes.length;--i >= 0;)
  //{
  //zeroes[i]=0;
  //}
 //}

 public static void main(String[] args) throws Exception
 {
        String actualURL = "screen_name=TestScreen&acct_no=12345&sub_accnt_no=98765";
      String unencryptedDataString = URLEncoder.encode(actualURL);
      //System.out.println(unencryptedDataString);
        byte [] unencrypted_data = unencryptedDataString.getBytes();
        int unencryptLen = unencryptedDataString.length();

        unencryptLen += (ENC_SIZE-(unencryptLen%ENC_SIZE));
        byte [] encryptedData = new byte[unencryptLen];
        byte [] decryptedData = new byte[unencryptLen];

        //instantiate Des3Cipher with some fixed key
        Des3Cipher cipher= new Des3Cipher("raviN");
        for(int eIndx=0;eIndx<unencrypted_data.length;eIndx+=ENC_SIZE )
              {
              in=smartCopy(unencrypted_data,eIndx,in,0,ENC_SIZE);
              cipher.encrypt(in , 0 , tempArr ,0);
              
              smartCopy(tempArr,0,encryptedData,eIndx,ENC_SIZE);
            System.arraycopy(zeroes,0,in,0,ENC_SIZE);
              System.arraycopy(zeroes,0,tempArr,0,ENC_SIZE);
              }
 
              System.out.println("\nFINALLY encryptedData= " + new String(encryptedData).trim());
            
            BASE64Encoder encoder = new BASE64Encoder(); // from sun.misc
            String base64 = encoder.encode(encryptedData);
            System.out.println("BASE64Encoding   " + base64);
            
            //URLEncoding
            //String data = URLEncoder.encode(base64);
            //System.out.println("URLEncoding : " + data);
            
            //URLDecoding
            //String dataD = NetTools.queryStringDecodeInternal(data);
            //System.out.println("URLDecoding : " + dataD);
            
            //Base64Decoding
            BASE64Decoder decoder = new BASE64Decoder(); // from sun.misc
            encryptedData = new byte[unencryptLen];
            
            encryptedData = decoder.decodeBuffer(base64);
            System.out.println("BASE64Decoding : " + new String(encryptedData).trim());
            
             cipher=null;
              cipher= new Des3Cipher("raviN");

  for(int dIndx=encryptedData.length;dIndx>=0;dIndx-=ENC_SIZE )
        {
        out=smartCopy(encryptedData,dIndx,out,0,ENC_SIZE);
        cipher.decrypt(out , 0 ,tempArr  ,0);
        smartCopy(tempArr,0,decryptedData,dIndx,ENC_SIZE);
        System.arraycopy(zeroes,0,out,0,ENC_SIZE);
        System.arraycopy(zeroes,0,tempArr,0,ENC_SIZE);
        }
      
       System.out.println("\nFINALLY decryptedData= " + decryptedData);
 }

 private static final byte[] smartCopy(byte [] src,int srcPos,byte [] dst,int dstPos,int len)
       {
              int lenSrcArr=src.length;
              int lenDstArr=dst.length ;
              //encryption
              if(lenSrcArr > lenDstArr)
                    {
                    if((srcPos+len) > lenSrcArr)
                    System.arraycopy(src,srcPos,dst,0,lenSrcArr - srcPos);
                    else
                    System.arraycopy(src,srcPos,dst,0,len);
                    }
              else
              //decryption
                    {
                    if((dstPos+len) > lenDstArr)
                    System.arraycopy(src,0,dst,dstPos,lenDstArr - dstPos);
                    else
                    System.arraycopy(src,0,dst,dstPos,len);
                    }
                    return dst;
       }
}
0
 
mbormannCommented:
Jod,
if this works for him we can do the rest when we have time.

i too am in a rush,but not so tight as u.

Ravi,
a few questions for u
(1)why u want to do Base64 encoding?
(2)when u send the '&' param ,i assume that u r using a applet /servlet communication,right? so the char is used for encoding ,use some other char like ',' then this program below works fine.

Use the sendPostMessage() of some file in www.servlets.com,will tell u tommorrow,gotta rush today.

here it is

import Acme.Crypto.Des3Cipher;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;

public class EncryptionTest
{
      private static final int ENC_SIZE = 8;
      private static byte zeroes[] = null;
      private static byte in[] = new byte[ENC_SIZE];
      private static byte out[] = new byte[ENC_SIZE];
      private static byte tempArr[] = new byte[ENC_SIZE];

      static
      {
            zeroes = new byte[ENC_SIZE];
            for(int i=zeroes.length;--i >= 0;)
            {
                  zeroes[i]=0;
            }
      }

      public static void main(String[] args) throws Exception
      {
            //String unencryptedDataString = "screen_name=TestScreen&acct_no=12345&sub_accnt_no=98765";
            String unencryptedDataString = "screenname=TestScreen,acct_no=12345,sub_accnt_no=98765";
            byte [] unencrypted_data = unencryptedDataString.getBytes();
            int unencryptLen = unencryptedDataString.length();

            System.out.println("unencryptLen="+unencryptLen);
            
            //since 8 is the size of encrypt/decrypt methods
            //of Des3Cipher,we need to pad the original
            //unencrypted byte array

            unencryptLen += (ENC_SIZE-(unencryptLen%ENC_SIZE));
            byte [] encryptedData = new byte[unencryptLen];
            
            //instantiate Des3Cipher with some fixed key
            Des3Cipher cipher= new Des3Cipher("0123456789abcdef");
            for(int eIndx=0;eIndx<unencrypted_data.length;eIndx+=ENC_SIZE )
            {
                  in=smartCopy(unencrypted_data,eIndx,in,0,ENC_SIZE);
                  cipher.encrypt(in , 0 , tempArr ,0);
                  //flush
                  smartCopy(tempArr,0,encryptedData,eIndx,ENC_SIZE);
                  //System.out.println("\ttempArr='"+new String(tempArr)+"'");
                  System.arraycopy(zeroes,0,in,0,ENC_SIZE);
                  System.arraycopy(zeroes,0,tempArr,0,ENC_SIZE);
            }

            //System.out.println("'"+new String(encryptedData)+"'");
            //URLEncoding
            String dataToSocket = URLEncoder.encode(new String(encryptedData));
            unencrypted_data=null;
            encryptedData=null;

            //note here u will transfer it thru Socket and the next
            //steps r to be taken at the other side
            
            //URLDecoding
            String dataFromSocket = decode(dataToSocket);
            //System.out.println("'"+dataFromSocket+"'");

            encryptedData = dataFromSocket.getBytes();
            byte [] decryptedData = new byte[encryptedData.length];
            
            //This proves that at one side u encrypt with a special key
            //at other u use the same one to decrypt,
            //Uh-Oh ,u gotta keep da key in a Seeeecure place man.
            cipher=null;
            cipher= new Des3Cipher("0123456789abcdef");

            //for(int dIndx=encryptedData.length;dIndx>=0;dIndx-=ENC_SIZE )
            System.arraycopy(zeroes,0,tempArr,0,ENC_SIZE);
            System.arraycopy(zeroes,0,out,0,ENC_SIZE);
            for(int dIndx=0;dIndx<encryptedData.length;dIndx+=ENC_SIZE )
            {
                  out=smartCopy(encryptedData,dIndx,out,0,ENC_SIZE);
                  System.out.println("\tout='"+new String(out)+"'");
                  cipher.decrypt(out , 0 ,tempArr  ,0);
                  smartCopy(tempArr,0,decryptedData,dIndx,ENC_SIZE);
                  System.out.println("tempArr='"+new String(tempArr)+"'");
                  //flush
                  System.arraycopy(zeroes,0,out,0,ENC_SIZE);
                  System.arraycopy(zeroes,0,tempArr,0,ENC_SIZE);
            }

            //to do a trim is very IMPORTANT,since we havta remove padded spaces.
            System.out.println("\nFINALLY decryptedData='"+new String(decryptedData).trim()+"'");
             
      }       

      private static final byte[] smartCopy(byte [] src,int srcPos,byte [] dst,int dstPos,int len)
      {
            int lenSrcArr=src.length;
            int lenDstArr=dst.length ;
            //encryption
            if(lenSrcArr > lenDstArr)
            {
                  if((srcPos+len) > lenSrcArr)
                        System.arraycopy(src,srcPos,dst,0,lenSrcArr - srcPos);
                  else
                        System.arraycopy(src,srcPos,dst,0,len);
            }
            else
            //decryption
            {
                  if((dstPos+len) > lenDstArr)
                        System.arraycopy(src,0,dst,dstPos,lenDstArr - dstPos);
                  else
                        System.arraycopy(src,0,dst,dstPos,len);
            }
            return dst;
      }
      
      /**
      * Translates String from x-www-form-urlEncoded format into text.
      * @param s String to be translated
      * @return the translated String.
      */
      public static String decode(String s)
      {
            ByteArrayOutputStream out = new ByteArrayOutputStream(s.length());
             
            for (int i = 0; i < s.length(); i++)
            {
                  int c = (int) s.charAt(i);
                  
                  if (c == '+')
                  {
                        out.write(' ');
                  }
                  else if (c == '%')
                  {
                        int c1 = Character.digit(s.charAt(++i), 16);
                        int c2 = Character.digit(s.charAt(++i), 16);
                        out.write((char) (c1 * 16 + c2));
                  }
                  else
                  {
                        out.write(c);
                  }
            }

            return out.toString();
      }
}
0
 
mbormannCommented:
didja get it to work?
0
 
rnarang2000Author Commented:
Thanks MB. Let me see it works or not.. Long Long weekend.. so I was out..

Regards
0
 
rnarang2000Author Commented:
Oh yea.. but surely I get it working with JCE.. Only problem being, I wanted with version JDK1.1.7 .. but JCE is supported by JDK1.2 .. dats the reason I am so much interested in your code..

Best Regards
0
 
rnarang2000Author Commented:
No man doesnot work.. try with

String urlencryption =
12screenname=TestScreen,acct_no=12345,sub_accnt_no=98765


if we run program.. it gives nice output like:

FINALLY decryptedData='12screenname=TestScreen,îU¶(&#8595;&#9794;¬ïf¿tåªuë%b_accnt_no=987655
Ѧ§-Ek¢'

with no change in code..

Regards
0
 
mbormannCommented:
sorry man,
will try later as i am under a tight schedule
0
 
mbormannCommented:
I too am stumped ,the whole idea then maybe wrong ,will have to try it with Streams as Jod said
0
 
mbormannCommented:
what is ur EXACT requirement ,for what r u doing this? expalin in detail
I think that if u remove the URLEncoder /URLDecoder  then it will work fine.

if using it for POSTing data to server thru browser then send it using a simple POST and I think it will work fine.

i think that the encrypted stuff is generating some stuff that is no good for URLEncoder like the '&' in previous example u posted many days ago.

what do u say?
0
 
mbormannCommented:
i got it thru Streams ,pls go ahead and fill out what u had to do with the URLEncoder etc...

import Acme.Crypto.*;
import java.io.*;
import java.net.*;

public class EncryptionTest
{
    public static void main(String[] args) throws Exception
    {
            ServerSocket sServ = new ServerSocket(13000);
            sServ.setSoTimeout(0);
            while(true)
            {
                  System.out.println("In accept()");
                  Des3Cipher cipher= new Des3Cipher("0123456789abcdef");
                  Socket sock = sServ.accept();
                  System.out.println("Got a Socket! Waiting for 5 secs for client data from socket");
                  try
                  {
                        Thread.sleep(2000);
                  }
                  catch(Exception e)
                  {}
                        
                  DataInputStream din = new DataInputStream(sock.getInputStream());
                  EncryptedInputStream enc = new EncryptedInputStream(cipher,din);
                  byte [] clearText = new byte[din.available()];
                  enc.read(clearText);
                  System.out.println("Clear Text from socket='"+new String(clearText)+"'");
                  enc.close();sock.close();
                  clearText=null;enc=null;sock=null;
            }
      }
}



import Acme.Crypto.*;
import java.io.*;
import java.net.*;

public class ConnectWithServer
{
      public static void main(String[] args) throws Exception
      {
            String toTest = args[0].trim();
            System.out.println("The entered string ='"+toTest+"'");

            Des3Cipher cipher= new Des3Cipher("0123456789abcdef");
            
            Socket s = new Socket("127.0.0.1",13000);
            DataOutputStream dout = new DataOutputStream(s.getOutputStream());
            EncryptedOutputStream enc = new EncryptedOutputStream(cipher,dout);
            enc.write(toTest.getBytes());
            enc.flush();
            enc.close();
            enc=null;
            
            try
            {
                  Thread.sleep(3000);
            }
            catch(Exception e)
            {}
            s.close();
            s=null;
            System.out.println("Closed socket ,chk at Server end");
      }
}
0
 
JodCommented:
That looks much better mb...very neat.
0
 
mbormannCommented:
ravi,do test it out throughly and let us no ur results
0
 
mbormannCommented:
no comment from u?What happened ?
0
 
adamretterCommented:
Ths smart copy function in your code has a problem in that: If you wanted to encode a string that was less that 8 charecters long you get an Array out of bounds error.

How can this function be modified to accept strings less that 8 chars long and to pad with zero's ?

Thanks Adam
adam@cosmic.org.uk
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.