package com.mcwl.common.utils.sign;


import com.baidu.aip.util.Base64Util;
import com.mcwl.common.constant.NcountKey;
import com.mcwl.common.exception.NCountDemoException;


import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class KeyUtils {

	/**
	 * 加载私钥
	 *
	 */
	public static PrivateKey loadPrivateKey(String privateKey) throws NCountDemoException {
		// 去除头尾标志
		// 去除换行符
		privateKey = privateKey.replace("\r", "").replace("\n", "").replace(" ", "");
		byte[] bPriKey = Base64Util.decode(privateKey);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bPriKey);
		KeyFactory keyFactory;
		try {
			keyFactory = KeyFactory.getInstance(NcountKey.ALGORITHM);
			PrivateKey key = keyFactory.generatePrivate(keySpec);
			return key;
		} catch (Exception e) {
			e.printStackTrace();
			throw new NCountDemoException("加载私钥异常", e);
		}
	}
}
