AES加解密工具类

java语言版本AES加解密工具类

package com.msxf.bot.basic.utils;

import com.alibaba.fastjson.JSON;
import com.msxf.eyas.common.crypto.Crypto;
import com.msxf.eyas.common.crypto.Crypto.Algorithm;
import com.msxf.eyas.common.crypto.Crypto.Mode;
import com.msxf.eyas.common.crypto.Crypto.Padding;
import com.msxf.eyas.common.util.Base64Util;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.Key;
import java.security.spec.KeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 
 * @date 2018/2/5
 */
public class CryptoUtil {
    /**
     * @return
     */
    public static byte[] generateKey(Crypto.Algorithm algorithm) {
        KeyGenerator keyGenerator = null;
        try {
            keyGenerator = KeyGenerator.getInstance(algorithm.getName());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        keyGenerator.init(algorithm.getKeySize());

        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }

    /**
     *
     * @param key
     * @return
     */
    private static Key toKey(Crypto.Algorithm algorithm, byte[] key) {
        try {
            KeySpec keySpec = null;
            if (algorithm.getName().equals("DES")) {
                keySpec = new DESKeySpec(key);
            } else if (algorithm.getName().equals("DESede")) {
                keySpec = new DESedeKeySpec(key);
            } else if (algorithm.getName().equals("AES")) {
                return new SecretKeySpec(key, "AES");
            } else {
                return new SecretKeySpec(key, algorithm.getName());
            }

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm.getName());
            return keyFactory.generateSecret(keySpec);
        } catch (NoSuchAlgorithmException e) {
            return new SecretKeySpec(key, algorithm.getName());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @param data  
     * @param mode  
     * @param padding 
     * @param key   
     * @return
     */
    public static byte[] encrypt(byte[] data, Crypto.Algorithm algorithm,
                                 Crypto.Mode mode, Crypto.Padding padding, byte[] key) {
        Key k = toKey(algorithm, key);

        String algorithmKey = algorithm.getName() + "/" + mode.getName() + "/" + padding.getName();

        try {
            Cipher cipher = Cipher.getInstance(algorithmKey);

            cipher.init(Cipher.ENCRYPT_MODE, k);

            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @param data  
     * @param mode  
     * @param padding 
     * @param key   
     * @return
     */
    public static byte[] decrypt(byte[] data, Crypto.Algorithm algorithm,
                                 Crypto.Mode mode, Crypto.Padding padding, byte[] key) {
        Key k = toKey(algorithm, key);

        String algorithmKey = algorithm.getName() + "/" + mode.getName() + "/" + padding.getName();

        try {
            Cipher cipher = Cipher.getInstance(algorithmKey);

            cipher.init(Cipher.DECRYPT_MODE, k);

            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param data
     * @return
     */
    public static String toHex(byte[] data) {
        return Hex.encodeHexString(data);
    }

    /**
     *
     * @param hex
     * @return
     */
    public static byte[] parseHex(String hex) {
        try {
            return Hex.decodeHex(hex.toCharArray());
        } catch (DecoderException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        byte[] key = CryptoUtil.generateKey(Algorithm.AES128);
        String aesKey = Base64Util.encode(key);
        System.out.println("密钥:" + aesKey);

        System.out.println("======入参加密demo============");
        Map<String,String> request = new HashMap<String,String>();
        request.put("name", "马上消费金融");
        request.put("address", "成都高新天府二街");

        byte[] encryptData = CryptoUtil.encrypt(JSON.toJSONString(request).getBytes(), Algorithm.AES128, Mode.ECB, Padding.PKCS5Padding, Base64Util.decode(aesKey));

        String encodeString = Base64Util.encode(encryptData);
        System.out.println("加密后的数据为:" + encodeString);

        byte[] decryptData = CryptoUtil.decrypt(Base64Util.decode(encodeString), Algorithm.AES128, Mode.ECB, Padding.PKCS5Padding, Base64Util.decode(aesKey));
        String decodeString = new String(decryptData);
        System.out.println("解密后的数据为:" + decodeString);

        System.out.println("======返回结果加密demo============");
        Map<String,String> response = new HashMap<String,String>();
        response.put("code", "10000");
        response.put("message", "请求成功");
        response.put("data", JSON.toJSONString(request));

        byte[] responseAllEncryptData = CryptoUtil.encrypt(JSON.toJSONString(response).getBytes(), Algorithm.AES128, Mode.ECB, Padding.PKCS5Padding, Base64Util.decode(aesKey));

        String responseAllEncodeString = Base64Util.encode(responseAllEncryptData);
        System.out.println("全部结果加密后的数据为:" + responseAllEncodeString);

        byte[] responseEncryptData = CryptoUtil.encrypt(JSON.toJSONString(request).getBytes(), Algorithm.AES128, Mode.ECB, Padding.PKCS5Padding, Base64Util.decode(aesKey));

        String responseEncodeString = Base64Util.encode(responseEncryptData);
        System.out.println("对data加密后的数据为:" + responseEncodeString);
    }
}

对应工具类**

 package com.msxf.bot.basic.utils;

public class Crypto {
    public static enum Algorithm {
        // DES
        DES("DES", 56),

        // 3DES
        DESede112("DESede", 112),
        DESede168("DESede", 168),

        // AES
        AES128("AES", 128),
        AES192("AES", 192), 
        AES256("AES", 256); 

        private String name; 
        private int keySize; 

        private Algorithm(String name, int keySize) {
            this.name = name;
            this.keySize = keySize;
        }

        public String getName() {
            return name;
        }

        public int getKeySize() {
            return keySize;
        }

        @Override
        public String toString() {
            return this.name + "-" + this.keySize;
        }

        /**
         *
         * @param name
         * @return
         */
        public static Algorithm get(String name, int length) {
            for (Algorithm algorithm : Algorithm.values()) {
                if (algorithm.getName().equals(name) && algorithm.getKeySize() == length) {
                    return algorithm;
                }
            }

            throw new UnsupportedOperationException("Can't find Algorithm by name: "
                    + name + ", keySize: " + length);
        }
    }

    public static enum Mode {
        ECB("ECB"),
        CBC("CBC"),
        CFB("CFB"),
        PCBC("PCBC"),
        CTR("CTR"),
        CTS("CTS"),
        OFB("OFB");

        private String name; 

        private Mode(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return this.name;
        }

        /**
         *
         * @param name
         * @return
         */
        public static Mode get(String name) {
            return Mode.valueOf(name);
        }
    }

    public static enum Padding {
        NoPadding("NoPadding"),
        PKCS5Padding("PKCS5Padding"),
        ISO10126Padding("ISO10126Padding");

        private String name; 

        private Padding(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return this.name;
        }

        public static Padding get(String name) {
            return Padding.valueOf(name);
        }
    }
}

package com.msxf.eyas.common.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

/**
 * @author
 * @date 2018/2/5
 */
public class Base64Util {
    /**
     *
     * @param data
     * @return
     */
    public static String encode(byte[] data) {
        return Base64.encodeBase64String(data);
    }

    /**
     * @param data
     * @return
     */
    public static String encode(String data) {
        return Base64.encodeBase64String(StringUtils.getBytesUtf8(data));
    }

    /**
     * @param data
     * @return
     */
    public static byte[] decode(String data) {
        return Base64.decodeBase64(data);
    }

    /**
     * @param data
     * @return
     */
    public static String decodeToString(String data) {
        byte[] result = decode(data);
        return StringUtils.newStringUtf8(result);
    }

    /**
     * @param data
     * @return
     */
    public static String encodeUrlSafe(byte[] data) {
        return StringUtils.newStringUtf8(Base64.encodeBase64URLSafe(data));
    }
}

results matching ""

    No results matching ""