Monday

Triple DES (3DES) with CBC mode algorithm in java

import java.security.Key;
import java.util.Arrays;

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

import org.apache.commons.codec.binary.Hex;

public static void main(String[] args) {
      String yourOwnKey = "ASDFGHJKLZXCVBNMQWERTYUI", originalText = "Give your text to encrypt.";
        decrypt(encrypt(originalText, yourOwnKey), yourOwnKey);
    }
public static String encrypt(String originalText, String yourOwnKey) {
      String encryptedText = null;
      byte[] bytes = null;
     
      try {
            bytes = originalText.getBytes();
            bytes = Arrays.copyOf(bytes, ((bytes.length + 7) / 8) * 8);
           
            Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            SecretKey key = new SecretKeySpec(yourOwnKey.getBytes(), "DESede");
            IvParameterSpec iv = new IvParameterSpec(new byte[8]);
             
            cipher.init(Cipher.ENCRYPT_MODE, (Key) key, iv);
            byte[] encryptByte = cipher.doFinal(bytes);
            encryptedText = new String(Hex.encodeHex(encryptByte));
           
            System.out.println("originalText: " +originalText+ " --> encryptedText: " + encryptedText);
         
            } catch (Exception e) {
                  //throw || log
            }
      return encryptedText;
    }
public static String decrypt(String encryptedTxt, String yourOwnKey) {
      String decryptedText  = null;
      byte[] bytes = null;
     
      try {
            bytes = Hex.decodeHex(encryptedTxt.toCharArray());
           
            Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            SecretKey key = new SecretKeySpec(yourOwnKey.getBytes(), "DESede");
            IvParameterSpec iv = new IvParameterSpec(new byte[8]);
             
            cipher.init(Cipher.DECRYPT_MODE, (Key) key, iv);
            byte[] decryptByte = cipher.doFinal(bytes);
           
            decryptedText = new String(decryptByte);
            if (decryptedText.indexOf((char) 0) > 0)
                  decryptedText = decryptedText.substring(0, decryptedText.indexOf((char) 0));
           
            System.out.println("encryptedTxt: " +encryptedTxt+ " --> decryptedText: " + decryptedText);
          
            } catch (Exception e) {
                  //throw || log
            }
      return decryptedText;
    }

No comments:

Post a Comment