Home how to decrypt image received from server
Reply: 1

how to decrypt image received from server

john tan
1#
john tan Published in 2018-02-14 06:30:53Z

In my case, I have generated a RSA key pair and an AES key. I encrypted an image with an AES key which is further encrypted with the RSA public key. To decrypt the image, I will have to use the RSA private key to decrypt the AES key which in turn will be used to decrypt the image. Problem is, I know how to do this if it's just a single piece of code and now I have 2 pieces of code so I'm unsure as to how I'm going to decrypt the image downloaded from the server to my client.

The following code will allow the client to download the image from the server, but the image can't be opened because it's encrypted.

Server.java

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(15123);
        Socket socket = null;
        String path = "C:\\Users\\john\\Documents\\Applied Cryptography\\Assignment 2";

        //start of AES
        //Generate AES Key
        int sizeofkey = 128;
        KeyGenerator kg = KeyGenerator.getInstance("AES");

        //initialize with sizeofkey(aes)
        kg.init(sizeofkey);
        Key mykey = kg.generateKey();
        System.out.println("AES Key Generated");

        //create cipher object & initialize with generated key(aes)
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, mykey);

        //create RSA keypair(rsa)
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);

        //generate RSA keypair(rsa)
        KeyPair keyPair = keyPairGenerator.genKeyPair();

        //split keys(rsa) and store in file
        PublicKey pub = keyPair.getPublic();
        PrivateKey priv = keyPair.getPrivate();
        X509EncodedKeySpec pubkey = new X509EncodedKeySpec(pub.getEncoded());
        FileOutputStream fos = new FileOutputStream(path + "/public.key");
        fos.write(pubkey.getEncoded());
        fos.close();

        //Initialise the RSA cipher with PUBLIC key
        Cipher rsacipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsacipher.init(Cipher.ENCRYPT_MODE, pub);

        //Get bytes for AES key & encrypt bytes of AES key
        byte[] encryptedKey = mykey.getEncoded();
        byte[] cipherkey = rsacipher.doFinal(encryptedKey);
        System.out.println("AES key Encrypted");

        while (true) {
            socket = serverSocket.accept();
            System.out.println("Accepted connection : " + socket.getRemoteSocketAddress().toString() + " <-> /127.0.0.1:15123");

            OutputStream sos = socket.getOutputStream();

            // get the image from a webcam
            URL myimage = new URL("http://183.76.13.58:80/SnapshotJPEG?Resolution=640x480");

            //Picture in byte array format
            byte[] plainpic = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream is = null;
            try {
                //in = new DataInputStream(myimage.openStream());


                is = myimage.openStream();
                byte[] byteChunk = new byte[4096];
                int n;

                while ((n = is.read(byteChunk)) > 0) {
                    baos.write(byteChunk, 0, n);
                }

                //Picture in byte array format
                plainpic = baos.toByteArray();
                System.out.println(plainpic);
            } catch (Exception ee) {
                System.out.println("Check internet connection please");
                socket.close();
                return;
            }
            byte[] cipherpic = cipher.doFinal(plainpic);

            DateFormat dateFormat = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
            Date date = new Date();
            System.out.println("Sending image " + dateFormat.format(date));


            sos.write(cipherpic);
            System.out.println("-------------- Done ----------");

            is.close();
            sos.flush();
            sos.close();
            socket.close();
        }
    }
}

Client.java

public class Client {
    public static void main(String[] args) throws IOException {
        String fname = "image.jpg";
        String path = "C:\\Users\\john\\Documents\\Applied Cryptography\\Assignment 2";
        File pubkeyfile = new File(path + "/public.key");
        FileInputStream fis = new FileInputStream(path + "/public.key");
        byte[] encodedPubKey = new byte[(int) pubkeyfile.length()];
        fis.close();

        Socket socket = new Socket("127.0.0.1", 15123);
        InputStream is = null;
        byte[] isbytearray = null;
        try {

            is = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] byteChunk = new byte[40000];
            int n;

            while ((n = is.read(byteChunk)) > 0) {
                baos.write(byteChunk, 0, n);
            }
            isbytearray = baos.toByteArray();

            //decrypt encrypted byte[], convert decrypted byte[] to bytes
            //how to decrypt?

        } catch (Exception ee) {
            System.out.println("Check connection please");
            socket.close();
            return;
        }

        FileOutputStream fos = new FileOutputStream(fname);
        try {
            //write converted bytes to file to display picture
            fos.write(isbytearray); //this is the encrypted image,not the decrypted one
        } catch (EOFException ee) {
            System.out.println("File transfer complete");
            is.close();
        }
        fos.flush();
        fos.close();
        socket.close();

        public static String asHex ( byte buf[]){

            //Obtain a StringBuffer object
            StringBuffer strbuf = new StringBuffer(buf.length * 2);
            int i;

            for (i = 0; i < buf.length; i++) {
                if (((int) buf[i] & 0xff) < 0x10)
                    strbuf.append("0");
                strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
            }
            // Return result string in Hexadecimal format
            return strbuf.toString();
        }
    }
}
gusto2
2#
gusto2 Reply to 2018-02-14 07:10:44Z

you are completely neglecting IV (initializatiin vector).

In theory you are using always a new key so it could be static, but when encrypting with RSA it is randomly generated and you have to retain the IV (usually the IV is prepended to the ciphertext) and use the value when decrypting. Even when stated the iv could be static in you case, please build a habit to use it properly (random) iv)

Encrypting with AES and explicit IV

SecureRandom rnd = new SecureRandom();
byte[] iv = new byte[SYMMETRIC_BLOCK_SIZE / 8];
rnd.nextBytes(iv);
encryptionParams.setIv(iv);

IvParameterSpec ivParamSpec = new 
IvParameterSpec(iv);
SecretKey symmetricKey = new 
SecretKeySpec(encryptionParams.getKey(), SYMMETRIC_KEY_ALG);

Cipher cipher = 
Cipher.getInstance(SYMMETRIC_CIPHER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, symmetricKey, ivParamSpec);

and then decrypting

// encryptionParams is an object I use to pass ciphertext, iv and mac

IvParameterSpec ivParamSpec = new 
IvParameterSpec(encryptionParams.getIv());
// you can read iv as part of the passed data
SecretKey symmetricKey = new 
SecretKeySpec(encryptionParams.getKey(), SYMMETRIC_KEY_ALG);

Cipher cipher = 
Cipher.getInstance(SYMMETRIC_CIPHER_NAME);
cipher.init(Cipher.DECRYPT_MODE, symmetricKey, ivParamSpec);

for working and proper examples you could read e. g. https://gusto77.wordpress.com/2017/10/30/encryption-reference-project/

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.343292 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO