1

My Code

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.*;

import org.apache.commons.codec.binary.Base64;

public class FrontierCipher
{
    private static final String ALGO = "AES";
    private static String keyString = "00112233445566778899AABBCCDDEEFF0123456789ABCDEF0123456789ABCDEF";

     private static Key generateKey() throws Exception 
     {
        Key key = new SecretKeySpec(convertToByteArray(keyString), ALGO);
        return key;
    }
    public static byte[] encryptBytes(byte[] data) throws Exception
    {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);

        byte[] encVal = c.doFinal(data);
        byte[] encryptedValue = Base64.encodeBase64(encVal);

        return encryptedValue;
    }

    public static byte[] decrpytBytes(byte[] encryptedData) throws Exception
    {   
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);

        byte[] decordedValue = Base64.decodeBase64(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);

        return decValue;
    }

    public static byte[] convertToByteArray(String key) throws KeySizeException
    {
        if(key.length()<64)
            throw new KeySizeException("Key must contain 64 characters");

        byte[] b = new byte[32];

        for(int i=0, bStepper=0; i<key.length()+2; i+=2)
            if(i !=0)
                b[bStepper++]=((byte) Integer.parseInt((key.charAt(i-2)+""+key.charAt(i-1)), 16));

        return b;
    }


    public static void main(String[] args) throws Exception
    {
        byte[] password  = {6,75,3};
        byte[] passwordEnc = encryptBytes(password);
        byte[] passwordDec = decrpytBytes(passwordEnc);

        System.out.println("Plain Text : " + password[0]+" "+ password[1]+" "+ password[2]);
        System.out.println("Encrypted Text : " + passwordEnc[0]+" "+ passwordEnc[1]+" "+ passwordEnc[2]);
        System.out.println("Decrypted Text : " + passwordDec[0]+" "+passwordDec[1]+" "+passwordDec[2]);
    }
}

When run locally

Plain Text : 6 75 3
Encrypted Text : 74 43 117
Decrypted Text : 6 75 3

When run, waiting for udp packet to come I get this

   javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)

TestServer Using

private static void udpServer()
    {
        try
        {      //This is whats coming in ==> byte[] password={6,75,3};

            DatagramSocket serverSocket = new DatagramSocket(18000);
            byte[] receiveData = new byte[64];

            while (true)
            {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);

                byte[] b = decrpytBytes(receivePacket.getData());
            }
        }
        catch(Exception e)
        {
            //blahh
        }
    }
stackoverflow
  • 18,348
  • 50
  • 129
  • 196
  • Hope this threads will be helpful for you : http://stackoverflow.com/questions/3954611/aes-encript-and-decript-problem-with-apache-base64 http://stackoverflow.com/questions/3180878/exception-in-aes-decryption-algorithm-in-java – Martin V. Jan 31 '13 at 23:02
  • 3
    Why are you converting the data to base64, if you're transporting it in binary? – Jon Skeet Jan 31 '13 at 23:10
  • What is the length of the byte array from `getData()`? – Lawrence Dol Jan 31 '13 at 23:13
  • @JonSkeet no clue to be honest. This is what every tutorial does for encryption so I tend to be sheepish and did the same. I assumed apache's base64 converter took care of padding issues. But to be honest I have no clue whats going on – stackoverflow Jan 31 '13 at 23:13
  • 2
    @Mrshll187: I suspect the problem is actually that you're just using `getData()` without calling `getLength()`, but the base64 is confusing things further. – Jon Skeet Jan 31 '13 at 23:14
  • @SoftwareMonkey since I put it into a 64 byte array it turns out to be 64 bytes – stackoverflow Jan 31 '13 at 23:14
  • Then what is the length of the actual data put into the 64 byte array? – Lawrence Dol Jan 31 '13 at 23:16
  • @JonSkeet Can I encrypt/decrypt without using Base64 encoding? – stackoverflow Jan 31 '13 at 23:16
  • @Mrshll187 yes, actually, you can only encrypt/decrypt bytes. So if you need to transport the bytes (which can have any value, not just ones that map to characters) using a text based service, only then do you need to encode using e.g. base 64. – Maarten Bodewes Jan 31 '13 at 23:20
  • @owlstead I guess that would explain why all the examples I was going off of were using strings to encrypt/decrypt with. – stackoverflow Jan 31 '13 at 23:22
  • @SoftwareMonkey well I put 3 bytes in my byte array and encrypted them. So there should be three encrypted bytes sitting in a byte array of 64 – stackoverflow Jan 31 '13 at 23:23
  • Yeah, but the base 64 decoder gets the full buffer, not just the bytes received. I think that is where the problem lies, take Jon's hint and use `getLength()`. – Maarten Bodewes Jan 31 '13 at 23:25
  • 2
    Besides that, you should not use `sun.misc`, use e.g. the Apache codec library instead **if** you require base 64. Personally I dislike base 64 encoders that output byte arrays by the way, the whole idea is that base 64 is text, not binary. Imagine the fun when you insert the base 64 encoded binary into something that is not compatible with ASCII (but if this goes over the top of your head, first start off by ripping out the base 64 from your UDP packets). – Maarten Bodewes Jan 31 '13 at 23:29
  • I apologize if I'm a little bit thick headed but how is that going to help me? I mean where exactly are you indicating I should use getLength? – stackoverflow Jan 31 '13 at 23:29
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/23742/discussion-between-owlstead-and-mrshll187) – Maarten Bodewes Jan 31 '13 at 23:30

