DES encryption and decryption method


import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;


/**
 * Using DES encryption and decryption method
 */
public class CryptoTools {

    private final byte[] DESkey = new byte[]{58, 21, 93, -100, 78, 4, -38, 32, 15, -89, 44, 90, 26, -6, -101, -112, 2, 94, 18, -52, 119, 35, -72, -69};// Set the key, omit
    // private final byte[] DESIV = new byte[]{-121, 39, -10, -113, 36, 99, -89, 3, 42, 8, 62, 83, -72, 4, -47, 43, -111, 39, 112, 58, -83, 10, 41, -44};// set the vector, omit
    private final byte[] DESIV = new byte[]{58, 21, 93, 93, 93, 93, 93, 93};// Set the key, omit

    private AlgorithmParameterSpec iv = null;// The parameter interface of the encryption algorithm, IvParameterSpec is an implementation of it
    private Key key = null;

    public CryptoTools() throws Exception {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// Get the key factory
        // Set the key parameters and get the key object
        key = keyFactory.generateSecret(new DESKeySpec(DESkey));// Get the key object
        iv = new IvParameterSpec(DESIV);// set vector
    }

    public String encode(String data) throws Exception {
        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// Get the encrypted object Cipher
        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// Set the working mode to encryption mode, give the key and vector
        byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(pasByte);
    }

    public String decode(String data) throws Exception {
        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
        BASE64Decoder base64Decoder = new BASE64Decoder();

        byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));

        return new String(pasByte, "UTF-8");
    }

    public static void main(String[] args) {
        try {
            String test = "a1";
            CryptoTools des = new CryptoTools();//Custom key
            System.out.println("Character before encryption: " + test);
            System.out.println("Encrypted characters: " + des.encode(test));
            System.out.println("Decrypted characters: " + des.decode(des.encode(test)));
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326117135&siteId=291194637