All Downloads are FREE. Search and download functionalities are using the official Maven repository.

matrix.boot.common.encrypt.DES Maven / Gradle / Ivy

There is a newer version: 2.1.11
Show newest version
package matrix.boot.common.encrypt;

import matrix.boot.common.exception.ServiceException;
import matrix.boot.common.utils.StringUtil;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * DES对称加密解密
 * @author wangcheng
 */
public class DES {

    /**
     * 加密
     * @param content 内容
     * @param password 密码
     * @return 加密后的字符串
     */
    public static String encrypt(String content, String password) {
        try {
            Cipher cipher = getCipher(password, Cipher.ENCRYPT_MODE);
            return Hex.byteToHex(cipher.doFinal(StringUtil.stringToByte(content)));
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 解密
     * @param content 加密后的字符串
     * @param password 密码
     * @return 解密后的字符串
     */
    public static String decrypt(String content, String password) {
        try {
            Cipher cipher = getCipher(password, Cipher.DECRYPT_MODE);
            return StringUtil.byteToString(cipher.doFinal(Hex.hexToByte(StringUtil.stringToByte(content))));
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 获取加密解密器
     * @param password 密钥
     * @param type 加密解密类型
     * @return 加密解密器
     */
    private static Cipher getCipher(String password, Integer type) {
        try {
            password = password.length() >= 8 ? password : MD5.get16(password);
            DESKeySpec dks = new DESKeySpec(StringUtil.stringToByte(password));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Key secretKey = keyFactory.generateSecret(dks);
            IvParameterSpec iv = new IvParameterSpec(StringUtil.stringToByte(password.substring(0, 8)));
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(type, secretKey, iv);
            return cipher;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy