JAVA常用加解密工具類

文章目錄

Des

import org.apache.commons.codec.binary.Base64;

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

public class DesUtil {

    private static final String SECRET_KEY_TYPE = "DES";
    private static final String ECB_MOB = "DES/ECB/PKCS5Padding";
    private static final String CHAESET_NAME = "UTF-8";

    private static Key getKey(String password) throws Exception{
        byte[] DESkey = password.getBytes(CHAESET_NAME);
        DESKeySpec keySpec = new DESKeySpec(DESkey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SECRET_KEY_TYPE);
        return keyFactory.generateSecret(keySpec);
    }

    public static String encode(String data, String password) throws Exception {
        Cipher enCipher = Cipher.getInstance(ECB_MOB);
        Key key = getKey(password);
        enCipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] pasByte = enCipher.doFinal(data.getBytes(CHAESET_NAME));
        return Base64.encodeBase64String(pasByte);
    }

    public static String decode(String data, String password) throws Exception {
        Cipher deCipher = Cipher.getInstance(ECB_MOB);
        Key key = getKey(password);
        deCipher.init(Cipher.DECRYPT_MODE, key);
        byte[] pasByte = deCipher.doFinal(Base64.decodeBase64(data.getBytes(CHAESET_NAME)));
        return new String(pasByte, CHAESET_NAME);
    }
}

AES

import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import cn.hutool.core.codec.Base64;

public class AESUtil {

    /**
     * 密鑰算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS7Padding";

    /**
     * AES加密
     * @param data
     *            加密內容
     * @param password
     *            加密密碼
     * @return
     * @throws Exception
     */
    public static String encryptData(String data, String password) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        // 創建密碼器
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        // 初始化爲加密模式的密碼
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));
        // 加密
        byte[] result = cipher.doFinal(data.getBytes());

        return Base64.encode(result);
    }

    /**
     * AES解密
     * @param base64Data
     *            解密內容
     * @param password
     *            解密密碼
     * @return
     * @throws Exception
     */
    public static String decryptData(String base64Data, String password) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        // 創建密碼器
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        // 使用密鑰初始化,設置爲解密模式
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
        // 執行操作
        byte[] result = cipher.doFinal(Base64.decode(base64Data));
        return new String(result, "utf-8");
    }

    /**
     * 生成加密祕鑰
     * @return
     */
    private static SecretKeySpec getSecretKey(String password) {
        SecretKeySpec key = new SecretKeySpec(MD5.sign(password, "UTF-8").toLowerCase().getBytes(), ALGORITHM);
        return key;
    }
}

