encryptor

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
     *            數(shù)據(jù)源
     * @param key
     *            密鑰
     * @return 返回加密后的數(shù)據(jù)
     * @throws Exception
     */
    private static byte[] desEncrypt(byte[] src, byte[] key) throws Exception {
        // DES算法要求有一個可信任的隨機數(shù)源
        SecureRandom sr = new SecureRandom();
        // 從原始密匙數(shù)據(jù)創(chuàng)建DESKeySpec對象
        DESKeySpec dks = new DESKeySpec(key);
        // 創(chuàng)建一個密匙工廠,然后用它把DESKeySpec轉(zhuǎn)換成
        // 一個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);
        // 現(xiàn)在,獲取數(shù)據(jù)并加密
        // 正式執(zhí)行加密操作
        return cipher.doFinal(src);
    }

    /**
     * 解密
     * @param src
     *            數(shù)據(jù)源
     * @param key
     *            密鑰
     * @return 返回解密后的原始數(shù)據(jù)
     * @throws Exception
     */
    private static byte[] desDecrypt(byte[] src, byte[] key) throws Exception {
        // DES算法要求有一個可信任的隨機數(shù)源
        SecureRandom sr = new SecureRandom();
        // 從原始密匙數(shù)據(jù)創(chuàng)建一個DESKeySpec對象
        DESKeySpec dks = new DESKeySpec(key);
        // 創(chuàng)建一個密匙工廠,然后用它把DESKeySpec對象轉(zhuǎn)換成
        // 一個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);
        // 現(xiàn)在,獲取數(shù)據(jù)并解密
        // 正式執(zhí)行解密操作
        return cipher.doFinal(src);
    }

    /**
     *字節(jié)轉(zhuǎn)化成十六進制字符串
     * @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();
    }

    /**
     * 十六進制轉(zhuǎn)換成字節(jié)
     * @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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 以下內(nèi)容是對xlsx包的說明文檔的整理:xlsx包說明文檔 該包通過操作以下七種對象來對excel進行操作 wor...
    煮豆燃逗比閱讀 1,093評論 0 3
  • 高度是什么? 老在講高度,高度不是細節(jié)推出來的嗎?細節(jié)不是生活中來的嗎?為什么生活細節(jié)出來的東西都不對了? 總是被...
    寧靜996閱讀 315評論 7 5
  • 最近看到一個故事:二桃殺三士。 說是,春秋時,齊景公有三個勇士:公孫接、田開疆和古冶子。三個人身材粗壯臂力驚人,但...
    冰玲_7387閱讀 658評論 0 2
  • 宏偉而遼遠, 寂寞而深沉。 鋼筋駐立原野, 水泥混攪大地。 冷漠而悸動的心穿越街口, 川流不息的紅綠燈, 映照這光...
    古風(fēng)長歌閱讀 479評論 2 4
  • 雜碎 一 九七五年二月間,一個平平常常的日子。天下著雪,密了,大了。飛舞的雪花把天地攪得一片迷蒙。 此刻,邵家溝的...
    黑土地_6345閱讀 384評論 2 12

友情鏈接更多精彩內(nèi)容