5 Replies Latest reply: Aug 3, 2011 8:49 AM by 796440 RSS

    creating the simplest string encrypt/decrypt example - yet no success

    itichy
      Being a crypt newbie I try to construct a simple string encryption/decryption example, but somehow the decrypted result differs too much :-)
      Can someone point me to the error in my reasoning? Thanks!

      import java.security.InvalidKeyException;
      import java.security.NoSuchAlgorithmException;
      import java.security.NoSuchProviderException;
      import javax.crypto.BadPaddingException;
      import javax.crypto.Cipher;
      import javax.crypto.IllegalBlockSizeException;
      import javax.crypto.NoSuchPaddingException;
      import javax.crypto.spec.SecretKeySpec;
      public class dum_8_decrypt64 {

      public static void main( String [] args ) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

           String input = "Hello, world!";
           String passkey = "nv93h50sk1zh508v";
           SecretKeySpec key;
           Cipher cipher = null;
           Cipher dcipher = null;
           String result,dresult;
           
           key = new SecretKeySpec(passkey.getBytes(), "AES");
           
           cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
           cipher.init(Cipher.ENCRYPT_MODE, key);

           result = new String(cipher.doFinal(input.getBytes()));
           
           System.out.println(" Encrypted String --------->"+ result + "<----------");
           
           dcipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
           dcipher.init(Cipher.DECRYPT_MODE, key);
           dresult = new String(cipher.doFinal(result.getBytes()));


           System.out.println(" Decrypted String --------->"+ dresult + "<----------");
           
           }
      }

      Output:

      Encrypted String --------->„
      pÿƒG¬µ?(.«<----------


      Decrypted String --------->QbkÚÛ $Ñ     5ÓâW’?);YEútÐp3Wvk<----------