Hello

Dont ask why but lets say I want to encrypt "hello" and the encrypted forum is "238324"

I want to do:

String avariable=dcrypt(238324); //avariable should now hold hello

public string dcrypt(String encryptedtext)
{
//do decrypt stuff
return descriptedtext; //decriptedtext should be hello
}

Basically thats what I want.....Dont care for algoritim AES MD5 etc....

Thanks

I think I'll ask why anyway. Are you trying to reverse engineer an algorithm or something?

This looks easy

This looks easy

Im not sure thats exactly what I am looking for....

Ill use first something like this: http://7thspace.com/webmaster_tools/online_md5_encoder.html

For example, hello gives me 5d41402abc4b2a76b9719d911017c592

My program will only have decryption, not encryption. I dont mind if its easy encryption such as md5...

MD5 is a message digest, it reduces the text, no matter how long, to a fiexd length hex string. It's one-way, you can't decode the digest back to the original text, which is what I thought you wanted to do?

MD5 was a example of what I wanted to do.

Hmmm - one of us is very confused, but I'm not sure who!

Using MD5, if you convert "hello" to the MD5 equivalent of "238324" then it's simply not possible to convert the "238324" back to "hello" like your first post requires.

if you don't know what you're looking for, how would you know when you've found it?

simplest form of course is

public String dcrypt(long input) {
    return "Hello";
}

:)

Im problably not explaining myself correctly.

With AES:

http://www.movable-type.co.uk/scripts/aes.html

hello is 5wHNILVjTFEbxnmwSw==

I would put a function that is decrypt(5wHNILVjTFEbxnmwSw==)

and that would return hello.

BTW, Im looking on how to do it; Dont really think if it is secure or not. Ignore that part.

The very first link I posted yesterday showed you exactly how to do that. It's only a few lines of copy/paste code.

Im looking at that page in IE9 and it is telling me Sorry, the browser you are using is not currently supported. To use the comments, Disqus recommends the following browsers:

What kind of bullshit is this? (Thats towards the webmaster not you, James)

I adapted the code on that page into a little class...

class EncoderDecoder {
   private Cipher c;
   private SecretKeySpec k;
   public EncoderDecoder(byte[] key) {
      assert key.length == 16;
      k = new SecretKeySpec(key, "AES");
      try {
         c = Cipher.getInstance("AES");
      } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
         e.printStackTrace();
      }
   }
   public byte[] encode(byte[] data) {
      try {
         c.init(Cipher.ENCRYPT_MODE, k);
         return c.doFinal(data);
      } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
         e.printStackTrace();
         return null;
      }
   }
   public byte[] decode(byte[] encryped) {
      try {
         c.init(Cipher.DECRYPT_MODE, k);
         return c.doFinal(encryped);
      } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
         e.printStackTrace();
         return null;
      }
   }
}

Little demo/test:

         byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 };//... secret sequence of 16 bytes
         EncoderDecoder code = new EncoderDecoder(key);
         byte[] sourceData = "hello from encrypted me".getBytes();
         byte[] codedData = code.encode(sourceData);
         byte[] endData = code.decode(codedData);
         System.out.println(new String(endData));

Feel free to adapt from this
JC

Did not read your post (will use your code). Sorry.

I made this:

