RSA驗籤

 RSA驗籤,祕鑰由文件中讀取,與加密解密的方法不一樣。


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class SecurityUtils {
	/**
	 * 私鑰
	 */
	public static PrivateKey privateKey;
	/**
	 * 公鑰
	 */
	public static PublicKey publicKey;
	/**
	 * 私鑰文件路徑 如:D:/rsa/prkey.key
	 */
	private static String privateKeyPath=SecurityUtils.class.getClassLoader().getResource("").getPath()+"static/";
	
	/**
	 * 公鑰文件路徑 如:D:/rsa/pbkey.key
	 */
	private static String publicKeyPath=SecurityUtils.class.getClassLoader().getResource("").getPath()+"static/";
	
	
	
	static {
		  try {
	            java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
	        }
	        catch (Exception e) {
	        	e.printStackTrace();
	        	System.out.println("密鑰初始化失敗");
	        }
	}
	/**
	 *  init:初始化私鑰
	 */
	public static void initPrivateKey(String prkeyName){
		try {
				if(privateKey==null){
					privateKey = getPrivateKey(privateKeyPath+prkeyName);
				}
		} catch (Exception e) {
			System.out.println("SecurityUtils初始化失敗" + e.getMessage());
			e.printStackTrace();
			System.out.println("密鑰初始化失敗");
		}
	}
	/**
	 * 初始化公鑰
	 */
	public static void initPublicKey(String pbkeyName){
		try {
			if(publicKey==null){
				publicKey = getPublicKey(publicKeyPath+pbkeyName);
			}
		} catch (Exception e) {
			System.out.println("SecurityUtils初始化失敗" + e.getMessage());
			e.printStackTrace();
			System.out.println("密鑰初始化失敗");
		}
	}
	/**
	 * 對傳入字符串進行簽名
	 * @param inputStr
	 * @return
	 * @ 
	 */
	public static String sign(String inputStr) {
		String result = null;
		  try {
			    if(privateKey==null){
			    	//初始化
			    	initPrivateKey("prkey.key");
			    }
	            byte[] tByte;
	            Signature signature = Signature.getInstance("SHA1withRSA","BC");
	            signature.initSign(privateKey);
	            signature.update(inputStr.getBytes("UTF-8"));
	            tByte = signature.sign();
			  	result = Base64.encode(tByte);
		  }
	        catch (Exception e) {
	        	e.printStackTrace();
	        	System.out.println("密鑰初始化失敗");
	        }
		return result;
	}
	/**
	 * 返回的數據進行驗籤
	 * @param src 返回數據明文
	 * @param signValue 返回數據簽名
	 * @return
	 */
	public static boolean verifySign(String src,String signValue) {
		  boolean bool = false;
		  try {
			  	if(publicKey==null){
			  		initPublicKey("pbkey.key");
				}
	            Signature signature = Signature.getInstance("SHA1withRSA","BC");
	            signature.initVerify(publicKey);
	            signature.update(src.getBytes("UTF-8"));
	            bool = signature.verify(Base64.decode(signValue));
	        }
	        catch (Exception e) {
	        	e.printStackTrace();
	        	System.out.println("密鑰初始化失敗");
	        }
		return bool;
	}
	private static PrivateKey getPrivateKey(String filePath) {
		String base64edKey = readFile(filePath);
		KeyFactory kf;
		PrivateKey privateKey = null;
		try {
			kf = KeyFactory.getInstance("RSA", "BC");
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(base64edKey));
			privateKey = kf.generatePrivate(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("密鑰初始化失敗");
		}
		return privateKey;
	}
	private static PublicKey getPublicKey(String filePath){
		String base64edKey = readFile(filePath);
		KeyFactory kf;
		PublicKey   publickey = null;
		try {
			kf = KeyFactory.getInstance("RSA", "BC"); 
			X509EncodedKeySpec   keySpec   =   new   X509EncodedKeySpec(Base64.decode(base64edKey));
			publickey   =   kf.generatePublic(keySpec);   
		 } catch (Exception e) {
			e.printStackTrace();
			System.out.println("密鑰初始化失敗");
		}
		return publickey;
	}
	private static String readFile(String fileName) {
      try {
      	File f = new File(fileName);
          FileInputStream in = new FileInputStream(f);
          int len = (int)f.length();
          
          byte[] data = new byte[len];
          int read = 0;
          while (read <len) {
              read += in.read(data, read, len-read);
          }
          in.close();
          return new String(data);
      } catch (IOException e) {
          return null;
      }
  }
}

 

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