公钥加密-私钥解密(RSA)

注意在导入该jar的时候:

it.sauronsoftware.base64.Base64

到该地址进行下载:

http://www.sauronsoftware.it/projects/javabase64/manual.php



代码实现:

package com.et.TL.parctice.encryption;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
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;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import it.sauronsoftware.base64.Base64;
import sun.misc.BASE64Encoder;

public class EncryptionUtils {

	/**
	 * 明文
	 */
	private final static String sourceString = "七里我是七里我是中国人,好不,好不好,你说呢,可以行呀中国人,好不,好不好,你说呢,可以行呀";
	private final static String PUBLIC_KEY = "publicRsa";
	private final static String PRIVATE_KEY = "privateRsa";
	private final static String KEY_ALGORITHM = "RSA";
	/** 
     * RSA最大加密明文大小 
     */  
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /** 
     * RSA最大解密密文大小 
     */  
    private static final int MAX_DECRYPT_BLOCK = 128; 
	
	//私钥
	private static String private_aa = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKF5yDP+6IEzYoUfp2Mb0FP538BGyufWbRlErFBxY6LwC4uuY4wkzl/sflTcTtHsoiRxLyBnImW8xlk3VIHlT3QOp9ZV6VZtDIGaY8b0cEI7yuf9Vy4aET3NK+EWTUJnmAcml19eUWzbMaQvndMI+qOoMBhU4Ch1Roo6RIBXxbzDAgMBAAECgYARivmFLJx17O83J0k4Kz1m4i685PQGW/VeWWefFbKNcSbP9hI6l4UURs0yyvyFMgArlWBZVNsX0np6FtjHg/ItrQxm/vczTr/plyhA9GjqeW7TVG1/PbSS7fcRmK5nkwM1JBdHhiDC+dprUzBYKo5KAjZKxpeKF4Xe1CNTf0xkgQJBAOoEzcc7LrPxyy/tddUeruJ9Y/XKf7Vss0rA8nSvhAJh7sB0GLX/0rPr9VXs5axtAwyYiA3eCavzGbMKE3W0M68CQQCwpJ0ld/89TZzZbNIa79FlDKAZ7cWTrbkEElrLCU/j9fIrAzfLHOycuSDXi7NxB/+C2Bp08pAmhdX+O+BrkIktAkBmMFbTawqH1UwOz7imqdFgYbTmvdhqlt7sA7lcLtCMYctqCshHoUCXBLCLJvlcA/ZS58BxncXHak6MmhfJTDlNAkAYsGlme0cpgleR7CvRqANUZFdcSGd9JKLfdtFJ35tS+WVHrcN2mCxaG2YDunryKXQFDb9k6SJMwBgQ2L2dSy5hAkEA1hCO8kyc8e2PQJLvs7Yyx8Mr8Jryuw12NRHS7iesuTuBo1yLkZuUQ93hC/TQ1xpxd7v4BJafLOJDYkmQv5uKaA==";
	//公钥
	private static String public_bb = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChecgz/uiBM2KFH6djG9BT+d/ARsrn1m0ZRKxQcWOi8AuLrmOMJM5f7H5U3E7R7KIkcS8gZyJlvMZZN1SB5U90DqfWVelWbQyBmmPG9HBCO8rn/VcuGhE9zSvhFk1CZ5gHJpdfXlFs2zGkL53TCPqjqDAYVOAodUaKOkSAV8W8wwIDAQAB";
	
	/**
	 * 公钥加密
	 * @return
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeySpecException 
	 * @throws NoSuchPaddingException 
	 * @throws InvalidKeyException 
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException 
	 * @throws IOException 
	 */
	public static byte[] encryption() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException{
		//将明文转换为字节数组
		byte[] sourceByte = sourceString.getBytes();
		
		byte[] keyBytes = Base64.decode(public_bb.getBytes());
		
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		
		//通过RSA来加密
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		
		//对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
        cipher.init(Cipher.ENCRYPT_MODE, publicK);  
        int inputLen = sourceByte.length;  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        int offSet = 0;  
        byte[] cache;  
        int i = 0;  
        // 对数据分段加密  
        while (inputLen - offSet > 0) {  
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {  
                cache = cipher.doFinal(sourceByte, offSet, MAX_ENCRYPT_BLOCK);  
            } else {  
                cache = cipher.doFinal(sourceByte, offSet, inputLen - offSet);  
            }  
            out.write(cache, 0, cache.length);  
            i++;  
            offSet = i * MAX_ENCRYPT_BLOCK;  
        }  
        byte[] encryptedData = out.toByteArray();  
        out.close(); 
        
		return encryptedData;
	}
	
	/**
	 * 测试
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		Map map = initKey();
		//获取私钥
		String priStr = getPrivateKey(map);
		//获取公钥
		String pubStr = getPublicKey(map);
		System.out.println("公钥:"+pubStr);
		System.out.println("私钥:"+priStr);
		System.out.println("-----------------------------------------------------------");
		System.out.println("未加密前的明文:"+sourceString);
		System.out.println("=============================================================");
		System.out.println("加密后:"+new String(encryption()));
		System.out.println("=============================================================");
		System.out.println("解密后:"+new String(decode(encryption())));
	}
	
	/**
	 * 私钥解密
	 * @return
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeySpecException 
	 * @throws NoSuchPaddingException 
	 * @throws InvalidKeyException 
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException 
	 * @throws IOException 
	 */
	public static byte[] decode(byte[] encryptedData) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException{
		
		byte[] keyBytes = Base64.decode(private_aa.getBytes());
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
        cipher.init(Cipher.DECRYPT_MODE, privateK);  
        int inputLen = encryptedData.length;  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        int offSet = 0;  
        byte[] cache;  
        int i = 0;  
        // 对数据分段解密  
        while (inputLen - offSet > 0) {  
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {  
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);  
            } else {  
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);  
            }  
            out.write(cache, 0, cache.length);  
            i++;  
            offSet = i * MAX_DECRYPT_BLOCK;  
        }  
        byte[] decryptedData = out.toByteArray();  
        out.close();
		return decryptedData;
	}
	
	//获得公钥
    public static String getPublicKey(Map keyMap) throws Exception {
        //获得map中的公钥对象 转为key对象
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        //byte[] publicKey = key.getEncoded();
        //编码返回字符串
        return (new BASE64Encoder().encodeBuffer(key.getEncoded()));
    }
    
    //获得私钥
    public static String getPrivateKey(Map keyMap) throws Exception {
        //获得map中的私钥对象 转为key对象
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        //byte[] privateKey = key.getEncoded();
        //编码返回字符串
        return (new BASE64Encoder()).encodeBuffer(key.getEncoded());
    }
	
	//map对象中存放公私钥
    public static Map initKey() throws Exception {
        //获得对象 KeyPairGenerator 参数 RSA 1024个字节
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        //通过对象 KeyPairGenerator 获取对象KeyPair
        KeyPair keyPair = keyPairGen.generateKeyPair();
        
        //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //公私钥对象存入map中
        Map keyMap = new HashMap(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }
}


你可能感兴趣的:(公钥加密-私钥解密)