RSA加密解密

package com.bjsasc.szcloud.util;

import static org.junit.Assert.assertEquals;

import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Encode {
	public static final String KEY_ALGORITHM = "RSA";
	
	/**
	 * 加密<br>
	 * 用公钥加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptByPublicKey(byte[] data, String key)
			throws Exception {
		// 对公钥解密
		byte[] keyBytes = decryptBASE64(key);

		// 取得公钥
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicKey = keyFactory.generatePublic(x509KeySpec);

		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);

		return cipher.doFinal(data);
	}
	
	/**
	 * 解密<br>
	 * 用私钥解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(byte[] data, String key)
			throws Exception {
		// 对密钥解密
		byte[] keyBytes = decryptBASE64(key);

		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateKey);

		return cipher.doFinal(data);
	}
	
	/**
	 * BASE64解密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptBASE64(String key) throws Exception {
		return (new BASE64Decoder()).decodeBuffer(key);
	}

	/**
	 * BASE64加密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptBASE64(byte[] key) throws Exception {
		return (new BASE64Encoder()).encodeBuffer(key);
	}
	
	public static String toUTFString(byte[] str) throws Exception {
		return new String(str,"UTF-8");
	}
	
	public static void main(String[] args) throws Exception{
		System.err.println("公钥加密——私钥解密");
		String inputStr = "abfdsfdsfdsfdsc";
		String publicKey= "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJpUSS4d0vMBfDCIFg2kQOycrn1v6NNDNmzOIv3NyVe6"
		        +"8gRwE74pKk7mQ8hPpreAkx14bOoL/R1l5pDd8sT7PCsCAwEAAQ==";
        String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAmlRJLh3S8wF8MIgWDaRA7JyufW/o"
        		+"00M2bM4i/c3JV7ryBHATvikqTuZDyE+mt4CTHXhs6gv9HWXmkN3yxPs8KwIDAQABAkEAlV/paQqS"
        		+"6IRSeQLvHYsTEDHjLiRIXVtb7VpkQfaR4CffEuzEk2IBsIv+Pk6G+ZwfbBohmz+F1T1giWEv4EPM"
        		+"8QIhANetV+ojkIUxbP/62B1j0WUPt/yRJkaMdrkSj1eunCADAiEAty67wwv0R9B3/5v4JpdzyRtC"
        		+"3Q6M1VoSRw6M0ODNXrkCIHE/R+ZdfkkxxrYylL/55b1XH5iy7pIkt0I+iJ3VxYzZAiEAsDhO/HXV"
        		+"i/hqWAVtFYMBKegFzK6goOZDSwQeRxrbtlECIGUKy3KOs8XOS/5jL/2mKvzIQFQSGPnhyQibsMY0"
        		+"MHUH";
		        
		byte[] data = inputStr.getBytes();

		byte[] encodedData = encryptByPublicKey(data, publicKey);
		
		String code64 = null;
        try {
        	code64 = encryptBASE64(encodedData);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("code64 = "+code64);
		
		byte[] decode64 = null;
        try {
        	decode64 = decryptBASE64(code64);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		byte[] decodedData = decryptByPrivateKey(decode64,
				privateKey);
		String outputStr = toUTFString(decodedData);
		System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + toUTFString(decodedData));
		assertEquals(inputStr, outputStr);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值