package com.steerinfo.util;

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

public class DESUtil {
    //解密
    public static String decrypt(String message, String key) throws Exception{
        byte[] bytesrc = convertHexString(message);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("GB2312"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("GB2312"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] retByte = cipher.doFinal(bytesrc);

        return new String(retByte, "GB2312");
    }

    //加密
    public static byte[] encrypt(String message, String key) throws Exception{
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("GB2312"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("GB2312"));
        cipher.init(Cipher.ENCRYPT_MODE,secretKey,iv);
        return cipher.doFinal(message.getBytes("GB2312"));
    }

    public static byte[] convertHexString(String ss) {
        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 toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String painText = Integer.toHexString(0xff & b[i]);
            if (painText.length() < 2) {
                painText = '0' + painText;
            }
            hexString.append(painText);
        }
        return hexString.toString();
    }
}
