Skip to content

Instantly share code, notes, and snippets.

@tdpauw
Created November 13, 2014 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdpauw/be447e2293c4f060ce34 to your computer and use it in GitHub Desktop.
Save tdpauw/be447e2293c4f060ce34 to your computer and use it in GitHub Desktop.
Cryptography examples in Java for Password Based Encryption, Blowfish and Key Store
import java.security.*;
import javax.crypto.*;
/**
* BlowfishExample.java
*
* This class creates a Blowfish key, encrypts some text,
* prints the ciphertext, then decrypts the text and
* prints that.
*
* It requires a JCE-compliant Blowfish engine, like Cryptix' JCE.
*/
public class BlowfishExample
{
public static void main (String[] args)
throws Exception
{
if (args.length != 1) {
System.err.println("Usage: java BlowfishExample text");
System.exit(1);
}
String text = args[0];
System.out.println("Generating a Blowfish key...");
// Create a Blowfish key
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128); // need to initialize with the keysize
Key key = keyGenerator.generateKey();
System.out.println("Done generating the key.");
// Create a cipher using that key to initialize it
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plaintext = text.getBytes("UTF8");
// Print out the bytes of the plaintext
System.out.println("\nPlaintext: ");
for (int i=0;i<plaintext.length;i++) {
System.out.print(plaintext[i]+" ");
}
// Perform the actual encryption
byte[] ciphertext = cipher.doFinal(plaintext);
// Print out the ciphertext
System.out.println("\n\nCiphertext: ");
for (int i=0;i<ciphertext.length;i++) {
System.out.print(ciphertext[i]+" ");
}
// Re-initialize the cipher to decrypt mode
cipher.init(Cipher.DECRYPT_MODE, key);
// Perform the decryption
byte[] decryptedText = cipher.doFinal(ciphertext);
String output = new String(decryptedText,"UTF8");
System.out.println("\n\nDecrypted text: "+output);
}
}
import java.security.*;
import javax.crypto.*;
import java.io.*;
// Import a package for BASE64 encoding.
// If sun.misc doesn't work for you, replace it with
// the line following
import sun.misc.*;
// import com.isnetworks.base64.*;
/**
* KeyStoreExample.java
*
* Encrypts or decrypts a string from STDIN using a
* 128-bit Blowfish key. That key is stored to the
* standard KeyStore in the filesystem.
*/
public class KeyStoreExample
{
private static String FILENAME = "keystore.ks";
public static void main(String[] args)
throws Exception
{
if (args.length != 3)
{
System.err.println("Usage: java KeyStoreExample -e|-d password text");
System.exit(1);
}
// Convert the password into a char array
char[] password = new char[args[1].length()];
args[1].getChars(0, args[1].length(), password, 0);
String text = args[2];
// Check if the user wants to encrypt or decrypt
if (args[0].equals("-e")) encrypt(password, text);
else decrypt(password, text);
}
/**
* Encrypts the plaintext passed in and outputs
* the ciphertext to STDOUT. Also stores the secret key
* to the filesystem inside a KeyStore.
*/
private static void encrypt(char[] password, String plaintext)
throws Exception
{
System.out.println("Generating a TripleDES key...");
// Create a Blowfish key
KeyGenerator keyGenerator = KeyGenerator.getInstance("TripleDES");
keyGenerator.init(168);
Key key = keyGenerator.generateKey();
System.out.println("Done generating the key.");
// Create a cipher using that key to initialize it
Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plaintextBytes = plaintext.getBytes();
// Perform the actual encryption
byte[] cipherText = cipher.doFinal(plaintextBytes);
// Now we need to Base64-encode it for ascii display
BASE64Encoder encoder = new BASE64Encoder();
String output = encoder.encode(cipherText);
System.out.println("Ciphertext: "+output);
/* Create a keystore and place the key in it
* We're using a jceks keystore, which is provided by Sun's JCE.
* If you don't have the JCE installed, you can use "JKS",
* which is the default keystore. It doesn't provide
* the same level of protection however.
*/
KeyStore keyStore = KeyStore.getInstance("JKS");
// This initializes a blank keystore
keyStore.load(null, null);
// Now we add the key to the keystore, protected
// by the password.
keyStore.setKeyEntry("exampleKey", key, password, null);
// Store the password to the filesystem, protected
// by the same password.
FileOutputStream fos = new FileOutputStream(FILENAME);
keyStore.store(fos, password);
fos.close();
}
/**
* Decrypts the ciphertext passes in and prints the plaintext
* to STDOUT. Pulls a key from a KeyStore in the filesystem,
* using the password given.
*/
private static void decrypt(char[] password, String ciphertext)
throws Exception
{
// Create a keystore and load it from the filesystem,
// using the password given.
KeyStore keyStore = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream(FILENAME);
keyStore.load(fis, password);
fis.close();
Key key = (Key)keyStore.getKey("exampleKey",password);
// Create a cipher using that key to initialize it
Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
// Perform the decryption, first BASE64 decoding the ciphertext
byte[] ciphertextBytes = new BASE64Decoder().decodeBuffer(ciphertext);
byte[] decryptedText = cipher.doFinal(ciphertextBytes);
String output = new String(decryptedText);
System.out.println("Plaintext: "+output);
}
}
/**
* PBE.java
*
* This is a Password-Based Encryption example.
*
* This example uses SHA-1 and Twofish to encrypt or decrypt some text
* using a password. The iteration count is set to 1000 and the
* salt is randomly chosen on encryption. The salt is then written to the
* first 8 bytes of the output text.
*
* When decrypting, this program will read the first 8 bytes of the
* ciphertext and use that as the salt.
*
* It requires a JCE-compliant PBEWithSHAAndTwofish-CBC engine, like the
* Bouncy Castle Provider (http://www.bouncycastle.org).
*/
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
// This is for BASE64 encoding and decoding
import sun.misc.*;
// import com.isnetworks.base64.*;
public class PBE
{
private static int ITERATIONS = 1000;
private static void usage()
{
System.err.println("Usage: java PBE -e|-d password text");
System.exit(1);
}
public static void main (String[] args)
throws Exception
{
if (args.length != 3) usage();
char[] password = args[1].toCharArray();
String text = args[2];
String output = null;
// Check the first argument: are we encrypting or decrypting?
if ("-e".equals(args[0])) output = encrypt(password, text);
else if ("-d".equals(args[0])) output = decrypt(password, text);
else usage();
System.out.println(output);
}
private static String encrypt(char[] password, String plaintext)
throws Exception
{
// Begin by creating a random salt of 64 bits (8 bytes)
byte[] salt = new byte[8];
Random random = new Random();
random.nextBytes(salt);
// Create the PBEKeySpec with the given password
PBEKeySpec keySpec = new PBEKeySpec(password);
// Get a SecretKeyFactory for PBEWithMD5AndDES
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHAAndTwofish-CBC");
// Create our key
SecretKey key = keyFactory.generateSecret(keySpec);
// Now create a parameter spec for our salt and iterations
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);
// Create a cipher and initialize it for encrypting
Cipher cipher = Cipher.getInstance("PBEWithSHAAndTwofish-CBC");
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes());
BASE64Encoder encoder = new BASE64Encoder();
String saltString = encoder.encode(salt);
String ciphertextString = encoder.encode(ciphertext);
return saltString+ciphertextString;
}
private static String decrypt(char[] password, String text)
throws Exception
{
// Begin by splitting the text into salt and text Strings
// salt is first 12 chars, BASE64 encoded from 8 bytes.
String salt = text.substring(0,12);
String ciphertext = text.substring(12,text.length());
// BASE64Decode the bytes for the salt and the ciphertext
BASE64Decoder decoder = new BASE64Decoder();
byte[] saltArray = decoder.decodeBuffer(salt);
byte[] ciphertextArray = decoder.decodeBuffer(ciphertext);
// Create the PBEKeySpec with the given password
PBEKeySpec keySpec = new PBEKeySpec(password);
// Get a SecretKeyFactory for PBEWithMD5AndDES
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHAAndTwofish-CBC");
// Create our key
SecretKey key = keyFactory.generateSecret(keySpec);
// Now create a parameter spec for our salt and iterations
PBEParameterSpec paramSpec = new PBEParameterSpec(saltArray, ITERATIONS);
// Create a cipher and initialize it for encrypting
Cipher cipher = Cipher.getInstance("PBEWithSHAAndTwofish-CBC");
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
// Perform the actual decryption
byte[] plaintextArray = cipher.doFinal(ciphertextArray);
return new String(plaintextArray);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment