security
DES with CBC example
With this example we are going to demonstrate how to encrypt data using the DES algorithm in CBC mode. In short, to encrypt/decrypt a String message with the Data Encryption Standard algorithm, in Chipher Block Chaining mode you should:
- Create a byte array to be used as initial input, a byte array to be used as a key and a byte array to be used as initialization vector.
- Create a new SecretKeySpec, using the key byte array and the DES algorithm.
- Create a new IvParameterSpec, using the initialization vector byte array.
- Create a new Cipher for the “DES/CBC/PKCS7Padding” transformation, using an
org.bouncycastle.jce.provider.BouncyCastleProvider()
. - Initialize the cipher in encryption mode, using the key and iv specs, with the
init(int opmode, Key key, AlgorithmParameterSpec params)
API method. - Do the encryption. Use the
update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
anddoFinal(byte[] output, int outputOffset)
API methods of the Cipher. - Initialize the cipher in decryption mode.
- Do the decryption, using the same steps as in the encryption.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Main { public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] input = "www.javaCODEgeeks.com".getBytes(); byte[] keyBytes = new byte[]{0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}; byte[] ivBytes = new byte[]{0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00}; SecretKeySpec pKey = new SecretKeySpec(keyBytes, "DES"); IvParameterSpec ivectorSpecv = new IvParameterSpec(ivBytes); Cipher c = Cipher.getInstance("DES/CBC/PKCS7Padding", "BC"); System.out.println("input : " + new String(input)); // encryption pass c.init(Cipher.ENCRYPT_MODE, pKey, ivectorSpecv); byte[] encr = new byte; int ctLen = c.update(input, 0, input.length, encr, 0); ctLen += c.doFinal(encr, ctLen); System.out.println("cipher: " + new String(encr).getBytes("UTF-8").toString() + " bytes: " + ctLen); // decryption pass c.init(Cipher.DECRYPT_MODE, pKey, ivectorSpecv); byte[] decrpt = new byte; int ptLen = c.update(encr, 0, ctLen, decrpt, 0); ptLen += c.doFinal(decrpt, ptLen); System.out.println("plain : " + new String(decrpt) + " bytes: " + ptLen); } }
Output:
input : www.javaCODEgeeks.com
cipher: [B@d1dca40 bytes: 24
plain : www.javaCODEgeeks.com
This was an example of how to encrypt data using the DES algorithm in CBC mode in Java.