package org.springblade.yeePay.service;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

public class Sm4GcmUtils {
	static {
		if (Security.getProvider("BC") == null) {
			Security.addProvider(new BouncyCastleProvider());
		}
	}

	/**
	 * 解密
	 *
	 * @param key
	 * @param data
	 * @param once
	 * @param associatedData
	 * @return
	 */
	public static String decrypt_GCM_NoPadding(String key, String data, String once, String associatedData) throws Exception {
		Cipher cipher = Cipher.getInstance("SM4/GCM/NoPadding", BouncyCastleProvider.PROVIDER_NAME);
		Key sm4Key = new SecretKeySpec(Base64.decodeBase64(key), "SM4");
		byte[] iv = new byte[12];
		if (StringUtils.isNotEmpty(once)) {
			iv = Base64.decodeBase64(once);
		}
		if (StringUtils.isNotEmpty(associatedData)) {
			byte[] aad = associatedData.getBytes();
			cipher.updateAAD(aad);
		}
		GCMParameterSpec s = new GCMParameterSpec(128, iv);
		cipher.init(Cipher.DECRYPT_MODE, sm4Key, s);
		return new String(cipher.doFinal(Base64.decodeBase64(data)));

	}

}
