package io.renren.common.utils.security;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import lombok.extern.log4j.Log4j2;

/**
 * 加密工具类
 * @author lsy
 *
 */
@Log4j2
public class SM4Utils {

	private static String Charset = "UTF-8";
	private  static SM4Context ctx = new SM4Context();

	/**
	 * 加密
	 * @param plainText 原文
	 * @param secretKey	秘钥
	 * @return
	 */
	public static String encryptData_ECB(String plainText, String secretKey) {
		try {
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_ENCRYPT;
			SM4 sm4 = new SM4();
			sm4.sm4_setkey_enc(ctx, secretKey.getBytes());
			byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes(Charset));
			String cipherText = Base64.encodeBase64String(encrypted);
			if (cipherText != null && cipherText.trim().length() > 0) {
				Pattern p = Pattern.compile("\\s*|\t|\r|\n");
				Matcher m = p.matcher(cipherText);
				cipherText = m.replaceAll("");
			}
			return cipherText;
		} catch (Exception e) {
			log.error("加密失败，返回原文",e.getMessage());
			return plainText;
		}
	}
	
	/**
	 * 解密
	 * @param cipherText 密文
	 * @param secretKey	秘钥
	 * @return
	 */
	public static String decryptData_ECB(String cipherText, String secretKey) {
		try {
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_DECRYPT;

			SM4 sm4 = new SM4();
			sm4.sm4_setkey_dec(ctx, secretKey.getBytes());
			byte[] decrypted = sm4.sm4_crypt_ecb(ctx,  Base64.decodeBase64(cipherText));
			return new String(decrypted, Charset);
		} catch (Exception e) {
			log.error("解密失败，返回原文",e.getMessage());
			return cipherText;
		}
	}

	public static void main(String[] args) throws IOException {
		String secretKey = "aaaaaaaaaaaaaaaa";
		System.out.println(secretKey);
		String plainText = "1111111";
		
		System.out.println("原文="+ plainText);
		
		String encryptInfo = SM4Utils.encryptData_ECB(plainText, secretKey);
		
		System.out.println("密文="+ encryptInfo);
		
		String info = SM4Utils.decryptData_ECB(encryptInfo, secretKey);
		
		System.out.println("明文="+ info);
		
		
	}
}

