Postagens

Mostrando postagens de 2017

AES Cipher in Java

How to implementing AES cipher in JAVA and main problems you may find in this challenge. When I started, I tried to do a parallel between my 3Des implementation and AES , so I discovered the first difference: I tried to generate a SecretKey from a pass-phrase for AES in the following way, KeySpec aesSpec = new KeySpec(key.getBytes(), "AES"); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES"); SecretKey secretKey = keyFactory.generateSecret(aesSpec); This is the very similar how I do with 3Des : KeySpec TDesSpec = new DESKeySpec( key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey secretKey = keyFactory.generateSecret(aesSpec); However when I tested, it threw an exception "AES SecretKeyFactory not available". So the solution was made some small change: SecretKey secretKey = new SecretKeySpec( key.getBytes() , "AES"); There are two hints here: The key

How convert a data from Hexa to Byte Array

Problem! Promote the conversion between hex data to byte array and reverse. Sample: Hex 30 = 0 Byte[48] = 0 Java                                                   final protected static char [] HEX_ARRAY = "0123456789ABCDEF" .toCharArray(); private static byte [] toByteArray(String hexString) throws HexStringException {     int len = hexString.length();     byte [] data = new byte [len / 2];     try     {        for ( int i = 0; i < len; i += 2)       {           data[i / 2] = ( byte ) ((Character.digit(hexString.charAt(i), 16) << 4) +                    Character.digit(hexString.charAt(i + 1), 16));       }    } catch (Exception e)    {        throw new HexStringException(e);    }        return data; } private static String fromByteArray( byte [] buffer )   {     char[] hexChars = new char [buffer. length * 2];     for ( int j = 0; j < buffer. length ; j++)    {       int v = buffer[j] & 0xFF;       hexChars[j * 2] = HE