java如何對字符串進行加密 ?

如題, 下面是lz使用java內置的DES算法進行的加密算法, 希望對你有用


import java.security.Key;

import javax.crypto.Cipher;

/**
 * 使用DES算法對字符串進行加密解密 (加密解密的操作步驟正好相反, 參考 {@link #encrypt(String)}, {@link #decrypt(String)})
 */
public class DesUtils {
    private static String defaultSecretKey = "default_secret_key"; //默認密鑰
    private Cipher encryptCipher = null; //加密器
    private Cipher decryptCipher = null; //解密器

    public DesUtils() throws Exception {
        this(defaultSecretKey);
    }

    /**
     * @param secretKey 加密解密使用的密鑰
     */
    public DesUtils(String secretKey) {
        Key key;
        try {
            key = getKey(secretKey.getBytes());
            encryptCipher = Cipher.getInstance("DES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, key);
            decryptCipher = Cipher.getInstance("DES");
            decryptCipher.init(Cipher.DECRYPT_MODE, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加密 (邏輯: 1. 將要加密的字符串轉換為字節數組(byte array)<br/>
     *            2. 將第一步的字節數組作為輸入使用加密器(Cipher)的doFinal方法進行加密, 返回字節數組<br/>
     *            3. 把加密后的字節數組轉換成十六進制的字符串)<br/>
     * @param strIn 要加密的字符串
     * @return 返回加密后的十六進制字符串
     * @throws Exception
     */
    public String encrypt(String strIn) throws Exception {
        return byteArr2HexStr(encrypt(strIn.getBytes()));
    }

    public byte[] encrypt(byte[] arrB) throws Exception {
        return encryptCipher.doFinal(arrB);
    }

    /**
     * 解密 (邏輯: 1. 把加密后的十六進制字符串轉換成字節數組(byte array)<br/>
     *            2. 將第一步的字節數組作為輸入使用加密器(Cipher)的doFinal方法進行解密, 返回字節數組(byte array)<br/>
     *            3. 把解密后的字節數組轉換成字符串)<br/>
     * @param strIn
     * @return
     * @throws Exception
     */
    public String decrypt(String strIn) throws Exception {
        return new String(decrypt(hexStr2ByteArr(strIn)));
    }

    public byte[] decrypt(byte[] arrB) throws Exception {
        return decryptCipher.doFinal(arrB);
    }

    public static String byteArr2HexStr(byte[] arrB) throws Exception {
        int iLen = arrB.length;
        // 每個byte用兩個字符才能表示,所以字符串的長度是數組長度的兩倍
        StringBuffer sb = new StringBuffer(iLen * 2);
        for (int i = 0; i < iLen; i++) {
            int intTmp = arrB[i];
            // 把負數轉換為正數
            while (intTmp < 0) {
                intTmp = intTmp + 256;
            }
            // 小于0F的數需要在前面補0
            if (intTmp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(intTmp, 16));
        }
        return sb.toString();
    }

    public static byte[] hexStr2ByteArr(String strIn) throws Exception {
        byte[] arrB = strIn.getBytes();
        int iLen = arrB.length;
        // 兩個字符表示一個字節,所以字節數組長度是字符串長度除以2
        byte[] arrOut = new byte[iLen / 2];
        for (int i = 0; i < iLen; i = i + 2) {
            String strTmp = new String(arrB, i, 2);
            arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
        }
        return arrOut;
    }

    private Key getKey(byte[] arrBTmp) throws Exception {
        // 創建一個空的8位字節數組(默認值為0)
        byte[] arrB = new byte[8];
        // 將原始字節數組轉換為8位
        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }
        // 生成密鑰
        Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
        return key;
    }


    /**
     * 用法實例
     */
    public static void main(String[] args) {
        try {
            String test = "liwc";
            //注意這里,自定義的加密的KEY要和解密的KEY一致,這就是鑰匙,如果你上鎖了,卻忘了鑰匙,那么是解密不了的
            DesUtils des = new DesUtils("leemenz"); //自定義密鑰
            System.out.println("加密前的字符:" + test);
            System.out.println("加密后的字符:" + des.encrypt(test));
            System.out.println("解密后的字符:" + des.decrypt(des.encrypt(test)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容