security
DES with ECB example
In this example we shall show you how to encrypt data using the DES algorithm in ECB mode. To encrypt a String message with the Data Encryption algorithm in Electronic Code Book mode one should perform the following steps:
- Create a byte array from the initial String message, and a byte array to be used as a key.
- Create a new SecretKeySpec from the given key, using the DES algorithm.
- Create a new Cipher for the DES/ECB/PKCS7Padding transformation, using the
org.bouncycastle.jce.provider.BouncyCastleProvider()
and initialize it in encryption mode, using the SecretKeySpec. - Encrypt the initial byte array, using 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 again, in decryption mode, using the SecretKeySpec.
- Decrypt the encrypted byte array, using the
update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
anddoFinal(byte[] output, int outputOffset)
API methods of the Cipher.
Note that in both cases the byte array of the result is initialized using the getOutputSize(int inputLen)
API method of the Cipher that returns the length in bytes of the next update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
or doFinal(byte[] output, int outputOffset)
operation result.
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.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}; SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC"); System.out.println("input : " + new String(input)); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; int ctLength = cipher.update(input, 0, input.length, cipherText, 0); ctLength += cipher.doFinal(cipherText, ctLength); System.out.println("cipher: " + new String(cipherText).getBytes("UTF-8").toString() + " bytes: " + ctLength); cipher.init(Cipher.DECRYPT_MODE, key); byte[] plainText = new byte[cipher.getOutputSize(ctLength)]; int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0); ptLength += cipher.doFinal(plainText, ptLength); System.out.println("plain : " + new String(plainText) + " bytes: " + ptLength); } }
Output:
input : www.javacodegeeks.com
cipher: [B@277c3833 bytes: 24
plain : www.javacodegeeks.com
This was an example of how to encrypt data using the DES algorithm in ECB mode in Java.