1. 程式人生 > >RSA演算法的Java實現及Base64的正確使用

RSA演算法的Java實現及Base64的正確使用

遇到的問題:
    今天參考他人程式碼實現了一下RSA演算法。遇到一個問題,網上的RSA工具類中的核心方法大多是需要傳入byte[]陣列進行處理,而不能直接傳入String進行處理,這裡對byte[]的處理部分進行了完全的封裝,使使用者的傳入引數完全String化。大大簡化了工具類的使用

    這其中關鍵是需要用到Base64對String和byte[]進行互轉。

Base64的jar包下載地址:http://download.csdn.net/detail/ldld1717/9772776

核心程式碼:

package RSARSA;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

public class RSATest {
	// 數字簽名,金鑰演算法
	private static final String RSA_KEY_ALGORITHM = "RSA";

	// 數字簽名簽名/驗證演算法
	private static final String SIGNATURE_ALGORITHM = "MD5withRSA";

	// RSA金鑰長度
	private static final int KEY_SIZE = 1024;
	
	private static final String PUBLIC_KEY = "publicKey";
	private static final String PRIVATE_KEY = "privateKey";

	/**
	 * 初始化RSA金鑰對
	 * @return RSA金鑰對
	 * @throws Exception 丟擲異常
	 */
	private static Map<String, String> initKey() throws Exception {
		KeyPairGenerator keygen = KeyPairGenerator
				.getInstance(RSA_KEY_ALGORITHM);
		SecureRandom secrand = new SecureRandom();
		secrand.setSeed("hahaha".getBytes());// 初始化隨機產生器
		keygen.initialize(KEY_SIZE, secrand); // 初始化金鑰生成器
		KeyPair keys = keygen.genKeyPair();
		String pub_key = Base64.encodeBase64String(keys.getPublic().getEncoded());
		String pri_key = Base64.encodeBase64String(keys.getPrivate().getEncoded());
		Map<String, String> keyMap = new HashMap<String, String>();
		keyMap.put(PUBLIC_KEY, pub_key);
		keyMap.put(PRIVATE_KEY, pri_key);
		System.out.println("公鑰:" + pub_key);
		System.out.println("私鑰:" + pri_key);
		return keyMap;
	}
	
    /**
     * 得到公鑰
     * @param keyMap RSA金鑰對
     * @return 公鑰
     * @throws Exception 丟擲異常
     */
	public static String getPublicKey(Map<String, String> keyMap) throws Exception{
		return keyMap.get(PUBLIC_KEY);
	}
	
	/**
	 * 得到私鑰
	 * @param keyMap RSA金鑰對
	 * @return 私鑰
	 * @throws Exception 丟擲異常
	 */
	public static String getPrivateKey(Map<String, String> keyMap) throws Exception{
		return keyMap.get(PRIVATE_KEY);
	}

	/**
	 * 數字簽名
	 * @param data 待簽名資料
	 * @param pri_key 私鑰
	 * @return 簽名
	 * @throws Exception 丟擲異常
	 */
	public static String sign(byte[] data, String pri_key) throws Exception {
		// 取得私鑰
		byte[] pri_key_bytes = Base64.decodeBase64(pri_key);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri_key_bytes);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
		// 生成私鑰
		PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
		// 例項化Signature
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		// 初始化Signature
		signature.initSign(priKey);
		// 更新
		signature.update(data);

		return Base64.encodeBase64String(signature.sign());
	}

	/**
	 * RSA校驗數字簽名
	 * @param data 資料
	 * @param sign 簽名
	 * @param pub_key 公鑰
	 * @return 校驗結果,成功為true,失敗為false
	 * @throws Exception 丟擲異常
	 */
	public boolean verify(byte[] data, byte[] sign, String pub_key) throws Exception {
		// 轉換公鑰材料
		// 例項化金鑰工廠
		byte[] pub_key_bytes = Base64.decodeBase64(pub_key);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
		// 初始化公鑰
		// 金鑰材料轉換
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub_key_bytes);
		// 產生公鑰
		PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
		// 例項化Signature
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		// 初始化Signature
		signature.initVerify(pubKey);
		// 更新
		signature.update(data);
		// 驗證
		return signature.verify(sign);
	}

	/**
	 * 公鑰加密
	 * @param data 待加密資料
	 * @param pub_key 公鑰
	 * @return 密文
	 * @throws Exception 丟擲異常
	 */
	private static byte[] encryptByPubKey(byte[] data, byte[] pub_key) throws Exception {
		// 取得公鑰
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub_key);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
		PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
		// 對資料加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		return cipher.doFinal(data);
	}

	/**
	 * 公鑰加密
	 * @param data 待加密資料
	 * @param pub_key 公鑰
	 * @return 密文
	 * @throws Exception 丟擲異常
	 */
	public static String encryptByPubKey(String data, String pub_key) throws Exception {
		// 私匙加密
		byte[] pub_key_bytes = Base64.decodeBase64(pub_key);
		byte[] enSign = encryptByPubKey(data.getBytes(), pub_key_bytes);
		return Base64.encodeBase64String(enSign);
	}

	/**
	 * 私鑰加密
	 * @param data 待加密資料
	 * @param pri_key 私鑰
	 * @return 密文
	 * @throws Exception 丟擲異常
	 */
	private static byte[] encryptByPriKey(byte[] data, byte[] pri_key) throws Exception {
		// 取得私鑰
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri_key);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
		// 對資料加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		return cipher.doFinal(data);
	}

	/**
	 * 私鑰加密
	 * @param data 待加密資料
	 * @param pri_key 私鑰
	 * @return 密文
	 * @throws Exception 丟擲異常
	 */
	public static String encryptByPriKey(String data, String pri_key) throws Exception {
		// 私匙加密
		byte[] pri_key_bytes = Base64.decodeBase64(pri_key);
		byte[] enSign = encryptByPriKey(data.getBytes(), pri_key_bytes);
		return Base64.encodeBase64String(enSign);
	}

	/**
	 * 公鑰解密
	 * @param data 待解密資料
	 * @param pub_key 公鑰
	 * @return 明文
	 * @throws Exception 丟擲異常
	 */
	private static byte[] decryptByPubKey(byte[] data, byte[] pub_key) throws Exception {
		// 取得公鑰
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub_key);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
		PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
		// 對資料解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
		return cipher.doFinal(data);
	}

	/**
	 * 公鑰解密
	 * @param data 待解密資料
	 * @param pub_key 公鑰
	 * @return 明文
	 * @throws Exception 丟擲異常
	 */
	public static String decryptByPubKey(String data, String pub_key) throws Exception {
		// 公匙解密
		byte[] pub_key_bytes = Base64.decodeBase64(pub_key);
		byte[] design = decryptByPubKey(Base64.decodeBase64(data), pub_key_bytes);
		return new String(design);
	}

	/**
	 * 私鑰解密
	 * @param data 待解密資料
	 * @param pri_key 私鑰
	 * @return 明文
	 * @throws Exception 丟擲異常
	 */
	private static byte[] decryptByPriKey(byte[] data, byte[] pri_key) throws Exception {
		// 取得私鑰
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri_key);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
		// 對資料解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return cipher.doFinal(data);
	}

	/**
	 * 私鑰解密
	 * @param data 待解密資料
	 * @param pri_key 私鑰
	 * @return 明文
	 * @throws Exception 丟擲異常
	 */
	public static String decryptByPriKey(String data, String pri_key) throws Exception {
		// 私匙解密
		byte[] pri_key_bytes = Base64.decodeBase64(pri_key);
		byte[] design = decryptByPriKey(Base64.decodeBase64(data), pri_key_bytes);
		return new String(design);
	}

	/**
	 * @param args
	 */
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws Exception {

		RSATest das = new RSATest();

		String datastr = "天街小雨潤如酥,草色遙看近卻無。最是一年春好處,絕勝煙柳滿皇都。";
		System.out.println("待加密資料:\n" + datastr);
		//獲取金鑰對
		Map<String, String> keyMap = new HashMap<String, String>();
		keyMap = das.initKey();
		String pub_key = (String) keyMap.get(PUBLIC_KEY);
		String pri_key = (String) keyMap.get(PRIVATE_KEY);
		// 公匙加密
		String pubKeyStr = RSATest.encryptByPubKey(datastr, pub_key);
		System.out.println("公匙加密結果:\n" + pubKeyStr);
		// 私匙解密
		String priKeyStr = RSATest.decryptByPriKey(pubKeyStr, pri_key);
		System.out.println("私匙解密結果:\n" + priKeyStr);

		//換行
		System.out.println();
		
		// 數字簽名
		String str1 = "漢兵已略地";
		String str2 = "四面楚歌聲";
		System.out.println("正確的簽名:" + str1 + "\n錯誤的簽名:" + str2);
		String sign = RSATest.sign(str1.getBytes(), pri_key);
		System.out.println("數字簽名:\n" + sign);
		boolean vflag1 = das.verify(str1.getBytes(), Base64.decodeBase64(sign), pub_key);
		System.out.println("數字簽名驗證結果1:\n" + vflag1);
		boolean vflag2 = das.verify(str2.getBytes(), Base64.decodeBase64(sign), pub_key);
		System.out.println("數字簽名驗證結果2:\n" + vflag2);
	}
}

這其中有必要對Base64的用法做一點提煉:

    1.byte[]轉為String用到Base64.encodeBase64String(傳待轉的byte陣列)方法;

    2.String轉byte[]用到Base64.decodeBase64(傳待轉的字串)方法;

    3.以上兩步若實現byte[]--->-String-->byte[],則byte[]不變,也不會有亂碼,所以Base64還是非常好用的。

實驗結果:


實驗結果完全符合預期。