RSA

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RsaUtils {

    private static final Logger logger = LoggerFactory.getLogger(RsaUtils.class);

    /**
     * RSA2簽名
     * @param content 待簽名的字符串
     * @param privateKey rsa私鑰字符串
     * @param charset 字符集編碼
     * @return 簽名結果
     */
    public static String rsaSign(String content, String privateKey, String charset) {
        try {
            PrivateKey priKey = getPrivateKeyFromPKCS8("RSA", new ByteArrayInputStream(privateKey.getBytes()));
            Signature signature = Signature.getInstance("SHA256WithRSA");
            signature.initSign(priKey);
            if (StringUtils.isBlank(charset)) {
                signature.update(content.getBytes());
            } else {
                signature.update(content.getBytes(charset));
            }
            byte[] signed = signature.sign();
            return new String(Base64.encodeBase64(signed));
        } catch (Exception e) {
            logger.error("RSA簽名異常:{}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * RSA2驗籤
     * 
     * @param content 被簽名的內容
     * @param sign 簽名後的結果
     * @param publicKey rsa公鑰
     * @param charset 字符集編碼
     * @return 驗簽結果
     */
    public static boolean doCheck(String content, String sign, String publicKey, String charset) {
        try {
            PublicKey pubKey = getPublicKeyFromX509("RSA", new ByteArrayInputStream(publicKey.getBytes()));
            Signature signature = Signature.getInstance("SHA256WithRSA");
            signature.initVerify(pubKey);
            signature.update(getContentBytes(content, charset));
            return signature.verify(Base64.decodeBase64(sign.getBytes()));
        } catch (Exception e) {
            logger.error("RSA驗籤異常:{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 
     * 獲取私鑰對象
     * @param algorithm 簽名方式
     * @param ins 私鑰流
     * @return
     * @throws Exception
     */
    private static PrivateKey getPrivateKeyFromPKCS8(String algorithm, InputStream ins) throws Exception {
        if (ins == null || StringUtils.isEmpty(algorithm)) {
            return null;
        }
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        byte[] encodedKey = readText(ins, "utf-8", true).getBytes();
        encodedKey = Base64.decodeBase64(encodedKey);
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
    }

    /**
     * 
     * 獲取公鑰對象
     * @param algorithm 簽名方式
     * @param ins 公鑰流
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static PublicKey getPublicKeyFromX509(String algorithm, InputStream ins) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
            StringWriter writer = new StringWriter();
            io(new InputStreamReader(ins), writer, true, true);
            byte[] encodedKey = writer.toString().getBytes();
            // 先base64解碼
            encodedKey = Base64.decodeBase64(encodedKey);
            return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
        } catch (InvalidKeySpecException e) {
            logger.error("公鑰簽名InvalidKeySpecException異常:{}", e.getMessage(), e);
            return null;
        } catch (NoSuchAlgorithmException e) {
            logger.error("公鑰簽名NoSuchAlgorithmException異常:{}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 
     * 獲取字符串對應編碼的字節
     * @param content 字符串內容
     * @param charset 字符集編碼
     * @return
     * @throws UnsupportedEncodingException
     */
    private static byte[] getContentBytes(String content, String charset) throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(charset)) {
            return content.getBytes();
        }
        return content.getBytes(charset);
    }

    /**
     * 
     * 將指定輸入流的所有文本全部讀出到一個字符串中
     * @param in 輸入流
     * @param charset 字符集編碼
     * @param closeIn 是否關閉流
     * @return
     * @throws IOException
     */
    private static String readText(InputStream in, String charset, boolean closeIn) throws IOException {
        Reader reader = charset == null ? new InputStreamReader(in) : new InputStreamReader(in, charset);
        return readText(reader, closeIn);
    }

    /**
     * 
     * 將指定<code>Reader</code>的所有文本全部讀出到一個字符串中
     * @param in 輸入流
     * @param closeIn 是否關閉流
     * @return
     * @throws IOException
     */
    private static String readText(Reader in, boolean closeIn) throws IOException {
        StringWriter out = new StringWriter();
        io(in, out, closeIn, true);
        return out.toString();
    }

    /**
     * 
     * 從輸入流讀取內容,寫入到輸出流中
     * @param in 輸入流
     * @param out 輸出流
     * @param closeIn 是否關閉流
     * @param closeOut 是否關閉流
     * @throws IOException
     */
    private static void io(Reader in, Writer out, boolean closeIn, boolean closeOut) {
        int bufferSize = 8192 >> 1;
        char[] buffer = new char[bufferSize];
        int amount;
        try {
            while ((amount = in.read(buffer)) >= 0) {
                out.write(buffer, 0, amount);
            }
            out.flush();
        } catch (Exception e) {
            logger.error("從輸入流讀取內容,寫入到輸出流中異常:{}", e.getMessage(), e);
        } finally {
            if (closeIn) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("從輸入流讀取內容,寫入到輸出流中異常:{}", e.getMessage(), e);
                }
            }
            if (closeOut) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("從輸入流讀取內容,寫入到輸出流中異常:{}", e.getMessage(), e);
                }
            }
        }
    }
}

發佈了402 篇原創文章 · 獲贊 60 · 訪問量 71萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章