java实现加密的常用方法

package com.utils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;

public class EncryptUtil {
    private static int GCM_NONCE_SIZE;
    private static int GCM_TAG_LENGGTH;
	
    static {
        Security.addProvider(new BouncyCastleProvider());
        GCM_NONCE_SIZE = 12;
        GCM_TAG_LENGGTH = 16;
    }
	
    public EncryptUtil() {
    }

    public static String decrypt(String keyHex, String cipherText) {
        return new String(decrypt(Hex.decode(keyHex), cipherText), StandardCharsets.UTF_8);
    }

    public static byte[] decrypt(byte[] keyBytes, String cipherText) {
        if (cipherText != null && !cipherText.isEmpty()) {
            int indexOfDot = cipherText.indexOf(".");
            if (indexOfDot < 1) {
                throw new RuntimeException("Cipher text format error.");
            } else {
                try {
                    String nonceInBase64 = cipherText.substring(0, indexOfDot);
                    String cipherTextInBase64 = cipherText.substring(indexOfDot + 1);
                    byte[] nonce = Base64.decode(nonceInBase64);
                    byte[] cihperTextBytes = Base64.decode(cipherTextInBase64);
                    Key key = new SecretKeySpec(keyBytes, "AES");
                    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGGTH * 8, nonce);
                    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
                    cipher.init(2, key, gcmParameterSpec);
                    return cipher.doFinal(cihperTextBytes);
                } catch (Exception var10) {
                    throw new RuntimeException(var10);
                }
            }
        } else {
            throw new RuntimeException("Cipher text is empty.");
        }
    }

    public static String encrypt(String keyHex, String plainText) {
        return encrypt(Hex.decode(keyHex), plainText.getBytes(StandardCharsets.UTF_8));
    }

    public static String encrypt(byte[] keyBytes, byte[] plainTextBytes) {
        return encrypt(keyBytes, plainTextBytes, new SecureRandom());
    }

    public static String encrypt(byte[] keyBytes, byte[] plainTextBytes, Random random) {
        try {
            Key key = new SecretKeySpec(keyBytes, "AES");
            byte[] nonce = new byte[GCM_NONCE_SIZE];
            random.nextBytes(nonce);
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGGTH * 8, nonce);
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
            cipher.init(1, key, gcmParameterSpec);
            byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);
            return Base64.toBase64String(nonce) + "." + Base64.toBase64String(cipherTextBytes);
        } catch (Exception var8) {
            throw new RuntimeException(var8);
        }
    }
}

package com.utils;

import com.alibaba.fastjson.JSON;
import com.utils.EncryptUtil;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.*;

public class EncryptUtils {

    private static final int CBC_IV_LENGTH = 16;

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String md5(String message) {
        try {
            return md5(message.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String md5(byte[] message) {
        try {
            return new String(Hex.encode(MessageDigest.getInstance("MD5").digest(message)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String md5(InputStream inputStream) {
        byte[] buffer = new byte[8192];

        try {
            int length = 0;
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            while ((length = inputStream.read(buffer)) != -1) {
                md5.update(buffer, 0, length);
            }
            return new String(Hex.encode(md5.digest()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String sha256(String message) {
        try {
            return sha256(message.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String sha256(byte[] message) {
        try {
            return new String(Hex.encode(MessageDigest.getInstance("SHA-256").digest(message)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String sha256(InputStream inputStream) {
        byte[] buffer = new byte[8192];

        try {
            int length = 0;
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            while ((length = inputStream.read(buffer)) != -1) {
                sha256.update(buffer, 0, length);
            }
            return new String(Hex.encode(sha256.digest()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String hmacSHA256(String plainText, String key) {
        try {
            return base64Encode(hmacSHA256(plainText.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String hmacSHA256(Map<String,Object> map, String key) {
        TreeMap<String, Object> paramMap = new TreeMap<>(map);
        List<String> params = new ArrayList<>();
        for (String paramKey : paramMap.keySet()) {
            Object object = paramMap.get(paramKey);
            if (object == null) {
                params.add(paramKey + "=");
            } else {
                if (object instanceof Map || object instanceof Collection) {
                    params.add(String.valueOf(paramKey) + "=" + JSON.toJSONString(object));
                } else {
                    params.add(String.valueOf(paramKey) + "=" + String.valueOf(object));
                }
            }
        }
        return hmacSHA256(CollectionUtils.join(params, "&"),key);
    }

    public static byte[] hmacSHA256(byte[] plainTextBytes, byte[] keyBytes) {
        try {
            Mac e = Mac.getInstance("HmacSHA256");
            e.init(new SecretKeySpec(keyBytes, "HmacSHA256"));
            return e.doFinal(plainTextBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String hmacSHA1(String plainText, String key) {
        try {
            return base64Encode(hmacSHA1(plainText.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] hmacSHA1(byte[] plainTextBytes, byte[] keyBytes) {
        try {
            Mac e = Mac.getInstance("HmacSHA1");
            e.init(new SecretKeySpec(keyBytes, "HmacSHA1"));
            return e.doFinal(plainTextBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * base64加密
     *
     * @param s
     * @return
     */
    public static String base64Encode(String s) {
        try {
            return base64Encode(s.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("base64 encode failed", e);
        }
    }

    /**
     * base64加密
     *
     * @param buff
     * @return
     */
    public static String base64Encode(byte[] buff) {
        return Base64.encodeBase64String(buff);
    }

    /**
     * base64解密
     *
     * @param s
     * @return
     */
    public static String base64Decode(String s) {
        try {
            return base64Decode(s.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException("base64 decode failed", e);
        }
    }

    /**
     * base64解密
     *
     * @param buff
     * @return
     */
    public static String base64Decode(byte[] buff) {
        try {
            return new String(Base64.decodeBase64(buff), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("base64 decode failed", e);
        }
    }

    public static String aes256GcmEncrypt(String keyHex, String plainText) {
        return EncryptUtil.encrypt(keyHex, plainText);
    }

    public static String aes256GcmDecrypt(String keyHex, String cipherText) {
        return EncryptUtil.decrypt(keyHex, cipherText);
    }
}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页