package com.ruoyi.database.util;

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

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

public class EncryptUtils {
    //AES秘钥与偏移量
	private static final String AESKEY     = "1234567891234567";   
    private static final String INITVECTOR = "1234567891234567"; 
    //MD5签名Token
    private static final String MD5TOKEN   = "123456789"; 

    //AES加密  "UTF-8"
    public static String encrypt(String value,String charset) {
        try {
            IvParameterSpec iv = new IvParameterSpec(INITVECTOR.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(AESKEY.getBytes(charset), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //AES解密  "UTF-8"
    public static String decrypt(String encrypted,String charset) {
        try {
            IvParameterSpec iv = new IvParameterSpec(INITVECTOR.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(AESKEY.getBytes(charset), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
            return new String(original,charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    } 

    //MD5签名
    public static String getMd5(String plainText) {
 		try {
 			MessageDigest md = MessageDigest.getInstance("MD5");
 			md.update(plainText.getBytes());
 			byte b[] = md.digest();
 			int i;

 			StringBuffer buf = new StringBuffer("");
 			for (int offset = 0; offset < b.length; offset++) {
 				i = b[offset];
 				if (i < 0)
 					i += 256;
 				if (i < 16)
 					buf.append("0");
 				buf.append(Integer.toHexString(i));
 			}
 			// 32位加密
 			return buf.toString();
 		} catch (Exception e) {
 			e.printStackTrace(); 			
 		}

        return null;
 	}

}
