Hello dear friends
I am developing an application in java and in part of it i need to implement RSA encryption alogorithm that can encrypt any form and size of files ...
can someone please guide me to an implementable code of RSA ?

Recommended Answers

All 6 Replies

I have tried that a lot .... I have been searching over a week but a lot of contradition I found
some say RSA cannot be used to encrypt big files and its only used to encrypt small files like DES or AES key files
others say it can be used to encrypt any form of files by slpitting each files into samller block and encrypting each block solely by they didnt show thier full solution.
I am seeking a help from some who does large files encryption by splitting files or any other method that does the same job .
appreciated.

I googled java rsa encrypt large file
and this was the second hit...
Encrypting and decrypting large data using Java and RSA

ps: Did you see the warnings about how unsuitable RDA is for large files? Depending on how big your files are you could easily get into minutes or hours for the encryption/decryption.

i run this code and it run correctly, but the resulting file (encrypted.txt) file appears empty and with a size of 0 bytes
can someone explain why i am getting an empty file ?

package test_code;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.math.BigInteger;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.KeySpec;
    import java.security.spec.RSAPrivateKeySpec;
    import java.security.spec.RSAPublicKeySpec;

    import javax.crypto.Cipher;
    import javax.crypto.CipherInputStream;
    import javax.crypto.CipherOutputStream;

    class Test {

        public static void main(String[] args) throws Exception {
            generateKeys();
            rsaEncrypt("C://Users//Faiz//Desktop//link.txt", "C://Users//Faiz//Desktop//encrypted.txt");    // D://Pics//pic2.JPG
            rsaDecrypt("C://Users//Faiz//Desktop//encrypted.txt", "C://Users//Faiz//Desktop//decrypted.txt");
        }

        public static void generateKeys() throws Exception {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            KeyPair kp = kpg.genKeyPair();
            PublicKey publicKey = kp.getPublic();
            PrivateKey privateKey = kp.getPrivate();

            System.out.println("keys created");

            KeyFactory fact = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec pub = fact.getKeySpec(publicKey, RSAPublicKeySpec.class);
            RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,RSAPrivateKeySpec.class);

            saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
            saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());


        System.out.println("keys saved");
        }

        public static void saveToFile(String fileName, BigInteger mod,
                BigInteger exp) throws IOException {
            ObjectOutputStream fileOut = new ObjectOutputStream(
                    new BufferedOutputStream(new FileOutputStream(fileName)));
            try {
                fileOut.writeObject(mod);

                fileOut.writeObject(exp);
            } catch (Exception e) {
                throw new IOException("Unexpected error");
            } finally {
                fileOut.close();
                System.out.println("Closed writing file.");
            }
        }

        // Return the saved key
        static Key readKeyFromFile(String keyFileName) throws IOException {
            InputStream in = new FileInputStream(keyFileName);
            ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
                    in));
            try {
                BigInteger m = (BigInteger) oin.readObject();
                BigInteger e = (BigInteger) oin.readObject();
                KeyFactory fact = KeyFactory.getInstance("RSA");
                if (keyFileName.startsWith("public"))
                    return fact.generatePublic(new RSAPublicKeySpec(m, e));
                else
                    return fact.generatePrivate(new RSAPrivateKeySpec(m, e));
            } catch (Exception e) {
                throw new RuntimeException("Spurious serialisation error", e);
            } finally {
                oin.close();
                System.out.println("Closed reading file.");
            }
        }

        // Use this PublicKey object to initialize a Cipher and encrypt some data
        public static void rsaEncrypt(String file_loc, String file_des)
                throws Exception {
            byte[] data = new byte[32];
            int i;

            System.out.println("start encyption");

            Key pubKey = readKeyFromFile("public.key");
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);

            FileInputStream fileIn = new FileInputStream(file_loc);
            FileOutputStream fileOut = new FileOutputStream(file_des);
            CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher);

            // Read in the data from the file and encrypt it
            while ((i = fileIn.read(data)) != -1) {
                cipherOut.write(data, 0, i);
            }

            // Close the encrypted file
            cipherOut.close();
            fileIn.close();

            System.out.println("encrypted file created");
        }

        // Use this PublicKey object to initialize a Cipher and decrypt some data
        public static void rsaDecrypt(String file_loc, String file_des)
                throws Exception {
            byte[] data = new byte[32];
            int i;

            System.out.println("start decyption");

            Key priKey = readKeyFromFile("private.key");
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);

            FileInputStream fileIn = new FileInputStream(file_loc);
            CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
            FileOutputStream fileOut = new FileOutputStream(file_des);

            // Write data to new file
            while ((i = cipherIn.read()) != -1) {
                fileOut.write(i);
            }

            // Close the file
            fileIn.close();
            cipherIn.close();
            fileOut.close();

            System.out.println("decrypted file created");

        }
    }

Nopbody in their right mind will waste a single moment trying to debug code that sytematically and universally discards all its Exception info. They could waste hours when the answer was always there in an ignored Exception's messaage and stack trace.

Remove all the "throws Exception" clauses from your method definitions, catch all your Exceptions, and put an e.printStackTrace(); into all the catch blocks. Then run it again, then let's try to debug it.

commented: Yep! +9

it worked correctly when i used a smaller file .. isn't it suppose to throw an exception when the size of the file is greater than the RSA block size ?!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.