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;
    }

}

 

你可能感兴趣的:(java)