RSA加解密工具類


import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA加解密工具類
 */
public class RsaUtils {

	 /**
	  * 私鑰簽名
	  * @param priKeyText 64位編碼的私鑰
	  * @param plainText 明文
	  * @return
	  */
	 public static String sign(String priKeyText, String plainText) {
		  try {
			  //根據base64位編碼私鑰字符串獲取到私鑰
			  RSAPrivateKey privateKey = loadPrivateKeyByStr(priKeyText);
			   // 用私鑰對信息生成數字簽名
			   Signature signet = Signature.getInstance("MD5withRSA");
			   signet.initSign(privateKey);
			   signet.update(plainText.getBytes());
			   byte[] signed = signet.sign();
			   //返回字符集編碼
			   return byte2Hex(signed);
		  } catch (Exception e) {
		   System.out.println("簽名失敗");
		   e.printStackTrace();
		  }
		  return null;
		 }
	 
	 
	 /**
	  * Description:校驗數字簽名,此方法不會拋出任務異常,成功返回true,失敗返回false,要求全部參數不能爲空
	  * @param pubKeyText    公鑰,base64編碼
	  * @param plainText          明文
	  * @param signText           數字簽名的密文(字符集)
	  * @return 校驗成功返回true 失敗返回false
	  */
	 public static boolean verify(String pubKeyText, String plainText, String signText) {
	  try {
		  //加載公鑰
		  RSAPublicKey publickey = loadPublicKeyByStr(pubKeyText);
		   // 解密由base64編碼的數字簽名
		   Signature signatureChecker = Signature.getInstance("MD5withRSA");
		   signatureChecker.initVerify(publickey);
		   signatureChecker.update(plainText.getBytes());
		   // 驗證簽名是否正常
		   if (signatureChecker.verify(hex2Bytes(signText))){
			   return true;
		   }else{
			   return false;
		   }
	  } catch (Throwable e) {
	   System.out.println("校驗簽名失敗");
	   e.printStackTrace();
	   return false;
	  }
	 }
	 
	 /**
	  * 根據私鑰base64位編碼字符串獲取到私鑰
	  * @param privateKeyStr
	  * @return
	  * @throws Exception
	  */
	 public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)throws Exception {
	        try {
	            BASE64Decoder base64Decoder = new BASE64Decoder();
	            byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
	            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
	            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
	        } catch (NoSuchAlgorithmException e) {
	            throw new Exception("無此算法");
	        } catch (InvalidKeySpecException e) {
	            e.printStackTrace();
	            throw new Exception("私鑰非法");
	        } catch (NullPointerException e) {
	            throw new Exception("私鑰數據爲空");
	        }
	    }
	 
	  /**
	     * 從字符串中加載公鑰
	     *
	     * @param publicKeyStr 公鑰數據字符串
	     * @throws Exception 加載公鑰時產生的異常
	     */
	    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception {
	        try {
	            BASE64Decoder base64 = new BASE64Decoder();
	            byte[] buffer = base64.decodeBuffer(publicKeyStr);
	            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
	            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
	        } catch (NoSuchAlgorithmException e) {
	            throw new Exception("無此算法");
	        } catch (InvalidKeySpecException e) {
	            throw new Exception("公鑰非法");
	        } catch (NullPointerException e) {
	            throw new Exception("公鑰數據爲空");
	        }
	    }
	 
	 /**
     * 將byte[] 轉換成字符串
     */
    public static String byte2Hex(byte[] srcBytes) {
        StringBuilder hexRetSB = new StringBuilder();
        for (byte b : srcBytes) {
            String hexString = Integer.toHexString(0x00ff & b);
            hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
        }
        return hexRetSB.toString();
    }
    
    /**
     * 將16進制字符串轉爲轉換成字符串
     */
    public static byte[] hex2Bytes(String source) {
        byte[] sourceBytes = new byte[source.length() / 2];
        for (int i = 0; i < sourceBytes.length; i++) {
            sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
        }
        return sourceBytes;
    }

}

 

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