Results 1 to 20 of 20
  1. #1
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Problem with TripleDES

    I'm trying to implement a 3DES routine to encrypt/decrypt strings. Here are the fields and constructor of my class:

    Java Code:
    private final String UNICODE_FORMAT = "UTF8";
    private final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    private byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    private SecretKey key;
    
    public Encryption()
    {
    	try
    	{
    		myEncryptionKey = "PutYourPaswordHere";
    		myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
    		arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
    		ks = new DESedeKeySpec(arrayBytes);  //** PROBLEM HERE **
    		skf = SecretKeyFactory.getInstance(myEncryptionScheme);
    		cipher = Cipher.getInstance(myEncryptionScheme);
    		key = skf.generateSecret(ks);
    	}
    	catch (Exception e)
    	{
    		// TODO: handle exception
    	}
    }
    The problem with this occurs on the line I have marked above where I attempt to create the ks (KeySpec object). The object is not being assigned, I end up with a null object. Does anyone have any ideas as to what the problem might be?
    Last edited by wmd; 08-12-2012 at 08:18 PM.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,561
    Rep Power
    25

    Default Re: Problem with TripleDES

    Is an exception thrown?

    The posted code can't be compiled and tested. It's missing the import statements, the class definition and a main() method.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Re: Problem with TripleDES

    I'm getting a Null Pointer Exception at a later point in my code, because the key hasn't been created (because the KeySpec has not been created).

    Here's the full class:

    Java Code:
    import java.security.spec.KeySpec;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import com.badlogic.gdx.utils.Base64Coder;
    
    public class Encryption
    {
    	private final String UNICODE_FORMAT = "UTF8";
    	private final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    	private KeySpec ks;
    	private SecretKeyFactory skf;
    	private Cipher cipher;
    	private byte[] arrayBytes;
    	private String myEncryptionKey;
    	private String myEncryptionScheme;
    	private SecretKey key;
    
    	public Encryption()
    	{
    		try
    		{
    			myEncryptionKey = "PutYourPaswordHere"; //Password
    			myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
    			arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
    			ks = new DESedeKeySpec(arrayBytes);
    			skf = SecretKeyFactory.getInstance(myEncryptionScheme);
    			cipher = Cipher.getInstance(myEncryptionScheme);
    			key = skf.generateSecret(ks);
    		}
    		catch (Exception e)
    		{
    			// TODO: handle exception
    		}
    	}
    
    	public String encrypt(String unencryptedString)
    	{
    		String encryptedString = null;
    		try
    		{
    			cipher.init(Cipher.ENCRYPT_MODE, key);
    			byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
    			byte[] encryptedText = cipher.doFinal(plainText);
    			//encryptedString = new String(Base64.encodeBase64(encryptedText));
    			encryptedString = new String(Base64Coder.encode(encryptedText));
    		}
    		catch (Exception e)
    		{
    			e.printStackTrace();
    		}
    		return encryptedString;
    	}
    
    	public String decrypt(String encryptedString)
    	{
    		String decryptedText = null;
    		try
    		{
    			cipher.init(Cipher.DECRYPT_MODE, key);
    			byte[] encryptedText = Base64Coder.decode(encryptedString);
    			byte[] plainText = cipher.doFinal(encryptedText);
    			decryptedText = new String(plainText);
    		}
    		catch (Exception e)
    		{
    			e.printStackTrace();
    		}
    		return decryptedText;
    	}
    }
    I'm using the libgdx Base64Coder, but you can use any base64 encoder such as sun.misc.BASE64Decoder / sun.misc.BASE64Ecoder or org.apache.commons.codec.binary.Base64.
    Last edited by wmd; 08-12-2012 at 09:21 PM.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,561
    Rep Power
    25

    Default Re: Problem with TripleDES

    Where is the main() method for testing?
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Re: Problem with TripleDES

    Just create a standard main and put this in it:

    Java Code:
    private Encryption encryption = new Encryption();
    String test = encryption.encrypt("test123");
    This will throw the exception caused as a result of the ks (KeySpec) object not being created in the Encryption class constructor.

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,561
    Rep Power
    25

    Default Re: Problem with TripleDES

    Ok, I'll wait until you get some testing code together.

    Also I can't compile the code as is because I don't have the third party package. Can you make a testing version that just uses Java SE classes?

    What about this comment:
    Java Code:
       // TODO: handle exception
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Re: Problem with TripleDES

    You can use any base64 encoder. I don't think Java comes with one.

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,561
    Rep Power
    25

    Default Re: Problem with TripleDES

    Did you see the end of my last post? Did you fix it?

    If the code as posted doesn't compile and execute, I'm not able to test it. I hope any OP that wants help will provide code that compiles and executes.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Re: Problem with TripleDES

    OK, we don't need all the code (or the Base64 coder) to show that the KeySpec is not being assigned. All you need is this:

    Java Code:
    import java.security.spec.KeySpec;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    
    public class Encryption
    {
    	private final String UNICODE_FORMAT = "UTF8";
    	private final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    	private KeySpec ks;
    	private SecretKeyFactory skf;
    	private Cipher cipher;
    	private byte[] arrayBytes;
    	private String myEncryptionKey;
    	private String myEncryptionScheme;
    	private SecretKey key;
    
    	public Encryption()
    	{
    		try
    		{
    			myEncryptionKey = "PutYourPaswordHere"; //Password
    			myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
    			arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
    			ks = new DESedeKeySpec(arrayBytes); //*** PROBLEM IS ON THIS LINE ***
    			skf = SecretKeyFactory.getInstance(myEncryptionScheme);
    			cipher = Cipher.getInstance(myEncryptionScheme);
    			key = skf.generateSecret(ks);
    		}
    		catch (Exception e)
    		{
    			// TODO: handle exception
    		}
    	}
    }
    Your main class should then attempt to create this object like this:

    Java Code:
    private Encryption encryption = new Encryption();
    Running this, you will see that the KeySpec is never assigned, it always remains null. There's nothing in the TODO part because I don't know why the KeySpec is not being created. The only exception reported is a Null Pointer Exception, as I mentioned previously, which doesn't really tell me anything that I couldn't already see when stepping through the code.
    Last edited by wmd; 08-13-2012 at 03:15 PM.

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,561
    Rep Power
    25

    Default Re: Problem with TripleDES

    You still have not fixed what the IDE is warning you about:
    Java Code:
       // TODO: handle exception
    I don't know why the KeySpec is not being created.
    What if there is an exception you are ignoring?
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    christopherx is offline Member
    Join Date
    Oct 2011
    Posts
    92
    Rep Power
    0

    Default Re: Problem with TripleDES

    If that line isn't the problem, perhaps the parameters involved at the issue? The way I usually work is I make one assumption (i.e: The object is not being assigned because of that particular line) then I work from there. Obviously that problem isn't in the line, so we should next assume the parameter isn't right. Does the byte array that you pass to the KeySpec constructor have a value? I suspect a null byte array will create a null object. Just a thought! :)

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: Problem with TripleDES

    Please, just stick a e.printStackTrace() in that catch block, as Norm is implying.
    Do not eat exceptions otherwise how will you ever know when something has gone wrong?

    A NullPointerException in this situation is almost invariably down to the fact you are ignoring an exception.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Re: Problem with TripleDES

    After a bit more research, I decided to ditch 3DES in favour of AES. I now have an AES class implemented but I have a question - should I be creating my own key (e.g. from a password/passphrase) or is it OK to use a KeyGenerator?

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: Problem with TripleDES

    Since you are clearly going to persist in ignoring the advice from both Norm and I then I suppose it is only fair that I simply ignore you...

    One last go.
    Stick something in that catch block!
    Please!
    Last edited by Tolls; 08-15-2012 at 09:30 AM.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  15. #15
    christopherx is offline Member
    Join Date
    Oct 2011
    Posts
    92
    Rep Power
    0

    Default Re: Problem with TripleDES

    He's abandoned the code so I guess fixing his try catch block is pointless :P.

    Generating your own key is okay, but you need to ensure te algorithm you're using is cryptographically secure.
    The key generator class should have a good algorithm for doing this, so you can save yourself some effort and just use that class. If you want to understand it though, I suggest using your own implementation.

    In terms of your try catch block, NEVER just ignore exceptions. That is one of the big mistakes in programming!!

  16. #16
    ics1010 is offline Member
    Join Date
    Aug 2012
    Posts
    10
    Rep Power
    0

    Default Re: Problem with TripleDES

    You could have looked at the docs for the call and seen that the only reason it fails is if the key is too short. You need to supply keys of the proper length whichever method you use. Best method imo is sha1 a salt to some digest of whatever size you need. You should def take a look at Using AES with Java Technology though.

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: Problem with TripleDES

    Quote Originally Posted by christopherx View Post
    He's abandoned the code so I guess fixing his try catch block is pointless :P.
    In terms of your try catch block, NEVER just ignore exceptions. That is one of the big mistakes in programming!!
    Exactly. They may be abandoning this attempt, but that's almost entirely down to ignoring exceptions. And they are probably going to continue to do that and continue to hit NPEs caused by exceptions earlier in the code that are ignored.

    Quote Originally Posted by ics1010 View Post
    You could have looked at the docs for the call and seen that the only reason it fails is if the key is too short. You need to supply keys of the proper length whichever method you use. Best method imo is sha1 a salt to some digest of whatever size you need. You should def take a look at Using AES with Java Technology though.
    And that is an error that would have been shown had they simply added printStackTrace() in the bloody catch block! Doesn't matter what tech they decide on using if they can't do the basics...
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  18. #18
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Re: Problem with TripleDES

    Quote Originally Posted by Tolls View Post
    Since you are clearly going to persist in ignoring the advice from both Norm and I then I suppose it is only fair that I simply ignore you...

    One last go.
    Stick something in that catch block!
    Please!
    Why so hostile? I quite clearly stated in my previous post that I had ditched the 3DES code and was now using an AES routine. I wasn't ignoring anyone.

    Quote Originally Posted by christopherx View Post
    He's abandoned the code so I guess fixing his try catch block is pointless :P.

    Generating your own key is okay, but you need to ensure te algorithm you're using is cryptographically secure.
    The key generator class should have a good algorithm for doing this, so you can save yourself some effort and just use that class. If you want to understand it though, I suggest using your own implementation.

    In terms of your try catch block, NEVER just ignore exceptions. That is one of the big mistakes in programming!!
    Thanks for the help, and the tip about exceptions is duly noted. In the end I decided to make my own key using a SecretKeySpec. It's only being used to encrypt local high scores in a small game I'm working on so I don't think I need to go overboard.

  19. #19
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Re: Problem with TripleDES

    Here's my code for you to scrutinise in case there are any glaring errors:

    Java Code:
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.spec.SecretKeySpec;
    import javax.xml.bind.DatatypeConverter;
    
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    
    public class AESEncryptor
    {	
    	private static final String symKeyHex = "DD01020304050607080F0E020C0D0E04";
    	private static String strCipherText = new String();
    	private static String strDecryptedText = new String();
    	
    	//private KeyGenerator keyGen;
    	private static SecretKey secretKey;
    	private static Cipher aesCipher;
    	
    	private static byte[] byteDataToEncrypt;
    	private static byte[] byteDecryptedText;
    	private static byte[] byteCipherText;
    	
    	private byte[] symKeyData;
    	
    	public AESEncryptor()
    	{
    		try
    		{
    			/**
    			 * Step 1. Generate an AES key using KeyGenerator Initialize the keysize to 128
    			 */
    			//keyGen = KeyGenerator.getInstance("AES");
    			//keyGen.init(128);
    			//secretKey = keyGen.generateKey();
    			
    			/**
    			 * Alternative Step 1. Create SecretKey from hex bytes String
    			 */
    			symKeyData = DatatypeConverter.parseHexBinary(symKeyHex);			
    			secretKey = new SecretKeySpec(symKeyData, "AES");
    
    			/**
    			* Step2. Create a Cipher by specifying the following parameters 
    			* 		 a. Algorithm name - here it is AES
    			*/
    			aesCipher = Cipher.getInstance("AES");
    
    			/**
    			* Step 3. Initialize the Cipher for Encryption
    			*/
    			aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
    		}
    
    		catch (NoSuchAlgorithmException noSuchAlgo)
    		{
    			System.out.println(" No Such Algorithm exists " + noSuchAlgo);
    		}
    
    		catch (NoSuchPaddingException noSuchPad)
    		{
    			System.out.println(" No Such Padding exists " + noSuchPad);
    		}
    
    		catch (InvalidKeyException invalidKey)
    		{
    			System.out.println(" Invalid Key " + invalidKey);
    		}
    	}
    	
    	public String encrypt(String strDataToEncrypt)
    	{
    		/**
    		* Step 4. Encrypt the Data 
    		* 	1. Declare / Initialize the Data. Here the data is of type String 
    		* 	2. Convert the Input Text to Bytes 
    		* 	3. Encrypt the bytes using doFinal method
    		*/
    		try
    		{
    			byteDataToEncrypt = strDataToEncrypt.getBytes();
    			byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
    			strCipherText = new BASE64Encoder().encode(byteCipherText);
    			//System.out.println("Cipher Text generated using AES is " + strCipherText);
    		}
    		catch (BadPaddingException badPadding)
    		{
    			System.out.println(" Bad Padding " + badPadding);
    		}
    		catch (IllegalBlockSizeException illegalBlockSize)
    		{
    			System.out.println(" Illegal Block Size " + illegalBlockSize);
    		}
    		
    		return strCipherText;
    	}
    	
    	public String decrypt(String strCipherText)
    	{
    		/**
    		* Step 5. Decrypt the Data 
    		* 	1. Initialize the Cipher for Decryption
    		* 	2. Decrypt the cipher bytes using doFinal method
    		*/
    		try
    		{
    			//byteCipherText = strCipherText.getBytes();
    			byteCipherText = new BASE64Decoder().decodeBuffer(strCipherText);
    			aesCipher.init(Cipher.DECRYPT_MODE, secretKey, aesCipher.getParameters());
    			byteDecryptedText = aesCipher.doFinal(byteCipherText);
    			strDecryptedText = new String(byteDecryptedText);
    			//System.out.println(" Decrypted Text message is " + strDecryptedText);
    		}
    		catch (Exception e)
    		{
    			System.out.println(e.toString());
    		}
    		
    		return strDecryptedText;
    	}
    }
    Last edited by wmd; 08-15-2012 at 07:27 PM.

  20. #20
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: Problem with TripleDES

    All your exception handling is wrong.
    As you have been told several times already.
    If you get an exception in there you will have no idea where it came from.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Small problem with problem with Java, C++ parse program.
    By dragstang86 in forum New To Java
    Replies: 4
    Last Post: 10-30-2011, 03:43 AM
  2. Replies: 9
    Last Post: 09-21-2010, 04:15 PM
  3. TripleDes
    By thekop in forum New To Java
    Replies: 1
    Last Post: 09-22-2009, 09:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •