Java Code to Encrypt and Decrypt a Sample Client Random

The following Java code illustrates how to encrypt and decrypt with RSA.

import java.math.BigInteger;
public class RdpRsaEncrypt
{
    //
    // Print out the contents of a byte array in hexadecimal.
    //
    private static void PrintBytes(
        byte[] bytes
        )
    {
        int cBytes = bytes.length;
        int iByte = 0;
        for (;;) {
            for (int i = 0; i < 8; i++) {
                String hex = Integer.toHexString(bytes[iByte++] & 0xff);
                if (hex.length() == 1) {
                    hex = "0" + hex;
                }
                System.out.print("0x" + hex + " ");
                if (iByte >= cBytes) {
                    System.out.println();
                    return;
                }
            }
            System.out.println();
        }
    }
    //
    // Reverse the order of the values in a byte array.
    //
    public static void ReverseByteArray(
        byte[] array
        )
    {
        int i, j;
        byte temp;
        for (i = 0, j = array.length - 1; i < j; i++, j--) {
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }       
    }
    //
    // Use RSA to encrypt data.
    //
    public static byte[] RsaEncrypt(
        byte[] modulusBytes,
        byte[] exponentBytes,
        byte[] dataBytes
        )
    {
        //
        // Reverse the passed in byte arrays and then use these to
        // create the BigIntegers for the RSA computation.
        //
        ReverseByteArray(modulusBytes);
        ReverseByteArray(exponentBytes);
        ReverseByteArray(dataBytes);
        BigInteger modulus = new BigInteger(
            1,
            modulusBytes
            );
        BigInteger exponent = new BigInteger(
            1,
            exponentBytes
            );
        BigInteger data = new BigInteger(
            1,
            dataBytes
            );
        //
        // Perform RSA encryption:
        // ciphertext = plaintext^exponent % modulus.
        //
        BigInteger cipherText = data.modPow(
            exponent,
            modulus
            );
        //
        // Reverse the generated ciphertext.
        //
        byte[] cipherTextBytes = cipherText.toByteArray();
        ReverseByteArray(cipherTextBytes);
        //
        // Undo the reversal of the passed in byte arrays.
        //
        ReverseByteArray(modulusBytes);
        ReverseByteArray(exponentBytes);
        ReverseByteArray(dataBytes);
        return cipherTextBytes;
    }
  
    //
    // Use RSA to decrypt data.
    //
    public static byte[] RsaDecrypt(
        byte[] modulusBytes,
        byte[] privateExponentBytes,
        byte[] encryptedDataBytes
        )
    {
        //
        // Reverse the passed in byte arrays and then use these to
        // create the BigIntegers for the RSA computation.
        //
        ReverseByteArray(modulusBytes);
        ReverseByteArray(privateExponentBytes);
        ReverseByteArray(encryptedDataBytes);
        BigInteger modulus = new BigInteger(
            1,
            modulusBytes
            );
        BigInteger privateExponent = new BigInteger(
            1,
            privateExponentBytes
            );
        BigInteger encryptedData = new BigInteger(
            1,
            encryptedDataBytes
            );
        //
        // Perform RSA encryption:
        // plaintext = ciphertext^privateExponent % modulus.
        //
        BigInteger decryptedData = encryptedData.modPow(
            privateExponent,
            modulus
            );
        //
        // Reverse the generated plaintext.
        //
        byte[] decryptedDataBytes = decryptedData.toByteArray();
        ReverseByteArray(decryptedDataBytes);
        //
        // Undo the reversal of the passed in byte arrays.
        //
        ReverseByteArray(modulusBytes);
        ReverseByteArray(privateExponentBytes);
        ReverseByteArray(encryptedDataBytes);
        return decryptedDataBytes;
    }
    //
    // Main routine.
    //
    public static void main(
        String[] args
        )
    {
        //
        // Modulus bytes obtained straight from the wire in the
        // proprietary certificate (in little endian format).
        // This is for a 512-bit key set.
        //
        byte[] modulusBytes =
        {       
            (byte) 0x37, (byte) 0xa8, (byte) 0x70, (byte) 0xfe,
            (byte) 0x9a, (byte) 0xb9, (byte) 0xa8, (byte) 0x54,
            (byte) 0xcb, (byte) 0x98, (byte) 0x79, (byte) 0x44,
            (byte) 0x7a, (byte) 0xb9, (byte) 0xeb, (byte) 0x38,
            (byte) 0x06, (byte) 0xea, (byte) 0x26, (byte) 0xa1,
            (byte) 0x47, (byte) 0xea, (byte) 0x19, (byte) 0x70,
            (byte) 0x5d, (byte) 0xf3, (byte) 0x52, (byte) 0x88,
            (byte) 0x70, (byte) 0x21, (byte) 0xb5, (byte) 0x9e,
            (byte) 0x50, (byte) 0xb4, (byte) 0xe1, (byte) 0xf5,
            (byte) 0x1a, (byte) 0xd8, (byte) 0x2d, (byte) 0x51,
            (byte) 0x4d, (byte) 0x1a, (byte) 0xad, (byte) 0x79,
            (byte) 0x7c, (byte) 0x89, (byte) 0x46, (byte) 0xb0,
            (byte) 0xcc, (byte) 0x66, (byte) 0x74, (byte) 0x02,
            (byte) 0xd8, (byte) 0x28, (byte) 0x5d, (byte) 0x9d,
            (byte) 0xd7, (byte) 0xca, (byte) 0xfc, (byte) 0x60,
            (byte) 0x0f, (byte) 0x38, (byte) 0xf9, (byte) 0xb3
        };
        //
        // Exponent bytes (in little endian order) obtained straight
        // from the wire (in the proprietary certificate).
        //
        byte[] exponentBytes =
        {       
            (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x00
        };
        //
        // Private exponent of the private key generated by the
        // server (in little endian format).
        //
        byte[] privateExponentBytes =
        {
            (byte) 0xc1, (byte) 0x07, (byte) 0xe7, (byte) 0xd4,
            (byte) 0xd3, (byte) 0x38, (byte) 0x8d, (byte) 0x36,
            (byte) 0xf5, (byte) 0x9e, (byte) 0x8b, (byte) 0x96,
            (byte) 0x0d, (byte) 0x55, (byte) 0x65, (byte) 0x08,
            (byte) 0x28, (byte) 0x25, (byte) 0xa3, (byte) 0x2e,
            (byte) 0xc7, (byte) 0x68, (byte) 0xd6, (byte) 0x44,
            (byte) 0x85, (byte) 0x2d, (byte) 0x32, (byte) 0xf6,
            (byte) 0x72, (byte) 0xa8, (byte) 0x9b, (byte) 0xba,
            (byte) 0x5e, (byte) 0x82, (byte) 0x82, (byte) 0xf0,
            (byte) 0x5c, (byte) 0x0c, (byte) 0xeb, (byte) 0x6b,
            (byte) 0x12, (byte) 0x6a, (byte) 0xa7, (byte) 0x45,
            (byte) 0x15, (byte) 0xce, (byte) 0x41, (byte) 0xe0,
            (byte) 0x03, (byte) 0xe5, (byte) 0xe6, (byte) 0x6d,
            (byte) 0xdf, (byte) 0xfd, (byte) 0x58, (byte) 0x61,
            (byte) 0x0b, (byte) 0x07, (byte) 0xa4, (byte) 0x7b,
            (byte) 0xb3, (byte) 0xf3, (byte) 0x71, (byte) 0x94
        };
        //
        // Sample 32-byte client random.
        //
        byte[] clientRandomBytes =
        {
            (byte) 0xff, (byte) 0xee, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff
        };
        System.out.println("Client random:");
        PrintBytes(clientRandomBytes);
        //
        // Perform encryption.
        //
        byte[] encryptedClientRandomBytes = RsaEncrypt(
            modulusBytes,
            exponentBytes,
            clientRandomBytes
            );       
        System.out.println("Encrypted client random:");
        PrintBytes(encryptedClientRandomBytes);
        //
        // Perform decryption.
        //
        byte[] decryptedClientRandomBytes = RsaDecrypt(
            modulusBytes,
            privateExponentBytes,
            encryptedClientRandomBytes
            );       
        System.out.println("Decrypted client random:");
        PrintBytes(decryptedClientRandomBytes);
    }
};

Keywords:

Filed Under:

Encryption example using RSA x.509

Generate Public\Private Key: http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml 

Encrypt files: http://www-users.york.ac.uk/~mal503/lore/pkencryption.htm

 

With the increase awareness to security the demand for securing data is rising. Fortunately Java provides pretty good tools that can help developers encrypt and decrypt data.

One of the most popular encryption is called RSA encryption. Named after its inventors, Ron Rivest, Adi Shamir and Leonard Adleman, RSA encryption transforms the number “char” into the number “cipher” with the formula

cipher = char^e (mod n)

The numbers e and n are the two numbers you create and publish. They are your “public key.” The number char can be simply the digital value of a block of ASCII characters. The formula says: multiply the number char by itself e times, then divide the result by the number n and save only the remainder. The remainder that we have called cipher is the encrypted representation of char.

Using the two numbers you have published, anyone can scramble a message and send it to you. You are the only one who can unscramble it; not even the sender of the message can decrypt the ciphertext.

Standard Java 2 distribution includes security provider support for generation of RSA digital signatures, but does NOT contain a provider implementation for generating RSA encrypted data. An extra provider must be added to obtain this capability from standard Java 2, such as the Bouncy Castle Provider.

Since I couldn’t find any good examples that use Java with RSA, we’ll build a nice RSAEncryptUtil class that you can use as a reference for using RSA encryption (you can download the full source code here).

The first thing we need to do is to define the algorithm that we want to use.


protected static final String ALGORITHM = "RSA";

Then as stated before we’ll need to add Bouncy Castle as our RSA provider. In order to do that we’ll write an Init method for our class

/**
* Init java security to add BouncyCastle as an RSA provider
*/
public static void init()
{
Security.addProvider(new BouncyCastleProvider());
}

To generate what is called private and public keys, Java provides us with a simple to use KeyPairGenerator class. The java.security.KeyPairGenerator generates the two keys that are returned in a java.security.KeyPair object.


/**
* Generate key which contains a pair of privae and public key using 1024 bytes
* @return key pair
* @throws NoSuchAlgorithmException
*/
public static KeyPair generateKey() throws NoSuchAlgorithmException
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
return key;
}

 


Now that we have the two keys we can encrypt and decrypt information. In order to do that we are going to use javax.crypto.Cipher. This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.

In order to create a Cipher object, the application calls the Cipher’s getInstance method, and passes the name of the requested transformation to it. Optionally, the name of a provider may be specified.
A transformation is a string that describes the operation (or set of operations) to be performed on the given input, to produce some output. A transformation always includes the name of a cryptographic algorithm, and may be followed by a feedback mode and padding scheme. A transformation is of the form:”algorithm/mode/padding” or “algorithm”
In our example we’ll encrypt a message using our public key.


/**
* Encrypt a text using public key.
* @param text The original unencrypted text
* @param key The public key
* @return Encrypted text
* @throws java.lang.Exception
*/
public static byte[] encrypt(byte[] text, PublicKey key) throws Exception
{
byte[] cipherText = null;
// get an RSA cipher object and print the provider
Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);
System.out.println(”nProvider is: ” + cipher.getProvider().getInfo());
// encrypt the plaintext using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text);
return cipherText;
}

The opposite method is to decrypt a message that was encrypted using a public key. Remember the only one who can decrypt an encrypted message is the one with the private key.


/**
* Decrypt text using private key
* @param text The encrypted text
* @param key The private key
* @return The unencrypted text
* @throws java.lang.Exception
*/
public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception
{
byte[] dectyptedText = null;
// decrypt the text using the private key
Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
return dectyptedText;
}


So far we’ve created public and private keys, encrypted and decrypted messaged. But in order for this utility to be useful we need to be able to send and receive keys and messages. In many implementations you’ll need to do those actions without using bytes, but using strings. The first notion is just convert the byte array to a string object. But this will not work. In order to do that you’ll need to convert the bytes array to a Base64 string representation. Luckily for us this is a very easy task. The following methods will convert bytes to Base64 string and back.


/**
* Encode bytes array to BASE64 string
* @param bytes
* @return Encoded string
*/
private static String encodeBASE64(byte[] bytes)
{
BASE64Encoder b64 = new BASE64Encoder();
return b64.encode(bytes);
}
/**
* Decode BASE64 encoded string to bytes array
* @param text The string
* @return Bytes array
* @throws IOException
*/
private static byte[] decodeBASE64(String text) throws IOException
{
BASE64Decoder b64 = new BASE64Decoder();
return b64.decodeBuffer(text);
}


Now that we have the strings we can do anything we want with them: Save the key in a database, send the public key thru email, web page or any other method, send and receive encrypted messages and anything else you can think of.

One more useful task you would like to do is to be able to handle files. The problem with files (and large strings) is that RSA encryption data size limitations are slightly less than the key modulus size, depending on the actual padding scheme used (e.g. with 1024 bit (128 byte) RSA key, the size limit is 117 bytes for PKCS#1 v 1.5 padding. Hence in order to handle files we need to read and write the files in small blocks. In our example well use blocks of 100 bytes.


/**
* Encrypt and Decrypt files using 1024 RSA encryption
*
* @param srcFileName Source file name
* @param destFileName Destination file name
* @param key The key. For encryption this is the Private Key and for decryption this is the public key
* @param cipherMode Cipher Mode
* @throws Exception
*/
public static void encryptDecryptFile(String srcFileName, String destFileName, Key key, int cipherMode) throws Exception
{
OutputStream outputWriter = null;
InputStream inputReader = null;
try
{
Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);
String textLine = null;
byte[] buf = cipherMode == Cipher.ENCRYPT_MODE? new byte[100] : new byte[128];
int bufl;
// init the Cipher object for Encryption…
cipher.init(cipherMode, key);
// start FileIO
outputWriter = new FileOutputStream(destFileName);
inputReader = new FileInputStream(srcFileName);
while ( (bufl = inputReader.read(buf)) != -1)
{
byte[] encText = null;
if (cipherMode == Cipher.ENCRYPT_MODE)
{
encText = encrypt(copyBytes(buf,bufl),(PublicKey)key);
}
else
{
encText = decrypt(copyBytes(buf,bufl),(PrivateKey)key);
}
outputWriter.write(encText);
}
outputWriter.flush();
}
finally
{
try
{
if (outputWriter != null)
{
outputWriter.close();
}
if (inputReader != null)
{
inputReader.close();
}
}
catch (Exception e)
{
// do nothing…
}
}
}
public static byte[] copyBytes(byte[] arr, int length)
{
  byte[] newArr = null;
  if (arr.length == length)
  {
    newArr = arr;
  }
  else
  {
    newArr = new byte[length];
    for (int i = 0; i < length; i++)
    {
      newArr[i] = (byte) arr[i];
    }
  }
  return newArr;
}


I hope this article will help you make your first steps in to the encryption world. You can download RSAEncryptUtil.zip (2.51 kb), which includes some other convenient methods for you to work with.

Keywords:

Filed Under: Java

Basic symmetric encryption example

http://www.java2s.com/Code/Java/Security/Basicsymmetricencryptionexample.htm 

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Basic symmetric encryption example
 */
public class MainClass {
  public static void main(String[] argsthrows Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());        
    byte[] input = " www.java2s.com ".getBytes();
    byte[] keyBytes = new byte[] { 0x000x010x020x030x040x050x060x070x080x09,
        0x0a0x0b0x0c0x0d0x0e0x0f0x100x110x120x130x140x150x160x17 };

    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding""BC");
    System.out.println("input text : " new String(input));

    // encryption pass

    byte[] cipherText = new byte[input.length];
    cipher.init(Cipher.ENCRYPT_MODE, key);
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);
    System.out.println("cipher text: " new String(cipherText" bytes: " + ctLength);

    // decryption pass

    byte[] plainText = new byte[ctLength];
    cipher.init(Cipher.DECRYPT_MODE, key);
    int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);
    System.out.println("plain text : " new String(plainText" bytes: " + ptLength);
  }
}

Oreilly also has examples: http://oreilly.com/catalog/javacrypt/chapter/ch06.html

Another good site with SALT: http://www.javafaq.nu/java-example-code-191.html

// -----------------------------------------------------------------------------
// StringEncrypter.java
// -----------------------------------------------------------------------------

/*
 * =============================================================================
 * Copyright (c) 1998-2005 Jeffrey M. Hunter. All rights reserved.
 *
 * All source code and material located at the Internet address of
 * http://www.idevelopment.info is the copyright of Jeffrey M. Hunter, 2005 and
 * is protected under copyright laws of the United States. This source code may
 * not be hosted on any other site without my express, prior, written
 * permission. Application to host any of the material elsewhere can be made by
 * contacting me at jhunter@idevelopment.info.
 *
 * I have made every effort and taken great care in making sure that the source
 * code and other content included on my web site is technically accurate, but I
 * disclaim any and all responsibility for any loss, damage or destruction of
 * data or any other property which may arise from relying on it. I will in no
 * case be liable for any monetary damages arising from such loss, damage or
 * destruction.
 *
 * As with any code, ensure to test this code in a development environment
 * before attempting to run it in production.
 * =============================================================================
 */
 
// CIPHER / GENERATORS
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.KeyGenerator;

// KEY SPECIFICATIONS
import java.security.spec.KeySpec;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;

// EXCEPTIONS
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import java.io.UnsupportedEncodingException;
import java.io.IOException;


/**
 * -----------------------------------------------------------------------------
 * The following example implements a class for encrypting and decrypting
 * strings using several Cipher algorithms. The class is created with a key and
 * can be used repeatedly to encrypt and decrypt strings using that key.
 * Some of the more popular algorithms are:
 *      Blowfish
 *      DES
 *      DESede
 *      PBEWithMD5AndDES
 *      PBEWithMD5AndTripleDES
 *      TripleDES
 *
 * @version 1.0
 * @author  Jeffrey M. Hunter  (jhunter@idevelopment.info)
 * @author  http://www.idevelopment.info
 * -----------------------------------------------------------------------------
 */

public class StringEncrypter {

    Cipher ecipher;
    Cipher dcipher;


    /**
     * Constructor used to create this object.  Responsible for setting
     * and initializing this object's encrypter and decrypter Chipher instances
     * given a Secret Key and algorithm.
     * @param key        Secret Key used to initialize both the encrypter and
     *                   decrypter instances.
     * @param algorithm  Which algorithm to use for creating the encrypter and
     *                   decrypter instances.
     */
    StringEncrypter(SecretKey key, String algorithm) {
        try {
            ecipher = Cipher.getInstance(algorithm);
            dcipher = Cipher.getInstance(algorithm);
            ecipher.init(Cipher.ENCRYPT_MODE, key);
            dcipher.init(Cipher.DECRYPT_MODE, key);
        } catch (NoSuchPaddingException e) {
            System.out.println("EXCEPTION: NoSuchPaddingException");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("EXCEPTION: NoSuchAlgorithmException");
        } catch (InvalidKeyException e) {
            System.out.println("EXCEPTION: InvalidKeyException");
        }
    }


    /**
     * Constructor used to create this object.  Responsible for setting
     * and initializing this object's encrypter and decrypter Chipher instances
     * given a Pass Phrase and algorithm.
     * @param passPhrase Pass Phrase used to initialize both the encrypter and
     *                   decrypter instances.
     */
    StringEncrypter(String passPhrase) {

        // 8-bytes Salt
        byte[] salt = {
            (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
            (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
        };

        // Iteration count
        int iterationCount = 19;

        try {

            KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
            SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

            ecipher = Cipher.getInstance(key.getAlgorithm());
            dcipher = Cipher.getInstance(key.getAlgorithm());

            // Prepare the parameters to the cipthers
            AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

            ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
            dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

        } catch (InvalidAlgorithmParameterException e) {
            System.out.println("EXCEPTION: InvalidAlgorithmParameterException");
        } catch (InvalidKeySpecException e) {
            System.out.println("EXCEPTION: InvalidKeySpecException");
        } catch (NoSuchPaddingException e) {
            System.out.println("EXCEPTION: NoSuchPaddingException");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("EXCEPTION: NoSuchAlgorithmException");
        } catch (InvalidKeyException e) {
            System.out.println("EXCEPTION: InvalidKeyException");
        }
    }


    /**
     * Takes a single String as an argument and returns an Encrypted version
     * of that String.
     * @param str String to be encrypted
     * @return <code>String</code> Encrypted version of the provided String
     */
    public String encrypt(String str) {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);

        } catch (BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (IOException e) {
        }
        return null;
    }


    /**
     * Takes a encrypted String as an argument, decrypts and returns the
     * decrypted String.
     * @param str Encrypted String to be decrypted
     * @return <code>String</code> Decrypted version of the provided String
     */
    public String decrypt(String str) {

        try {

            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");

        } catch (BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (IOException e) {
        }
        return null;
    }


    /**
     * The following method is used for testing the String Encrypter class.
     * This method is responsible for encrypting and decrypting a sample
     * String using several symmetric temporary Secret Keys.
     */
    public static void testUsingSecretKey() {
        try {

            System.out.println();
            System.out.println("+----------------------------------------+");
            System.out.println("|  -- Test Using Secret Key Method --    |");
            System.out.println("+----------------------------------------+");
            System.out.println();

            String secretString = "Attack at dawn!";

            // Generate a temporary key for this example. In practice, you would
            // save this key somewhere. Keep in mind that you can also use a
            // Pass Phrase.
            SecretKey desKey       = KeyGenerator.getInstance("DES").generateKey();
            SecretKey blowfishKey  = KeyGenerator.getInstance("Blowfish").generateKey();
            SecretKey desedeKey    = KeyGenerator.getInstance("DESede").generateKey();

            // Create encrypter/decrypter class
            StringEncrypter desEncrypter = new StringEncrypter(desKey, desKey.getAlgorithm());
            StringEncrypter blowfishEncrypter = new StringEncrypter(blowfishKey, blowfishKey.getAlgorithm());
            StringEncrypter desedeEncrypter = new StringEncrypter(desedeKey, desedeKey.getAlgorithm());

            // Encrypt the string
            String desEncrypted       = desEncrypter.encrypt(secretString);
            String blowfishEncrypted  = blowfishEncrypter.encrypt(secretString);
            String desedeEncrypted    = desedeEncrypter.encrypt(secretString);

            // Decrypt the string
            String desDecrypted       = desEncrypter.decrypt(desEncrypted);
            String blowfishDecrypted  = blowfishEncrypter.decrypt(blowfishEncrypted);
            String desedeDecrypted    = desedeEncrypter.decrypt(desedeEncrypted);

            // Print out values
            System.out.println(desKey.getAlgorithm() + " Encryption algorithm");
            System.out.println("    Original String  : " + secretString);
            System.out.println("    Encrypted String : " + desEncrypted);
            System.out.println("    Decrypted String : " + desDecrypted);
            System.out.println();

            System.out.println(blowfishKey.getAlgorithm() + " Encryption algorithm");
            System.out.println("    Original String  : " + secretString);
            System.out.println("    Encrypted String : " + blowfishEncrypted);
            System.out.println("    Decrypted String : " + blowfishDecrypted);
            System.out.println();

            System.out.println(desedeKey.getAlgorithm() + " Encryption algorithm");
            System.out.println("    Original String  : " + secretString);
            System.out.println("    Encrypted String : " + desedeEncrypted);
            System.out.println("    Decrypted String : " + desedeDecrypted);
            System.out.println();

        } catch (NoSuchAlgorithmException e) {
        }
    }


    /**
     * The following method is used for testing the String Encrypter class.
     * This method is responsible for encrypting and decrypting a sample
     * String using using a Pass Phrase.
     */
    public static void testUsingPassPhrase() {

        System.out.println();
        System.out.println("+----------------------------------------+");
        System.out.println("|  -- Test Using Pass Phrase Method --   |");
        System.out.println("+----------------------------------------+");
        System.out.println();

        String secretString = "Attack at dawn!";
        String passPhrase   = "My Pass Phrase";

        // Create encrypter/decrypter class
        StringEncrypter desEncrypter = new StringEncrypter(passPhrase);

        // Encrypt the string
        String desEncrypted       = desEncrypter.encrypt(secretString);

        // Decrypt the string
        String desDecrypted       = desEncrypter.decrypt(desEncrypted);

        // Print out values
        System.out.println("PBEWithMD5AndDES Encryption algorithm");
        System.out.println("    Original String  : " + secretString);
        System.out.println("    Encrypted String : " + desEncrypted);
        System.out.println("    Decrypted String : " + desDecrypted);
        System.out.println();

    }


    /**
     * Sole entry point to the class and application used for testing the
     * String Encrypter class.
     * @param args Array of String arguments.
     */
    public static void main(String[] args) {
        testUsingSecretKey();
        testUsingPassPhrase();
    }

}


Keywords:

Filed Under: Java

TextBox widget example - adding any formatted HTML code to the widget.

Comment List

  • None

Month List