RAS加簽實現類

import java.io.*;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

/**
 * Rsa加解籤
 */
@Component
public class RsaSignUtil {

	private static final Logger logger = LoggerFactory.getLogger(RsaSignUtil.class);

	/**私鑰緩存*/
	private static Map<String, PrivateKey> pkMap = new HashMap<String, PrivateKey>();


	public static PrivateKey genPrivateKey(byte[] key) {
		PrivateKey pk = null;
		try {
			PKCS8EncodedKeySpec e = new PKCS8EncodedKeySpec(key);
			KeyFactory kf = KeyFactory.getInstance("RSA");
			pk = kf.generatePrivate(e);
			return pk;
		} catch (Exception arg3) {
			return null;
		}
	}

	public static byte[] sign(PrivateKey pk, byte[] data) {
		byte[] sb = (byte[]) null;
		try {
			Signature e = Signature.getInstance("SHA256withRSA");
			e.initSign(pk);
			e.update(data);
			sb = e.sign();
			return sb;
		} catch (Exception arg3) {
			return null;
		}
	}

	public static X509Certificate genCertificate(byte[] certData) {
		ByteArrayInputStream bais = new ByteArrayInputStream(certData);
		X509Certificate cert = null;

		try {
			CertificateFactory e = CertificateFactory.getInstance("X.509");
			cert = (X509Certificate) e.generateCertificate(bais);
			return cert;
		} catch (Exception arg3) {
			return null;
		}
	}

	public static boolean verifySign(X509Certificate cert, byte[] plain, byte[] signData) {
		try {
			Signature e = Signature.getInstance("SHA256withRSA");
			e.initVerify(cert);
			e.update(plain);
			return e.verify(signData);
		} catch (Exception arg3) {
			return false;
		}
	}

	/**
	 * 生成簽名
	 * 
	 * @param inStr
	 * 			待簽名字符串
	 * @param privateKeyPath
	 *          私鑰證書文件位置
	 * @return
	 */
	public static String createSign(String inStr, String privateKeyPath) {
		String returnSign = null;
		logger.info("生成簽名,私鑰證書地址:" + privateKeyPath);
		PrivateKey pk = getPk(privateKeyPath);
		byte[] signData;
		try {
			signData = sign(pk, inStr.getBytes("UTF-8"));
			returnSign = Base64.encode(signData);
		} catch (UnsupportedEncodingException e) {
			logger.error( "生成簽名異常,字符轉換失敗", e);
		}
        logger.info(String.format("明文串[%s],加密串[%s]", inStr, returnSign));
		return returnSign;
	}
	/***
	 * 獲取私鑰對象
	 * @param pkPath 私鑰路徑
	 * @return
	 */
	public static PrivateKey getPk(String pkPath) {
		PrivateKey pk = pkMap.get(pkPath);
		if (null != pk)
			return pk;
		try {
			pk = loadPrivateKey(pkPath);
			pkMap.put(pkPath, pk);
            logger.info(String.format("load pk ok %s",pkPath));
		} catch (Exception e) {
			RuntimeException rex = new RuntimeException(e.getMessage());
			rex.setStackTrace(e.getStackTrace());
			throw rex;
		} 
		return pk;
	}

	/**
	 * <br>description : 加載證書文件
	 *
	 * @version 1.0
	 */
	private static PrivateKey loadPrivateKey(String privateKeyPath) {
		PrivateKey privateKey = null;
		//System.out.println("loadPrivateKey:::" + privateKeyPath);
		InputStream in = null;

		try {
			byte[] b = new byte[4096];
			File file = ResourceUtils.getFile(privateKeyPath);
//			in = RsaSignUtil.class.getClassLoader().getResourceAsStream(privateKeyPath);
			in = new FileInputStream(file);
			in.read(b);
			PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec(b);
			KeyFactory kf = KeyFactory.getInstance("RSA");
			privateKey = kf.generatePrivate(peks);

		} catch (Exception ex) {
			logger.error("加載證書異常", ex);
			return null;
		} finally {
			try {
				if (null != in)
					in.close();
			} catch (Exception ex) {
				;
			}
		}
		return privateKey;

	}

}

測試類:

package com.umpay.util;

import com.umpay.utils.RsaSignUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SignUtils {
    @Test
    public void contextLoads() {

//        String path = "E:\\sercurity\\testUmpay.key.p8";
        String path = "classpath:sercurity/testUmpay.key.p8";

        System.out.println(RsaSignUtil.createSign("adasdf", path));

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章