1 Answers1

1

OK, this is a terrible example that I will update later, I will have to sleep.

Note that using ECB encoding is always unsafe for normal data. CBC encoding is terribly unsafe when there is a possibility of a man-in-the-middle attack (padding Oracle attack). But it should work. If you have an updated Java 7, try and use "AES/GCM/NoPadding" and don't forget to send the randomized IV to the other side as well.

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class UDP_AES {


    /**
     * @param args
     * @throws SocketException 
     */
    public static void main(String[] args) throws SocketException {


        Thread t = new Thread(new Runnable() {
            DatagramSocket socket;
            byte[] receiveData = new byte[1024];
            Cipher aesCipher;

            {
                try {
                    socket = new DatagramSocket(18000);
                    aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                    IvParameterSpec zeroIV = new IvParameterSpec(new byte[aesCipher.getBlockSize()]);
                    SecretKey key = new SecretKeySpec(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,}, "AES");
                    aesCipher.init(Cipher.DECRYPT_MODE, key, zeroIV);
                } catch (Exception e) {
                    throw new IllegalStateException("Could not create server socket or cipher", e);
                }

            }

            @Override
            public void run() {
                while (true) {
                    DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);

                    try {
                        socket.receive(packet);
                        final byte[] plaintextBinary = aesCipher.doFinal(packet.getData(), 0, packet.getLength());
                        String plaintext = new String(plaintextBinary, Charset.forName("UTF-8"));
                        System.out.println(plaintext);
                    } catch (Exception e) {
                        throw new IllegalStateException("Could not receive or decrypt packet");
                    }
                }
            }

        });
        t.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // yeah, whatever
        }

        DatagramSocket sendingSocket = new DatagramSocket();
        String plaintext = "1234";
        byte[] plaintextBinary = plaintext.getBytes(Charset.forName("UTF-8"));

        try {
            Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKey key = new SecretKeySpec(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,}, "AES");
            IvParameterSpec zeroIV = new IvParameterSpec(new byte[aesCipher.getBlockSize()]);
            aesCipher.init(Cipher.ENCRYPT_MODE, key, zeroIV);
            final byte[] ciphertextBinary = aesCipher.doFinal(plaintextBinary);

        DatagramPacket sendingPacket = new DatagramPacket(ciphertextBinary, ciphertextBinary.length);
        sendingPacket.setSocketAddress(new InetSocketAddress("localhost", 18000));
            sendingSocket.send(sendingPacket);
        } catch (Exception e) {
            throw new IllegalStateException("Could not send or encrypt", e);
        }
    }

}
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Thank you I appreciate your response. This seems to be working. I'm not too keen on what that IvParameterSpec is really dooing though – stackoverflow Feb 01 '13 at 15:29
  • You will always need an IV if you encrypt multiple messages with the same key. That IV should be randomized for most cipher modes, and is most of the time prepended to the ciphertext. ECB does not use an V but is unsafe for encrypting e.g. text. – Maarten Bodewes Feb 01 '13 at 16:51