java加密算法-DES

public class DESUtil {
    private static String strdefaultkey = "13456789abcd";//默认的key
    private Cipher encryptCipher = null;//加密
    private Cipher decryptCipher = null;//解密

    public static String byteArr2HexStr(byte[] arrb) {
        int len = arrb.length;
        StringBuffer sb = new StringBuffer(len * 2);
        for (int i = 0; i < len; i++) {
            int inttmp = arrb[i];
            while (inttmp < 0) {
                inttmp = inttmp + 256;
            }
            if (inttmp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(inttmp, 16));
        }
        return sb.toString();
    }

    public static byte[] hexstr2byteatrr(String strin) {
        byte[] arrb = strin.getBytes();
        int len = arrb.length;
        byte[] arro = new byte[len / 2];
        for (int i = 0; i < len; i = i + 2) {
            String strt = new String(arrb, i, 2);
            arro[i / 2] = (byte) Integer.parseInt(strt, 16);
        }
        return arro;
    }

    // public DesUtils() throws Exception {      this(strDefaultKey);    }
    public DESUtil() throws Exception {
        this(strdefaultkey);
    }

    public DESUtil(String strdefaultkey2) throws Exception {

        Security.addProvider(new SunJCE());
        Key key = getKey(strdefaultkey2.getBytes());
        encryptCipher = Cipher.getInstance("DES");
        encryptCipher.init(Cipher.ENCRYPT_MODE, key);
        decryptCipher = Cipher.getInstance("DES");
        decryptCipher.init(Cipher.DECRYPT_MODE, key);
    }

    public byte[] encrypt(byte[] arrb) throws Exception {
        return encryptCipher.doFinal(arrb);
    }

    public String encrypt(String str) throws Exception {
        return byteArr2HexStr(encrypt(str.getBytes()));
    }

    public byte[] decrypt(byte[] arrB) throws Exception {
        return decryptCipher.doFinal(arrB);
    }

    public String decrypt(String strIn) throws Exception {
        return new String(decrypt(hexstr2byteatrr(strIn)));
    }

    private Key getKey(byte[] arrBTmp){
        byte[]arrB=new byte[8];
        for(int i=0;i<arrBTmp.length&&i<arrB.length;i++){

            arrB[i]=arrBTmp[i];
        }
        // 生成密钥
        Key key=new javax.crypto.spec.SecretKeySpec(arrB,"DES");
        return key;
}

    public static void main(String[] args) throws Exception {
        
        String test="ksjdfksjdflk;342315.,,52256266322555124123225555";
        DESUtil des = new DESUtil("kj;skldjfklsdj,.-=sdfjj;f'wons2862485");//自定义key值
        String b = des.encrypt(test);//加密
        System.out.println("加密后:"+b);
        String a= des.encrypt(test);
        //DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm SSS");
        
        System.out.println("解密后"+des.decrypt(a));//解密
        
        
    }
    
}
原文地址:https://www.cnblogs.com/syscn/p/7742266.html