DES encryption and decryption in Java

  • 2020-04-01 03:45:35
  • OfStack

Without further ado, here is the code:

A code


package com.eabax.plugin.yundada.utils;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
public class DESEncryptHelper {
  private final static String DES = "DES";
  
  public static String getDESKey(String encryptStr){
    if (!CacheManager.getCache().containsKey("encryptKey_"+encryptStr)) {
      CacheManager.getCache().put("encryptKey_"+encryptStr, encryptStr+"tablemiyaokey");
    }
    String key = (String) CacheManager.getCache().get("encryptKey_"+encryptStr);
    return key;
  }
   
  public static String decrypt(String data, String key) throws IOException,
      Exception {
    if (data == null)
      return null;
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] buf = decoder.decodeBuffer(data);
    byte[] bt = decrypt(buf,key.getBytes());
    return new String(bt);
  }
  
  public static String getEncryptStr(String str,String encryptStr) throws InvalidKeyException,
      IllegalBlockSizeException, BadPaddingException,
      InvalidKeySpecException, NoSuchAlgorithmException,
      NoSuchPaddingException {
    //To get the key
    String key = getDESKey(encryptStr);
    //To get the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
    DESKeySpec keyspec = new DESKeySpec(key.getBytes());
    SecretKey deskey = factory.generateSecret(keyspec);
    //The Cipher performs encryption or decryption
    Cipher c = Cipher.getInstance("DES");
    //The Cipher object is initialized based on the key, and DECRYPT_MODE represents the encryption mode
    c.init(Cipher.ENCRYPT_MODE, deskey);
    byte[] src = str.getBytes();
    //This byte array is responsible for holding the encrypted results
    byte[] cipherByte = c.doFinal(src);
    String enstr = new String(Base64.encodeBase64(cipherByte));
    return enstr;
  }
   
  private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
    //Generate a trusted random number source
    SecureRandom sr = new SecureRandom();
    //Create the DESKeySpec object from the original key data
    DESKeySpec dks = new DESKeySpec(key);
    //Create a key factory and use it to transform the DESKeySpec into a SecretKey object
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    //A Cipher object actually does the decryption
    Cipher cipher = Cipher.getInstance(DES);
    //Initializes a Cipher object with a key
    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
    return cipher.doFinal(data);
  }
}

Code 2


package com.sinosoft.olyvem.common;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Encoder;

public class DES ...{
  private byte[] desKey;

  public DES(byte[] desKey) ...{
    this.desKey = desKey;
  }

  public byte[] doEncrypt(byte[] plainText) throws Exception ...{
    //The DES algorithm requires a trusted random number source
    SecureRandom sr = new SecureRandom();
    byte rawKeyData[] = desKey;/**/
    //Create a DESKeySpec object from the raw key data
    DESKeySpec dks = new DESKeySpec(rawKeyData);
    //Create a key factory and use it to convert the DESKeySpec to
    //A SecretKey object
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key = keyFactory.generateSecret(dks);
    //A Cipher object actually does the encryption
    Cipher cipher = Cipher.getInstance("DES");
    //Initializes a Cipher object with a key
    cipher.init(Cipher.ENCRYPT_MODE, key, sr);
    //Now, get the data and encrypt it
    byte data[] = plainText;/**/
    //Formally perform the encryption operation
    byte encryptedData[] = cipher.doFinal(data);
    return encryptedData;
  }

  public byte[] doDecrypt(byte[] encryptText) throws Exception ...{
    //The DES algorithm requires a trusted random number source
    SecureRandom sr = new SecureRandom();
    byte rawKeyData[] = desKey; /**/
    //Create a DESKeySpec object from the raw key data
    DESKeySpec dks = new DESKeySpec(rawKeyData);
    //Create a key factory and use it to convert the DESKeySpec object to
    //A SecretKey object
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key = keyFactory.generateSecret(dks);
    //A Cipher object actually does the decryption
    Cipher cipher = Cipher.getInstance("DES");
    //Initializes a Cipher object with a key
    cipher.init(Cipher.DECRYPT_MODE, key, sr);
    //Now, get the data and decrypt it
    byte encryptedData[] = encryptText;/**/
    //Execute the decryption operation formally
    byte decryptedData[] = cipher.doFinal(encryptedData);
    return decryptedData;
  }

  public static void main(String[] args) throws Exception ...{
    String key = "FtpXPass";
    String value = "olympic";
    BASE64Encoder base64Encoder = new BASE64Encoder();

    DES desEncrypt = new DES(key.getBytes());
    byte[] encryptText = desEncrypt.doEncrypt(value.getBytes());
    //System.out.println("doEncrypt  -  " + toHexString(encryptText));
    System.out.println("doEncrypt  -  "
        + base64Encoder.encode(encryptText));
    byte[] decryptText = desEncrypt.doDecrypt("r9NGYcKAtdo=".getBytes());
    System.out.println("doDecrypt  -  " + new String(decryptText));
    //System.out.println("doDecrypt  -  " + toHexString(decryptText));

  }

  public static String toHexString(byte[] value) ...{
    String newString = "";
    for (int i = 0; i < value.length; i++) ...{
      byte b = value[i];
      String str = Integer.toHexString(b);
      if (str.length() > 2) ...{
        str = str.substring(str.length() - 2);
      }
      if (str.length() < 2) ...{
        str = "0" + str;
      }
      newString += str;
    }
    return newString.toUpperCase();
  }

}

Above is the code on DES encryption and decryption, I hope to help you learn Java.


Related articles: