Blog Archive

JAVA RSA encrypt file with public key using bouncy castle Crypto APIs

The following sample code encrypts a file using RSA public key. You can pass the public key file name, input file name to encrypt and file name to contain hex encoded encrypted data. This program is very handy when it comes to encrypting xml file or text file. Before you can run the program you need to install the following jars in your classpath. Learn RSA Encryption and Decryption Basics

TIP: Get jars based on your java installation
package com.as400samplecode;


import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PublicKeyFactory;

import sun.misc.BASE64Decoder;

public class RSAEncryptFile {

    public static void main(String[] args)

        String publicKeyFilename = null;
        String inputFilename = null;
        String encryptedFilename = null;

        RSAEncryptFile rsaEncryptFile = new RSAEncryptFile();

        if (args.length < 3)
            System.err.println("Usage: java "+ rsaEncryptFile.getClass().getName()+
            " Public_Key_Filename Input_Filename Encrypted_Filename");

        publicKeyFilename = args[0].trim();
        inputFilename = args[1].trim();
        encryptedFilename = args[2].trim();
        rsaEncryptFile.encrypt(publicKeyFilename, inputFilename, encryptedFilename);


    private void encrypt (String publicKeyFilename, String inputFilename, String encryptedFilename){

        try {

            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            String value = "";
            String key = readFileAsString(publicKeyFilename);
            BASE64Decoder b64 = new BASE64Decoder();
            AsymmetricKeyParameter publicKey = 
                (AsymmetricKeyParameter) PublicKeyFactory.createKey(b64.decodeBuffer(key));
            AsymmetricBlockCipher e = new RSAEngine();
            e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
            e.init(true, publicKey);

            String inputdata = readFileAsString(inputFilename);
            byte[] messageBytes = inputdata.getBytes();
            int i = 0;
            int len = e.getInputBlockSize();
            while (i < messageBytes.length)
                if (i + len > messageBytes.length)
                    len = messageBytes.length - i;

                byte[] hexEncodedCipher = e.processBlock(messageBytes, i, len);
                value = value + getHexString(hexEncodedCipher);
                i += e.getInputBlockSize();

            BufferedWriter out = new BufferedWriter(new FileWriter(encryptedFilename));
        catch (Exception e) {

    public static String getHexString(byte[] b) throws Exception {
        String result = "";
        for (int i=0; i < b.length; i++) {
            result +=
                Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
        return result;

    private static String readFileAsString(String filePath)
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while(( != -1){
            String readData = String.valueOf(buf, 0, numRead);
            buf = new char[1024];
        return fileData.toString();