package EncryptDerypt;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class EncryptDecrypt {

    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        String input="Hello";
        String eresult= encrypt(input);
        System.out.println("Encrypted is: " + eresult);
        String dresult= decrypt(eresult);
        System.out.println("Decrypted is: " + dresult);



    }

    public static String encrypt(String dstring)
    {
        String result="";
        String skey="123123";
        byte[] key = skey.getBytes();
        byte[] dataToSend = dstring.getBytes();

        try {
            Cipher c = Cipher.getInstance("AES");
            SecretKeySpec k =  new SecretKeySpec(key, "AES");
            try {
                c.init(Cipher.ENCRYPT_MODE, k);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            byte[] encryptedData = c.doFinal(dataToSend);
            result=encryptedData.toString();
            return result;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;



    }

    public static String decrypt(String encrypteddata)
    {
        String result="";
        String skey="123123";
        byte[] key = skey.getBytes();
                byte[] encryptedData = encrypteddata.getBytes();

                Cipher c;
                try {
                    c = Cipher.getInstance("AES");
                    SecretKeySpec k =
                              new SecretKeySpec(key, "AES");
                            try {
                                c.init(Cipher.DECRYPT_MODE, k);
                                try {
                                    byte[] data = c.doFinal(encryptedData);
                                    result=data.toString();
                                    return result;
                                } catch (IllegalBlockSizeException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (BadPaddingException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } catch (InvalidKeyException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }


                } catch (NoSuchAlgorithmException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return result;

                // do something with data
    }

}

And it popped this:

java.security.InvalidKeyException: Invalid AES key length: 6 bytes
    at com.sun.crypto.provider.AESCipher.engineGetKeySize(DashoA13*..)
    at javax.crypto.Cipher.b(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at EncryptDerypt.EncryptDecrypt.encrypt(EncryptDecrypt.java:40)
    at EncryptDerypt.EncryptDecrypt.main(EncryptDecrypt.java:20)
Exception in thread "main" java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.c(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
    at EncryptDerypt.EncryptDecrypt.encrypt(EncryptDecrypt.java:45)
    at EncryptDerypt.EncryptDecrypt.main(EncryptDecrypt.java:20)

Why not make just one big class instead of splitting it up?

The clue's in my code:
assert key.length == 16;
AES requires the key to be byte[16], hence "Invalid AES key length: 6 bytes"

You can also run into problems becuase you convert the encoded text into a String, then convert it back to byte array to decode it. Because Java Strings are chars, not bytes, byte[] -> String ->byte[] is a nightmare in Java, despite the fact that it should be OK unless you change the default charset. The encrypted byte array will contain any/all possible values, and some of those just don't convert to/from String as you would expect. Try this:

      byte[] b = new byte[256];
      for (int i = 0; i<256; i++)  b[i] = (byte) i; // all 256 possible values
      String s = new String(b); // convert to String (default charset)
      byte[] b2 = s.getBytes(); // convert back to byte[] (default charset)
      for (int i = 0; i<256; i++) { // check resulting array is correct...
         if (b2[i] != b[i])  System.out.println(b[i] + " != " +b2[i]); // oops!
      }

On my system there are 5 values that get corrupted. Maybe you can fix this by specifying some suitable charset? I don't know.
The encrypted text won't be printable anyway, so I would just keep it as a byte[]. If you really want a String version I would use something like base64 to convert the byte[] to an all-printable String and v.v.

Why not make just one big class instead of splitting it up?

? I don't understand that question.
It's just one small class, designed for simple re-use. Get an instance by setting the encryption key in the consructor, then use that instance to encrypt/decrypt as much as you like.

? I don't understand that question.
It's just one small class, designed for simple re-use. Get an instance by setting the encryption key in the consructor, then use that instance to encrypt/decrypt as much as you like.

I ment like just make one class with all of that and a simply void main. Im not going to even do encrypting; I just need the encrypting method to test out if input/output is correct or not.

It's a deeply engrained habit. Every time I write some new code that could possible be useful somewhere else in the future, I always try to package it in a small self-contained class and keep it in my repository. After a few years that repository is a goldmine of useful stuff that saves me time almost every day.
That process also helps to structure code properly - interfaces become explicit and clear, responsibities are correctly separated.
I haven't looked at AES encryption before, but now I've got a neat little package that does it for me, and is the basis for implementing some of the things that you need to make AES properly secure. So the time I spent on it wasn't just "spent", it was invested

Well one guy's habit usually doesnt agree with anothers!

Thank you for helping.

@james,
Your "NoSuchAlgorithmException" gives the following error for me:

No exception of type Object can be thrown; an exception type must be a subclass of Throwable

My catch clauses use a Java 7 construct that's not available in earlier versions -
catch (Exception1 | Exception2 ... // single catch for multiple exception types
If you are using an old veriosn of Java you will need to split those into separate catch clauses, or just "cheat" them into a single catch (Exception e)

If you're using Java 7 maybe you are missing an import?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.