RsaKeyEncryption.java for RSA Encryption Operation

This section provides a tutorial example on how to implement RSA encryption operation using the java.math.BigInteger class. The important part of the implementation is to determine the cleartext block size, ciphertext block size, and the padding of the last block.

Finally, we are ready to implement the RSA public key encryption operation using the java.math.BigInteger class. Here is my initial draft:

/* RsaKeyEncryption.java
#- Copyright (c) 2013, HerongYang.com, All Rights Reserved.
 */
import java.math.BigInteger;
import java.io.*;
class RsaKeyEncryption {
   private BigInteger n, e;
   public static void main(String[] a) {
      if (a.length<3) {
         System.out.println("Usage:");
         System.out.println("java RsaKeyEncryption key input output");
         return;
      }
      String keyFile = a[0];
      String input = a[1];
      String output = a[2];

      RsaKeyEncryption encryptor = new RsaKeyEncryption(keyFile);
      encryptor.encrypt(input,output);
   }

// Reading in RSA public key
   RsaKeyEncryption(String input) {
      try {
         BufferedReader in = new BufferedReader(new FileReader(input));
         String line = in.readLine();
         while (line!=null) {
            if (line.indexOf("Modulus: ")>=0) {
               n = new BigInteger(line.substring(9));
            }
            if (line.indexOf("Public key: ")>=0) {
               e = new BigInteger(line.substring(12));
            }
            line = in.readLine();
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
      System.out.println("--- Reading public key ---");
      System.out.println("Modulus: "+n);
      System.out.println("Key size: "+n.bitLength());
      System.out.println("Public key: "+e);
   }

// Encrypting original message
   public void encrypt(String intput, String output) {
      int keySize = n.bitLength();                       // In bits
      int clearTextSize = Math.min((keySize-1)/8,256);   // In bytes
      int cipherTextSize = 1 + (keySize-1)/8;            // In bytes
      System.out.println("Cleartext block size: "+clearTextSize);
      System.out.println("Ciphertext block size: "+cipherTextSize);
      try {
         FileInputStream fis = new FileInputStream(intput);
         FileOutputStream fos = new FileOutputStream(output);
         byte[] clearTextBlock = new byte[clearTextSize];
         byte[] cipherTextBlock = new byte[cipherTextSize];
         long blocks = 0;
         int dataSize = fis.read(clearTextBlock);
         boolean isPadded = false; 

//       Reading input message
         while (dataSize>0) {
            blocks++;
            if (dataSize<clearTextSize) {
               padBytesBlock(clearTextBlock,dataSize);
               isPadded = true;
            }
            
            BigInteger clearText = new BigInteger(1,clearTextBlock);
            BigInteger cipherText = clearText.modPow(e,n);
            byte[] cipherTextData = cipherText.toByteArray();
            putBytesBlock(cipherTextBlock,cipherTextData);
            fos.write(cipherTextBlock);
            
            dataSize = fis.read(clearTextBlock);
         }

//       Adding a full padding block, if needed
         if (!isPadded) {
            blocks++;
            padBytesBlock(clearTextBlock,0);
            BigInteger clearText = new BigInteger(1,clearTextBlock);
            BigInteger cipherText = clearText.modPow(e,n);
            byte[] cipherTextData = cipherText.toByteArray();
            putBytesBlock(cipherTextBlock,cipherTextData);
            fos.write(cipherTextBlock);
         }

         fis.close();
         fos.close();
         System.out.println("Encryption block count: "+blocks);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }

// Putting bytes data into a block
   public static void putBytesBlock(byte[] block, byte[] data) {
      int bSize = block.length;
      int dSize = data.length;
      int i = 0;
      while (i<dSize && i<bSize) {
          block[bSize-i-1] = data[dSize-i-1];
          i++;
      }
      while (i<bSize) {
          block[bSize-i-1] = (byte)0x00;
          i++;
      }
   }

// Padding input message block
   public static void padBytesBlock(byte[] block, int dataSize) {
      int bSize = block.length;
      int padSize = bSize - dataSize;
      int padValue = padSize%bSize;
      for (int i=0; i<padSize; i++) {    
          block[bSize-i-1] = (byte) padValue;
      }
   }
}

Some notes on RsaKeyEncryption.java:

Testing result is presented in the next tutorial.

Last update: 2013.

Table of Contents

 About This Book

 Cryptography Terminology

 Cryptography Basic Concepts

 Introduction to AES (Advanced Encryption Standard)

 Introduction to DES Algorithm

 DES Algorithm - Illustrated with Java Programs

 DES Algorithm Java Implementation

 DES Algorithm - Java Implementation in JDK JCE

 DES Encryption Operation Modes

 DES in Stream Cipher Modes

 PHP Implementation of DES - mcrypt

 Blowfish - 8-Byte Block Cipher

 Secret Key Generation and Management

 Cipher - Secret Key Encryption and Decryption

 Introduction of RSA Algorithm

RSA Implementation using java.math.BigInteger Class

 java.Math.BigInteger Class

 Generating Prime Number with BigInteger Class

 Performance of Prime Number Generation

 RSA Encryption Implementation using BigInteger Class

 RsaKeyGenerator.java for RSA Key Generation

 RSA Keys Generated by RsaKeyGenerator.java

 RsaKeyValidator.java for RSA Key Validation

 64-bit RSA Key Validated by RsaKeyValidator.java

 Converting Byte Sequences to Positive Integers

 Cleartext Block Size for RSA Encryption

 Cleartext Message Padding and Revised Block Size

 Ciphertext Block Size for RSA Encryption

RsaKeyEncryption.java for RSA Encryption Operation

 RsaKeyDecryption.java for RSA Decryption Operation

 Testing RsaKeyEncryption.java with a 16-bit Key

 Testing RsaKeyEncryption.java with a 64-bit Key

 Testing RsaKeyEncryption.java with a 3072-bit Key

 Introduction of DSA (Digital Signature Algorithm)

 Java Default Implementation of DSA

 Private key and Public Key Pair Generation

 PKCS#8/X.509 Private/Public Encoding Standards

 Cipher - Public Key Encryption and Decryption

 MD5 Mesasge Digest Algorithm

 SHA1 Mesasge Digest Algorithm

 OpenSSL Introduction and Installation

 OpenSSL Generating and Managing RSA Keys

 OpenSSL Managing Certificates

 OpenSSL Generating and Signing CSR

 OpenSSL Validating Certificate Path

 "keytool" and "keystore" from JDK

 "OpenSSL" Signing CSR Generated by "keytool"

 Migrating Keys from "keystore" to "OpenSSL" Key Files

 Certificate X.509 Standard and DER/PEM Formats

 Migrating Keys from "OpenSSL" Key Files to "keystore"

 Using Certificates in IE (Internet Explorer)

 Using Certificates in Firefox

 Using Certificates in Google Chrome

 Outdated Tutorials

 References

 PDF Printing Version