Home how to decrypt image received from server
Reply: 0

how to decrypt image received from server

user6319 Published in June 19, 2018, 4:09 pm

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.


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)
        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");

        //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");

        //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() + " <-> /");

            OutputStream sos = socket.getOutputStream();

            // get the image from a webcam
            URL myimage = new URL("");

            //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();
            } catch (Exception ee) {
                System.out.println("Check internet connection please");
            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));

            System.out.println("-------------- Done ----------");



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()];

        Socket socket = new Socket("", 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");

        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");

        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(Long.toString((int) buf[i] & 0xff, 16));
            // Return result string in Hexadecimal format
            return strbuf.toString();
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO