encryptor

作者: 小明17 | 来源:发表于2020-04-27 11:36 被阅读0次
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class GeEncryptor {

    /**
     * Encrypt a input string to MD5 code
     * @param src
     *      Input string src
     * @return
     *      encrypted result
     */
    public static String encryptToMD5(String src){
        String md5result = null;
        try {
            md5result = unreversedEncrypt(src,"MD5");
        } catch (Exception e) {}
        return md5result;
    }

    /**
     * Unreversed encrypt a string with specified algorithm
     * @param src
     * @param algorithm
     * @return
     */
    public static String unreversedEncrypt(String src, String algorithm)throws Exception{

        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.reset();
            messageDigest.update(src.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorgithm:"+algorithm);
        }

        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            String hex = Integer.toHexString(0xFF & byteArray[i]);
            if (hex.length() == 1)
                md5StrBuff.append("0").append(hex);
            else
                md5StrBuff.append(hex);
        }

        return md5StrBuff.toString();
    }

    /**
     * Encrypt a input string SHA1 code
     * @param src
     * @return
     */
    public static String encryptToSHA1(String src){
        String sha1result = null;
        try {
            sha1result = unreversedEncrypt(src,"SHA1");
        } catch (Exception e) {}
        return sha1result;
    }

    /**
     * Encrypt(DES) input data with a string key
     * @param data
     *      Input data
     * @param strKey
     *      String key with a length bigger or equals to 8
     * @return
     *      Encrypted result
     */
    public static String encryptByDES(String data,String strKey){

        if(strKey==null || strKey.length()<8)
            throw new IllegalArgumentException("The strKey should have a value with its'length bigger than 8");

        try {
            return byte2hex(desEncrypt(data.getBytes(), strKey.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Decrypt(DES) input data with a string key
     * @param data
     *      Input data
     * @param strKey
     *      String key with a length bigger or equals to 8
     * @return
     *      Decrypted result
     */
    public static String decryptByDES(String data,String strKey){

        if(strKey==null || strKey.length()<8)
            throw new IllegalArgumentException("The strKey should have a value with its'length bigger than 8");

        try {
            byte[] bs = desDecrypt(hex2byte(data.getBytes()),strKey.getBytes());
            return new String(bs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private final static String DES = "DES";

    /**
     * 加密
     * @param src
     *            数据源
     * @param key
     *            密钥
     * @return 返回加密后的数据
     * @throws Exception
     */
    private static byte[] desEncrypt(byte[] src, byte[] key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        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(src);
    }

    /**
     * 解密
     * @param src
     *            数据源
     * @param key
     *            密钥
     * @return 返回解密后的原始数据
     * @throws Exception
     */
    private static byte[] desDecrypt(byte[] src, byte[] key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        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(src);
    }

    /**
     *字节转化成十六进制字符串
     * @param b
     * @return
     */
    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }

    /**
     * 十六进制转换成字节
     * @param b
     * @return
     */
    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("the length of input is not even");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }
}

相关文章

网友评论

      本文标题:encryptor

      本文链接:https://www.haomeiwen.com/subject/orkywhtx.html