Code to Encrypt and Decrypt in AES

Java allows you to play online games, chat with people around the world, calculate your mortgage interest, and view images in 3D, just to name a few. It's also integral to the intranet applications and other e-business solutions that are the foundation of corporate computing.
Admin
Site Admin
Posts: 951
Joined: Thu Aug 23, 2007 10:35 am

Code to Encrypt and Decrypt in AES

Postby Admin » Tue Aug 16, 2011 3:30 pm

Open a Command Line and type to encrypt:
java -jar "C:\DecryptConsole.jar" encrypt 123456
encrypt
cb71981e1652e4113774a761fdbd752d

Open a Command Line and type to decrypt:
java -jar "C:\DecryptConsole.jar" decrypt cb71981e1652e4113774a761fdbd752d
decrypt
123456

Code: Select all

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package decryptconsole;

import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author 24556
 */
public class Main {
  private static byte[] m_rawKey = { -93, -86, 119, -94, 23, -39, -76, -46, -61, 5, 55, -24, 99, 75, 8, -94 };
  private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    /**
     * @param args the command line arguments
     */
        public static void main(String[] args) {
            // TODO code application logic here
            try
            {
                System.out.println(args[0]);

                if (args[0].equals("encrypt"))
                {
                    //encrypt("123456", m_rawKey);
                    String MyRet = encrypt(args[1], m_rawKey);
                    System.out.println(MyRet);
                }

                if (args[0].equals("decrypt"))
                {
                    //String Decrypted = decrypt("cb71981e1652e4113774a761fdbd752d", m_rawKey);
                    String Decrypted = decrypt(args[1], m_rawKey);
                    System.out.println(Decrypted);
                }
            }
            catch (Exception MyEx)
            {
             System.out.println("Failed");
            }
        }

        private static String decrypt(String paramString, byte[] paramArrayOfByte) throws Exception
      {
        if (paramString.startsWith("cleartext:"))
        {
          return paramString.substring("cleartext:".length());
        }

        if ((paramString.length() == 0) || (paramString.length() % 2 > 0))
        {
          throw new Exception("Invalid string length or encoding for decryption.");
        }

        byte[] arrayOfByte1;
        try
        {
          arrayOfByte1 = (byte[])(byte[])decode(paramString);
        }
        catch (Exception localDecoderException) {
          throw new Exception("Invalid encoding for decryption: " + localDecoderException.toString());
        }
        String str;
        try {
          Cipher localCipher = getCipher(2, paramArrayOfByte);
          byte[] arrayOfByte2 = localCipher.doFinal(arrayOfByte1);
          str = new String(arrayOfByte2);
        }
        catch (GeneralSecurityException localGeneralSecurityException)
        {
          throw new Exception("Error decrypting text.", localGeneralSecurityException);
        }

        return str;
      }

        private static String encrypt(String paramString, byte[] paramArrayOfByte) throws Exception
      {
        String str = null;
        try
        {
          Cipher localCipher = getCipher(1, paramArrayOfByte);
          byte[] arrayOfByte = localCipher.doFinal(paramString.getBytes());

          str = new String(encode(arrayOfByte));
        }
        catch (GeneralSecurityException localGeneralSecurityException)
        {
          localGeneralSecurityException.printStackTrace();
          throw new Exception("Error encrypting text.", localGeneralSecurityException);
        }
        return str;
      }
        public static byte[] encode(byte[] array)
      {
        return new String(encodeHex(array)).getBytes();
      }
         public static char[] encodeHex(byte[] data)
      {
        int l = data.length;

        char[] out = new char[l << 1];

        int i = 0; for (int j = 0; i < l; i++) {
          out[(j++)] = DIGITS[((0xF0 & data[i]) >>> 4)];
          out[(j++)] = DIGITS[(0xF & data[i])];
        }

        return out;
      }

         public static byte[] decode(byte[] array)
        throws Exception
      {
        return decodeHex(new String(array).toCharArray());
      }

         public static Object decode(Object object)
            throws Exception
          {
            try
            {
              char[] charArray = (object instanceof String) ? ((String)object).toCharArray() : (char[])object;
              return decodeHex(charArray); } catch
              (ClassCastException e) {

            throw new Exception(e.getMessage());
          }
        }


           public static byte[] decodeHex(char[] data)
        throws Exception
      {
        int len = data.length;

        if ((len & 0x1) != 0) {
          throw new Exception("Odd number of characters.");
        }

        byte[] out = new byte[len >> 1];

        int i = 0; for (int j = 0; j < len; i++) {
          int f = toDigit(data[j], j) << 4;
          j++;
          f |= toDigit(data[j], j);
          j++;
          out[i] = (byte)(f & 0xFF);
        }

        return out;
      }

           protected static int toDigit(char ch, int index)
        throws Exception
      {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
          throw new Exception("Illegal hexadecimal charcter " + ch + " at index " + index);
        }
        return digit;
      }


        private static Cipher getCipher(int paramInt, byte[] paramArrayOfByte) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException
      {
        SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte, "AES");
        Cipher localCipher = Cipher.getInstance("AES");
        localCipher.init(paramInt, localSecretKeySpec);
        return localCipher;
      }


}

Return to “Java”

Who is online

Users browsing this forum: No registered users and 1 guest