package test;

import com.alibaba.fastjson.JSONObject;

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

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

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.SecureRandom;

public class FpayEncryTool {

    private final static String ENCODE = "GBK";
    private final static String DES = "DES";
    private final static int keyLengthMax=24;

    //对数据进行加密
    //type:pay,refund
    public static String encryFpayData(String key,String data) throws Exception {
        //将数据转为json验证数据有效性

        JSONObject jsonStr = JSONObject.parseObject(data);
        if(jsonStr.get("type").equals("pay")){
            if(jsonStr.get("order_amount")==null||!StringUtils.isNumeric(jsonStr.get("order_amount").toString())){
                return null;
            }
            if(jsonStr.get("product_name")==null||(jsonStr.get("product_name")).toString().length()>100){
                return null;
            }
            if(jsonStr.get("order_info")==null||(jsonStr.get("order_info")).toString().length()>100){
                return null;
            }
            if(jsonStr.get("auth_code")==null||(jsonStr.get("auth_code")).toString().length()>128){
                return null;
            }
            if(jsonStr.get("order_no")==null||(jsonStr.get("order_no")).toString().length()>30){
                return null;
            }
        }else if(jsonStr.get("type").equals("refund")){
            if(jsonStr.get("order_no")==null||(jsonStr.get("order_no")).toString().length()>30){
                return null;
            }
            if(jsonStr.get("ref_desc")==null||(jsonStr.get("ref_desc")).toString().length()>30){
                return null;
            }
        }else if(jsonStr.get("type").equals("result")){

        }else{
            return null;
        }
        return encrypt(data, key);

    }

    //对数据进行解密
    public static String decrypFpayData(String key,String data) throws Exception {
        return decrypt(data,key);
    }

    

    /**
     * Description 根据键值进行加密
     * @param data 待加密数据
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(ENCODE), key.getBytes(ENCODE));
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }

    /**
     * 根据键值进行解密
     * @param data 待解密数据
     * @param key    密钥
     * @return
     * @throws IOException
     * @throws Exception
     */
    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(ENCODE));
        return new String(bt, ENCODE);
    }

    /**
     * Description 根据键值进行加密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        key=extendKey(key);
        
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    public static byte[] extendKey(byte[] key) {
        //System.out.println("length:"+key.length);
        byte[] tmpKey = new byte[keyLengthMax];
        if (key.length < keyLengthMax) { // short key ? .. extend to 24 byte key 
            int i;int iMax=(int)(keyLengthMax/key.length);int iRem=(int)(keyLengthMax%key.length);
            System.arraycopy(key, 0, tmpKey, 0,iRem+1);
            //System.out.println(" begI:"+0+" endI:"+(iRem));
            for(i=0;i<iMax;i++) {
                //System.out.println("i:"+i+" begI:"+(i*key.length+iRem)+" endI:"+(i*key.length+iRem+key.length));
                //System.out.println("keyL:"+key.length+" temL:"+tmpKey.length);
                System.arraycopy(key, 0, tmpKey, i*key.length+iRem, key.length);
            }
        }else {
            System.arraycopy(key, 0, tmpKey, 0,keyLengthMax);
        }
        return tmpKey;
    }
    
    
    /**
     * Description 根据键值进行解密
     *
     * @param data
     * @param key 加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        key=extendKey(key);
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    public static void main(String[] args){
        /*String data = "12AUism810jsqASI08";
        String key ="qwerrewq";
        System.out.println("加密前===>"+data);
        try {
            //System.err.println(encrypt(data, key));
            //System.err.println(decrypt(encrypt(data, key), key));
            String jiamihou = encrypt(data,key);
            System.out.println("加密后===>"+jiamihou);
            System.out.println("解密后===>"+decrypt(jiamihou,key));
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        String temp;
        // temp="{'order_amount':'1','product_name':'测试','order_info':'测试加解密','auth_code':'285192674239050687','order_no':'201905140953','type':'pay'}";
        temp="{'order_no':'TY_YH_ali_1557814483393_61','ref_desc':'测试退款退款','type':'refund'}";
        String key="544646";

        String str1=null;
        String str2=null;
        try {
            str1=FpayEncryTool.encryFpayData(key,temp);
            str2=FpayEncryTool.decrypFpayData(key,str1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonStr = JSONObject.parseObject(str2);
        System.out.println("str1:"+str1);
        System.out.println("str1转译:"+URLEncoder.encode(str1));
        System.out.println("str2:"+str2);
        System.out.println("type:"+jsonStr.get("type"));
    }
    
    //将结果对特殊字符转译
    
    
    
    
}
View Code

打印结果如下

 打印结果:
str1:obbHcSjVYQ3rA1CTMYObuFd9zGSvMgfItZGv9MjceSPJa+0HQh1gC/PtgjOsodOxgyaudtddP2Dk
NfiiDN/w0SK6PGpPD9PgTZQiAF4AKvUea29Bae/B2Q==
str1转译:obbHcSjVYQ3rA1CTMYObuFd9zGSvMgfItZGv9MjceSPJa%2B0HQh1gC%2FPtgjOsodOxgyaudtddP2Dk%0D%0ANfiiDN%2Fw0SK6PGpPD9PgTZQiAF4AKvUea29Bae%2FB2Q%3D%3D
str2:{'order_no':'TY_YH_ali_1557814483393_61','ref_desc':'测试退款退款','type':'refund'}
type:refund

如果通过post发送数据,记得转码

 

posted on 2019-05-14 14:44  黑狱  阅读(685)  评论(0编辑  收藏  举报