Des 加密算法java工具类

package com.lock.demo.service;

import org.apache.tomcat.util.codec.binary.Base64;

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

/**
 * @author niunafei
 * @function
 *         des 对称性算法加密 解密工具类 可逆性算法
 * @email [email protected]
 * @date 2018/12/12  下午2:05
 */
public class DesUtils {

    private static final String DES="DES";

    /**
     * 公钥  8位以上
     */
    private static final String SECRET_KEY="12345678";

    /**
     * 获取秘钥对象
     * @return
     * @throws Exception
     */
    private static final SecretKey getSecretKeyFactory() throws Exception {
        SecretKeyFactory des = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = des.generateSecret(new DESKeySpec(SECRET_KEY.getBytes()));
        return secretKey;
    }

    /**
     * 加密
     * @param param
     * @return
     * @throws Exception
     */
    public static final String encryption(String param) throws Exception {
        Cipher cipher = Cipher.getInstance(DES);
        SecretKey secretKey = getSecretKeyFactory();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return  new String(Base64.encodeBase64(cipher.doFinal(param.toString().getBytes())));
    }

    /**
     * 解密
     * @param value
     * @return
     * @throws Exception
     */
    public static final String decrypt(String value) throws Exception {
        Cipher cipher = Cipher.getInstance(DES);
        SecretKey secretKey = getSecretKeyFactory();
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.decodeBase64(value.getBytes())));
    }

    /**
     测试
     */
    public static void main(String[] args) throws Exception {
        String key="123";
        System.out.println(" key="+key);
        //输出 key=123
        String value=DesUtils.encryption(key);
        System.out.println("encryption value="+value);
        //输出 encryption value=LDiFUdf0iew=
        System.out.println("decrypt key="+DesUtils.decrypt(value));
        //输出 decrypt key=123

    }
}

比较简单无脑~~~~~

猜你喜欢

转载自www.cnblogs.com/niunafei/p/10108180.html