Java實現RSA非對稱加密工具類

RSA非對稱加密通常運用於對字符串進行加密,通過密鑰對(公鑰、私鑰)實現加密。

通過生成的公鑰,對字符串加密後,得到一個加密的字符串,將私鑰與這個加密後的字符串進行解密,得到原先的字符串。

補充:如果加密的字符串過長,會報錯:javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 byte

這裏在文章後面補充兩個方法用於解決超出117字節加密和126字節解密問題。

Java代碼:

package com.vandet.indwebproject.utils;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.UrlBase64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.security.rsa.RSASignature;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import static com.vandet.indwebproject.test.Test2.KEY_ALGORITHM;

public class RSAUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
    public static final String ENCODING = "utf-8";
    public static final String X509 = "X.509";

    /**
     * 獲取私鑰
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(ENCODING));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 獲取公鑰
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(ENCODING));
        CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
        InputStream in = new ByteArrayInputStream(keyBytes);
        Certificate certificate = certificateFactory.generateCertificate(in);
        PublicKey publicKey = certificate.getPublicKey();
        return publicKey;
    }


    /**
     * 使用公鑰對明文進行加密,返回BASE64編碼的字符串
     *
     * @param publicKey
     * @param plainText
     * @return
     */
    public static String encrypt(String publicKey, String plainText) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            byte[] encodedKey = Base64.decodeBase64(publicKey.getBytes(ENCODING));
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] enBytes = cipher.doFinal(plainText.getBytes());
            return new String(Base64.encodeBase64(enBytes));
        } catch (Exception e) {
            LOGGER.error("rsa encrypt exception: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 使用私鑰對明文密文進行解密
     *
     * @param privateKey
     * @param enStr
     * @return
     */
    public static String decrypt(String privateKey, String enStr) {
        try {
            PrivateKey priKey = getPrivateKey(privateKey);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            byte[] deBytes = cipher.doFinal(Base64.decodeBase64(enStr));
            return new String(deBytes);
        } catch (Exception e) {
            LOGGER.error("rsa decrypt exception: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * RSA私鑰簽名
     *
     * @param content    待簽名數據
     * @param privateKey 私鑰
     * @return 簽名值
     */
    public static String signByPrivateKey(String content, String privateKey) {
        try {
            PrivateKey priKey = getPrivateKey(privateKey);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(priKey);
            signature.update(content.getBytes(ENCODING));
            byte[] signed = signature.sign();
            return new String(UrlBase64.encode(signed), ENCODING);
        } catch (Exception e) {
            LOGGER.error("sign error, content: {}", content, e);
        }
        return null;
    }

    /**
     * 公鑰驗籤
     * @param content
     * @param sign
     * @param publicKey
     * @return
     */
    public static boolean verifySignByPublicKey(String content, String sign, String publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            byte[] encodedKey = Base64.decodeBase64(publicKey.getBytes(ENCODING));
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pubKey);
            signature.update(content.getBytes(ENCODING));

            return signature.verify(UrlBase64.decode(sign.getBytes(ENCODING)));

        } catch (Exception e) {
            LOGGER.error("verify sign error, content: {}, sign: {}", content, sign, e);
        }
        return false;
    }

    /**
     * 隨機生成密鑰對
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        //用於封裝隨機產生的公鑰與私鑰
        Map<String, String> keyMap = new HashMap<String, String>();
        // KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密鑰對生成器,密鑰大小爲96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一個密鑰對,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私鑰
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公鑰
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私鑰字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 將公鑰和私鑰保存到Map
        keyMap.put("publicKey",publicKeyString);  //公鑰
        keyMap.put("privateKey",privateKeyString);  //私鑰
        System.err.println("公鑰:"+keyMap.get("publicKey"));
        System.err.println("私鑰:"+keyMap.get("privateKey"));
    }

}
/** 
	 * RSA公鑰加密 針對長字符串
	 *  
	 * @param str 
	 *            加密字符串
	 * @param publicKey 
	 *            公鑰 
	 * @return 密文 
	 * @throws Exception 
	 *             加密過程中的異常信息 
	 */  
	public static String encrypt( String str, String publicKey ) throws Exception{
		//base64編碼的公鑰
		byte[] decoded = Base64.decodeBase64(publicKey);
		RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
		//RSA加密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
//		String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
		String outStr = null;
		byte[] inputArray = str.getBytes("UTF-8");
		int inputLength = inputArray.length;
		System.out.println("加密字節數:" + inputLength);
		// 最大加密字節數,超出最大字節數需要分組加密
		int MAX_ENCRYPT_BLOCK = 117;
		// 標識
		int offSet = 0;
		byte[] resultBytes = {};
		byte[] cache = {};
		while (inputLength - offSet > 0) {
			if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
				offSet += MAX_ENCRYPT_BLOCK;
			} else {
				cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
				offSet = inputLength;
			}
			resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
			System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
		}
		outStr = Base64.encodeBase64String(resultBytes);
		return outStr;
	}


	/** 
	 * RSA私鑰解密 針對長字符串
	 *  
	 * @param str 
	 *            加密字符串
	 * @param privateKey 
	 *            私鑰 
	 * @return 銘文
	 * @throws Exception 
	 *             解密過程中的異常信息 
	 */  
	public static String decrypt(String str, String privateKey) throws Exception{
		//64位解碼加密後的字符串
		byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
		//base64編碼的私鑰
		byte[] decoded = Base64.decodeBase64(privateKey);  
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));  
		//RSA解密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, priKey);
//		String outStr = new String(cipher.doFinal(inputByte));
		String outStr = null;
		byte[] inputArray = Base64.decodeBase64(str.getBytes("UTF-8"));
		int inputLength = inputArray.length;
		System.out.println("加密字節數:" + inputLength);
		// 最大加密字節數,超出最大字節數需要分組加密
		int MAX_ENCRYPT_BLOCK = 128;
		// 標識
		int offSet = 0;
		byte[] resultBytes = {};
		byte[] cache = {};
		while (inputLength - offSet > 0) {
			if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
				offSet += MAX_ENCRYPT_BLOCK;
			} else {
				cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
				offSet = inputLength;
			}
			resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
			System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
		}
		outStr = new String(resultBytes);
		return outStr;
	}

 

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