The encryption and decryption functions of java based on Des symmetric encryption algorithm are explained in detail

  • 2020-05-27 05:36:58
  • OfStack

This paper illustrates the encryption and decryption functions of java based on Des symmetric encryption algorithm. I will share it with you for your reference as follows:

Introduction to Des encryption related classes:

The class SecureRandom is inherited from the class java.util.Random

There are three types of constructors for the class SecureRandom. Here are two:

SecureRandom() constructs a safe random number generator (RNG) that implements the default random number algorithm.

SecureRandom(byte[] seed) constructs a secure random number generator (RNG) that implements the default random number algorithm.

The DESKeySpec class is used to generate the secret key content of the secret key using the original secret key

DESKeySpec has two constructors:

DESKeySpec(byte[] key) creates an DESKeySpec object, using the first eight bytes of key as the key content of the DES key.

DESKeySpec(byte[] key, int offset) creates an DESKeySpec object, using the first eight bytes of key that begin and contain offset as the key content of the DES-EDE key.

SecretKeyFactory, a key factory used to convert a key (an opaque encryption key of type Key) to a key specification (a transparent representation of the underlying key material) and vice versa. Secret key factories operate only on secret (symmetric) keys.

The SecretKey object, the secret key object, generates the secret key by calling the generateSecret (DESKeySpec deskeyspace) method of the secret key factory

The Cipher class provides password functionality for encryption and decryption by calling getInstance("des") of Cipher to get an instance

The Cipher object initializes the object by calling the init () method, and the init() method takes specific parameters, whether encrypted or decrypted, as the case may be

Finally, the doFinal() method of Cipher is called for encryption and decryption.

Consult everybody here a problem, whether use BASE64Encoder coding 1 or 2 kinds of org. apache. commons. codec. binary. Base64 coding, transforming String into byte and conversion of byte String require UTF - 8 / GBK coding to coding, decoding?

1. Use the sun. misc. BASE64Decoder and BASE64Encoder decoding, encoding


package com.soufun.com;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
//  The import sun the 64 A coding 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 *@author WHD
 *
 * Even if the import sun.misc This rack bag will also report errors, then first put your JRE Shelf package removed and imported 1 Just next time 
 */
public class DesUtil {
  //  Define the encryption method 
   private final static String DES = "DES";
   private final static String UTF8="GBK";
   static SecretKeyFactory keyFactory = null;
  static {
    try {
      keyFactory=SecretKeyFactory.getInstance("DES");
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    public static void main(String[] args) throws Exception {
      long begin=new Date().getTime();
      String data = "aaades Encryption test ";
      //  Note: DES In both encryption and decryption, the key length must be 8 A multiple of 
      String key = "qazwsxed";
      System.err.println(encrypt(data, key));
      System.err.println(decrypt(encrypt(data, key), key));
      long end =new Date().getTime();
      System.out.println(end-begin);
    }
    /**
     * Description  Encrypt by key value 
     * @param data
     * @param key  The encryption key byte An array of 
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
      //  Gets the content to be encrypted using the specified encoding, 1 General secret keys are letters or Numbers do not need to specify the encoding, but can be specified 
      byte[] bt = encrypt(data.getBytes(UTF8), key.getBytes(UTF8));
      // Note: used during encryption and decryption sun the BASE64Encoder () encode and decode otherwise there will be garbled code 
      // Looked at a lot of instances on the Internet, there is no coding and decoding, also said there is no garbled code problem, and I appeared here garbled code, so use BASE64Encoder () is encoded and decoded 
      String strs = new BASE64Encoder().encode(bt);
      return strs;
    }
    /**
     * Description  Decrypt by key value 
     * @param data
     * @param key  The encryption key byte An array of 
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws IOException,
        Exception {
      if (data == null)
        return null;
      // Note: used during encryption and decryption sun the BASE64Encoder () encode and decode otherwise there will be garbled code 
      BASE64Decoder decoder = new BASE64Decoder();
      byte[] buf = decoder.decodeBuffer(data);
      byte[] bt = decrypt(buf,key.getBytes());
      return new String(bt,UTF8);
    }
    /**
     * Description  Encrypt by key value 
     * @param data
     * @param key  The encryption key byte An array of 
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
      //  generate 1 A trusted random number source 
      SecureRandom sr = new SecureRandom();
      //  Create from the original key data DESKeySpec Object, which is the secret key content that creates the secret key 
      DESKeySpec dks = new DESKeySpec(key);
      //  The key factory is used to hold the key (type  Key  Convert to the key specification (a transparent representation of the underlying key material) and vice versa. Secret key factories operate only on secret (symmetric) keys. 
      //  Instead, use the singleton pattern 
      //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
      // Generate according to the key specification (key material) provided  SecretKey( The secret key )  Object. 
      SecretKey securekey = keyFactory.generateSecret(dks);
      // Cipher The object actually does the encryption , This class provides password capabilities for encryption and decryption 
      Cipher cipher = Cipher.getInstance(DES);
      //  Initialize this with a key and a random source  Cipher . ENCRYPT_MODE Is used to  Cipher  Initialize to a constant of the encryption mode. 
      cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
      // Formally perform the encryption operation 
      return cipher.doFinal(data);
    }
    /**
     * Description  Decrypt by key value 
     * @param data
     * @param key  The encryption key byte An array of 
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
      //  generate 1 A trusted random number source 
      SecureRandom sr = new SecureRandom();
      //  Create from the original key data DESKeySpec Object, which is the secret key content that creates the secret key 
      DESKeySpec dks = new DESKeySpec(key);
      //  The key factory is used to hold the key (type  Key  Convert to the key specification (a transparent representation of the underlying key material) and vice versa. Secret key factories operate only on secret (symmetric) keys. 
      //  Instead, use the singleton pattern 
      //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
      // Generate according to the key specification (key material) provided  SecretKey( The secret key ) Object. 
      SecretKey securekey = keyFactory.generateSecret(dks);
      // Cipher Class provides password functionality for encryption and decryption 
      Cipher cipher = Cipher.getInstance(DES);
      // DECRYPT_MODE Is used to  Cipher  Initializes to a constant of the decryption pattern. 
      cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
      //  Official decryption operation 
      return cipher.doFinal(data);
    }
}

2. Use org. apache. commons. codec. binary. Base64 decoding and encoding


package com.soufun.com;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
 *@author WHD
 *
 */
public class DesUtil {
  //  Define the encryption method 
   private final static String DES = "DES";
   private final static String UTF8="GBK";
   static SecretKeyFactory keyFactory = null;
  static {
    try {
      keyFactory=SecretKeyFactory.getInstance("DES");
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    public static void main(String[] args) throws Exception {
      long begin=new Date().getTime();
      String data = "aaades Encryption test ";
      //  Note: DES In both encryption and decryption, the key length must be 8 A multiple of 
      String key = "qazwsxed";
      System.err.println(encrypt(data, key));
      System.err.println(decrypt(encrypt(data, key), key));
      long end =new Date().getTime();
      System.out.println(end-begin);
    }
    /**
     * Description  Encrypt by key value 
     * @param data
     * @param key  The encryption key byte An array of 
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
      //  Gets the content to be encrypted using the specified encoding, 1 General secret keys are letters or Numbers do not need to specify the encoding, but can be specified 
      byte[] bt = encrypt(data.getBytes(UTF8), key.getBytes());
      //  The first 1 Using the sun.misc.BASE64Encoder; It was coded but said to be used online org.apache.commons.codec.binary.Base64 It's better so give it a try 
      String strs = Base64.encodeBase64String(bt);
      return strs;
    }
    /**
     * Description  Decrypt by key value 
     * @param data
     * @param key  The encryption key byte An array of 
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws IOException,
        Exception {
      if (data == null)
        return null;
      //  use org.apache.commons.codec.binary.Base64 decoding 
      byte [] buf=Base64.decodeBase64(data);
      byte[] bt = decrypt(buf,key.getBytes());
      return new String(bt,UTF8);
    }
    /**
     * Description  Encrypt by key value 
     * @param data
     * @param key  The encryption key byte An array of 
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
      //  generate 1 A trusted random number source 
      SecureRandom sr = new SecureRandom();
      //  Create from the original key data DESKeySpec Object, which is the secret key content that creates the secret key 
      DESKeySpec dks = new DESKeySpec(key);
      //  The key factory is used to hold the key (type  Key  Convert to the key specification (a transparent representation of the underlying key material) and vice versa. Secret key factories operate only on secret (symmetric) keys. 
      //  Instead, use the singleton pattern 
      //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
      // Generate according to the key specification (key material) provided  SecretKey( The secret key )  Object. 
      SecretKey securekey = keyFactory.generateSecret(dks);
      // Cipher The object actually does the encryption , This class provides password capabilities for encryption and decryption 
      Cipher cipher = Cipher.getInstance(DES);
      //  Initialize this with a key and a random source  Cipher . ENCRYPT_MODE Is used to  Cipher  Initialize to a constant of the encryption mode. 
      cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
      // Formally perform the encryption operation 
      return cipher.doFinal(data);
    }
    /**
     * Description  Decrypt by key value 
     * @param data
     * @param key  The encryption key byte An array of 
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
      //  generate 1 A trusted random number source 
      SecureRandom sr = new SecureRandom();
      //  Create from the original key data DESKeySpec Object, which is the secret key content that creates the secret key 
      DESKeySpec dks = new DESKeySpec(key);
      //  The key factory is used to hold the key (type  Key  Convert to the key specification (a transparent representation of the underlying key material) and vice versa. Secret key factories operate only on secret (symmetric) keys. 
      //  Instead, use the singleton pattern 
      //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
      // Generate according to the key specification (key material) provided  SecretKey( The secret key ) Object. 
      SecretKey securekey = keyFactory.generateSecret(dks);
      // Cipher Class provides password functionality for encryption and decryption 
      Cipher cipher = Cipher.getInstance(DES);
      // DECRYPT_MODE Is used to  Cipher  Initializes to a constant of the decryption pattern. 
      cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
      //  Official decryption operation 
      return cipher.doFinal(data);
    }
}

Download address of shelf package used in 1.2:

Download: sun. misc. BASE64Decoder.
Download: apache Base64 codec.

3. Decoding rack package without any encoding


package com.soufun.com;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
/**
 *@author WHD
 *
 */
public class DESCrypt {
  static SecretKeyFactory secretKeyFactory = null;
  //Cipher  "Algorithm / model / Fill in" 
  static final String CIPHER = "DES/CBC/PKCS5Padding";
  static {
    try {
      //  Gets the secret key project in a static block of code 
      secretKeyFactory = SecretKeyFactory.getInstance("DES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
  }
  //  Define constants   , encoding format 
  private static final String UTF8 = "GBK";
  /*
   *  Object cache container 
   */
  static abstract class Cache {
    private final Map innerCache = new HashMap();
    protected abstract Object createValue(Object key) throws Exception;
    public Object get(Object key) throws Exception {
      Object value;
      synchronized (innerCache) {
        value = innerCache.get(key);
        if (value == null) {
          value = new CreationPlaceholder();
          innerCache.put(key, value);
        }
      }
      if (value instanceof CreationPlaceholder) {
        synchronized (value) {
          CreationPlaceholder progress = (CreationPlaceholder) value;
          if (progress.value == null) {
            progress.value = createValue(key);
            synchronized (innerCache) {
              innerCache.put(key, progress.value);
            }
          }
          return progress.value;
        }
      }
      return value;
    }
    static final class CreationPlaceholder {
      Object value;
    }
  }
  /*
   * hex->str & str->hex
   */
  public static byte[] stringToHex(String ss) {
    //  String conversion we
    byte digest[] = new byte[ss.length() / 2];
    for (int i = 0; i < digest.length; i++) {
      String byteString = ss.substring(2 * i, 2 * i + 2);
      int byteValue = Integer.parseInt(byteString, 16);
      digest[i] = (byte) byteValue;
    }
    return digest;
  }
  public static String hexToString(byte b[]) {
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < b.length; i++) {
      String plainText = Integer.toHexString(0xff & b[i]);
      if (plainText.length() < 2) {
        hexString.append("0");
      }
      hexString.append(plainText);
    }
    return hexString.toString();
  }
  private static byte[] _convertKeyIv(String text) throws IOException {
    if (text.length() == 8) {
      return text.getBytes(UTF8);
    }
    if (text.startsWith("0x") && text.length() == 32) {
      byte[] result = new byte[8];
      for (int i = 0; i < text.length(); i += 2) {
        if (text.charAt(i++) == '0' && text.charAt(i++) == 'x') {
          try {
            result[i / 4] = (byte) Integer.parseInt(
                text.substring(i, i + 2), 16);
          } catch (Exception e) {
            throw new IOException("TXT '" + text + "' is invalid!");
          }
        }
      }
      return result;
    }
    throw new IOException("TXT '" + text + "' is invalid!");
  }
  /*
   * SecretKey & IvParameterSpec The cache 
   */
  private static Cache SecretKeySpecs = new Cache() {
    protected Object createValue(Object key) throws Exception {
      SecretKey secretKeyObj = null;
      try {
        secretKeyObj = secretKeyFactory.generateSecret(new DESKeySpec(
            _convertKeyIv((String) key)));
      } catch (Exception e) {
        e.printStackTrace();
      }
      return secretKeyObj;
    }
  };
  private static Cache IvParamSpecs = new Cache() {
    protected Object createValue(Object key) throws Exception {
      IvParameterSpec ivObj = null;
      ivObj = new IvParameterSpec(_convertKeyIv((String) key));
      return ivObj;
    }
  };
  /*
   *  encryption & decryption 
   */
  public static String encrypt(String text, String authKey, String authIv) {
    SecretKey secretKeyObj = null;
    IvParameterSpec ivObj = null;
    try {
      secretKeyObj = (SecretKey) SecretKeySpecs.get(authKey);
      ivObj = (IvParameterSpec) IvParamSpecs.get(authIv);
    } catch (Exception e) {
      e.printStackTrace();
    }
    byte[] data = null;
    try {
      data = text.getBytes(UTF8);
    } catch (Exception e) {
      e.printStackTrace();
    }
    byte[] authToken = null;
    try {
      authToken = encrypt(data, secretKeyObj, ivObj);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return hexToString(authToken);
  }
  public static byte[] encrypt(byte[] data, SecretKey secretKey,
      IvParameterSpec iv) throws Exception {
    Cipher cipher = Cipher.getInstance(CIPHER);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    return cipher.doFinal(data);
  }
  public static String decrypt(String hexString, String authKey, String authIv)
      throws Exception {
    SecretKey secretKeyObj = null;
    IvParameterSpec ivObj = null;
    try {
      secretKeyObj = (SecretKey) SecretKeySpecs.get(authKey);
      ivObj = (IvParameterSpec) IvParamSpecs.get(authIv);
    } catch (Exception e) {
      e.printStackTrace();
    }
    String text = decrypt(hexString, secretKeyObj, ivObj);
    return text;
  }
  public static String decrypt(String message, SecretKey secretKey,
      IvParameterSpec iv) throws Exception {
    byte[] data = stringToHex(message);
    return decrypt(data, secretKey, iv);
  }
  public static String decrypt(byte[] data, SecretKey secretKey,
      IvParameterSpec iv) throws Exception {
    Cipher cipher = Cipher.getInstance(CIPHER);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
    byte[] retByte = cipher.doFinal(data);
    return new String(retByte);
  }
  public static void main(String[] args) throws Exception {
    long begin= new Date().getTime();
    String authKey = "w8f3k9c2";
    String authIv = "w8f3k9c2";
    String text = "aaades Encryption test ";
    // 140CB412BA03869F
    // 140cb412ba03869f
    //  Encrypt the text 
    String encryptedText = encrypt(text, authKey, authIv);
    System.out.println("encryptedText:" + encryptedText);
    //  Restore the ciphertext 
    String plainText = decrypt(encryptedText, authKey, authIv);
    System.out.println("plainText:" + plainText);
    //2a329740ce15f549be64190b183a5be2
    long end =new Date().getTime();
    System.out.println(end-begin);
  }
}

PS: about encryption and decryption interested friends can also refer to the website online tools:

Password security online detection:
http://tools.ofstack.com/password/my_password_safe

High strength password generator:
http://tools.ofstack.com/password/CreateStrongPassword

Thunderbolt, express, whirlwind URL encryption/decryption tools:
http://tools.ofstack.com/password/urlrethunder

Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt

MD5/hash/ SHA-1 / SHA-2 / SHA-256 / SHA-512 / SHA-3 / RIPEMD-160 encryption tools:
http://tools.ofstack.com/password/hash_md5_sha

Online sha1 sha224 / sha256 sha384 / sha512 encryption tools:
http://tools.ofstack.com/password/sha_encode

I hope this article is helpful to you java programming.


Related articles: