Java加密技术(三)

接下来我们介绍非对称加密算法,RSA
RSA
    这种算法1978年就出现了,它是第一个既能用于数据加密也能用于数字签名的算法。它易于理解和操作,也很流行。算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman。
    这种加密算法的特点主要是密钥的变化,上文我们看到DES只有一个密钥。相当于只有一把钥匙,如果这把钥匙丢了,数据也就不安全了。RSA同时有两把钥匙,公钥与私钥。
    公钥公开,私钥保密。我们用公钥加密数据,用私钥解密数据,最常用作为数字签名。
通过java代码实现如下:

Java代码 复制代码
  1. import java.security.Key;   
  2. import java.security.KeyFactory;   
  3. import java.security.KeyPair;   
  4. import java.security.KeyPairGenerator;   
  5. import java.security.interfaces.RSAPrivateKey;   
  6. import java.security.interfaces.RSAPublicKey;   
  7. import java.security.spec.PKCS8EncodedKeySpec;   
  8. import java.security.spec.X509EncodedKeySpec;   
  9.   
  10. import java.util.HashMap;   
  11. import java.util.Map;   
  12.   
  13. import javax.crypto.Cipher;   
  14.   
  15. /**  
  16.  * RSA安全编码组件  
  17.  *   
  18.  * @author 梁栋  
  19.  * @version 1.0  
  20.  * @since 1.0  
  21.  */  
  22. public class RSACoder extends Coder {   
  23.     public static final String ALGORITHM = "RSA";   
  24.     private static final String PUBLIC_KEY = "RSAPublicKey";   
  25.     private static final String PRIVATE_KEY = "RSAPrivateKey";   
  26.   
  27.     /**  
  28.      * 解密<br>  
  29.      * 用私钥解密  
  30.      *   
  31.      * @param data  
  32.      * @param key  
  33.      * @return  
  34.      * @throws Exception  
  35.      */  
  36.     public static byte[] decrypt(byte[] data, String key) throws Exception {   
  37.         // 对密钥解密   
  38.         byte[] keyBytes = decryptBASE64(key);   
  39.   
  40.         // 取得私钥   
  41.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);   
  42.         KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);   
  43.         Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);   
  44.   
  45.         // 对数据解密   
  46.         Cipher cipher = Cipher.getInstance(ALGORITHM);   
  47.         cipher.init(Cipher.DECRYPT_MODE, privateKey);   
  48.   
  49.         return cipher.doFinal(data);   
  50.     }   
  51.   
  52.     /**  
  53.      * 加密<br>  
  54.      * 用公钥加密  
  55.      *   
  56.      * @param data  
  57.      * @param key  
  58.      * @return  
  59.      * @throws Exception  
  60.      */  
  61.     public static byte[] encrypt(byte[] data, String key) throws Exception {   
  62.         // 对公钥解密   
  63.         byte[] keyBytes = decryptBASE64(key);   
  64.   
  65.         // 取得公钥   
  66.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);   
  67.         KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);   
  68.         Key publicKey = keyFactory.generatePublic(x509KeySpec);   
  69.   
  70.         // 对数据加密   
  71.         Cipher cipher = Cipher.getInstance(ALGORITHM);   
  72.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);   
  73.   
  74.         return cipher.doFinal(data);   
  75.     }   
  76.   
  77.     /**  
  78.      * 取得私钥  
  79.      *   
  80.      * @param keyMap  
  81.      * @return  
  82.      * @throws Exception  
  83.      */  
  84.     public static String getPrivateKey(Map<String, Object> keyMap)   
  85.             throws Exception {   
  86.         Key key = (Key) keyMap.get(PRIVATE_KEY);   
  87.   
  88.         return encryptBASE64(key.getEncoded());   
  89.     }   
  90.   
  91.     /**  
  92.      * 取得公钥  
  93.      *   
  94.      * @param keyMap  
  95.      * @return  
  96.      * @throws Exception  
  97.      */  
  98.     public static String getPublicKey(Map<String, Object> keyMap)   
  99.             throws Exception {   
  100.         Key key = (Key) keyMap.get(PUBLIC_KEY);   
  101.   
  102.         return encryptBASE64(key.getEncoded());   
  103.     }   
  104.   
  105.     /**  
  106.      * 初始化密钥  
  107.      *   
  108.      * @return  
  109.      * @throws Exception  
  110.      */  
  111.     public static Map<String, Object> initKey() throws Exception {   
  112.         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);   
  113.         keyPairGen.initialize(1024);   
  114.   
  115.         KeyPair keyPair = keyPairGen.generateKeyPair();   
  116.   
  117.         // 公钥   
  118.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();   
  119.   
  120.         // 私钥   
  121.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   
  122.   
  123.         Map<String, Object> keyMap = new HashMap<String, Object>(2);   
  124.   
  125.         keyMap.put(PUBLIC_KEY, publicKey);   
  126.         keyMap.put(PRIVATE_KEY, privateKey);   
  127.   
  128.         return keyMap;   
  129.     }   
  130. }  
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
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 javax.crypto.Cipher;

/**
 * RSA安全编码组件
 * 
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 */
public class RSACoder extends Coder {
	public static final String ALGORITHM = "RSA";
	private static final String PUBLIC_KEY = "RSAPublicKey";
	private static final String PRIVATE_KEY = "RSAPrivateKey";

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

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

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

		return cipher.doFinal(data);
	}

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

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

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

		return cipher.doFinal(data);
	}

	/**
	 * 取得私钥
	 * 
	 * @param keyMap
	 * @return
	 * @throws Exception
	 */
	public static String getPrivateKey(Map<String, Object> keyMap)
			throws Exception {
		Key key = (Key) keyMap.get(PRIVATE_KEY);

		return encryptBASE64(key.getEncoded());
	}

	/**
	 * 取得公钥
	 * 
	 * @param keyMap
	 * @return
	 * @throws Exception
	 */
	public static String getPublicKey(Map<String, Object> keyMap)
			throws Exception {
		Key key = (Key) keyMap.get(PUBLIC_KEY);

		return encryptBASE64(key.getEncoded());
	}

	/**
	 * 初始化密钥
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> initKey() throws Exception {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
		keyPairGen.initialize(1024);

		KeyPair keyPair = keyPairGen.generateKeyPair();

		// 公钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

		// 私钥
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

		Map<String, Object> keyMap = new HashMap<String, Object>(2);

		keyMap.put(PUBLIC_KEY, publicKey);
		keyMap.put(PRIVATE_KEY, privateKey);

		return keyMap;
	}
}


再给出一个测试类:

Java代码 复制代码
  1. import static org.junit.Assert.*;   
  2.   
  3. import org.junit.Test;   
  4.   
  5. import org.zlex.commons.io.IOUtils;   
  6.   
  7. import java.util.Map;   
  8.   
  9. /**  
  10.  *   
  11.  * @author 梁栋  
  12.  * @version 1.0  
  13.  * @since 1.0  
  14.  */  
  15. public class RSACoderTest {   
  16.     @Test  
  17.     public void test() throws Exception {   
  18.         String inputStr = "abc";   
  19.         byte[] data = inputStr.getBytes();   
  20.   
  21.         Map<String, Object> keyMap = RSACoder.initKey();   
  22.   
  23.         String publicKey = RSACoder.getPublicKey(keyMap);   
  24.         String privateKey = RSACoder.getPrivateKey(keyMap);   
  25.         System.err.println("publicKey: \n\r" + publicKey);   
  26.         System.err.println("privateKey: \n\r" + privateKey);   
  27.   
  28.         byte[] encodedData = RSACoder.encrypt(data, publicKey);   
  29.   
  30.         byte[] decodedData = RSACoder.decrypt(encodedData, privateKey);   
  31.         String outputStr = new String(decodedData);   
  32.         System.err.println("inputStr: " + inputStr + "\n\r" + "outputStr: "  
  33.                 + outputStr);   
  34.         assertEquals(inputStr, outputStr);   
  35.     }   
  36. }  
import static org.junit.Assert.*;

import org.junit.Test;

import org.zlex.commons.io.IOUtils;

import java.util.Map;

/**
 * 
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 */
public class RSACoderTest {
	@Test
	public void test() throws Exception {
		String inputStr = "abc";
		byte[] data = inputStr.getBytes();

		Map<String, Object> keyMap = RSACoder.initKey();

		String publicKey = RSACoder.getPublicKey(keyMap);
		String privateKey = RSACoder.getPrivateKey(keyMap);
		System.err.println("publicKey: \n\r" + publicKey);
		System.err.println("privateKey: \n\r" + privateKey);

		byte[] encodedData = RSACoder.encrypt(data, publicKey);

		byte[] decodedData = RSACoder.decrypt(encodedData, privateKey);
		String outputStr = new String(decodedData);
		System.err.println("inputStr: " + inputStr + "\n\r" + "outputStr: "
				+ outputStr);
		assertEquals(inputStr, outputStr);
	}
}


控制台输出:

Console代码 复制代码
  1. publicKey:    
  2.   
  3. MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCynMFQnRG1ZwfewDxaNDvFskU8zC1R6Uxq7hk+   
  4. 0eaUHU/6Yi5kYWU1LJkkw23PvTq1JJ9XfunSWP2q2HlNCGQ+802MGXh5N3tikRIcA4XIehPwTTdN   
  5. 5Gzvohh39N5lOL9X/TPhMIFtRzCaVWYpz/allDlB9SlJ+/pmYo37H5cIyQIDAQAB   
  6.   
  7. privateKey:    
  8.   
  9. MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBALKcwVCdEbVnB97APFo0O8WyRTzM   
  10. LVHpTGruGT7R5pQdT/piLmRhZTUsmSTDbc+9OrUkn1d+6dJY/arYeU0IZD7zTYwZeHk3e2KREhwD   
  11. hch6E/BNN03kbO+iGHf03mU4v1f9M+EwgW1HMJpVZinP9qWUOUH1KUn7+mZijfsflwjJAgMBAAEC   
  12. gYEAmQbOZVe89VNpncHLs2jvEQkUYut3pKciLrcB8B171MhsXlPB9YSwZmdoaeP58DLq2ome7yKw   
  13. B+TwqHBBNOuMnifeSSNMusqwQ34rq0d9cuYMIAN2L5RieTL8kWZ5FVWk0JlugjnrK7x6asVAUJIW   
  14. smZnlaga51s20jDsixhgPlECQQDb5IqC4VtaY+tE3Re9e1rkRkJhQmO1AQhWS14YMyEyzDrP0cbx   
  15. Iezpszl+nXnskAJ8ZSng/TpUf3NH8H+Wj9MdAkEAz/DxDuD8aQCo2cgbUMifOFCfQ/RtP68sW7Wq   
  16. GrNa01YSihBqR44gWkCAW+M+67TtVz1BBKUolqauOSeQu1fQnQJBANZd3LJvI/HgyvFdYNF2Okuk   
  17. Ov46DJ3endQSsW6CGfE9rHABICLfYekKshg/SSdX1TSUItmVxJGvliEh0iBjofkCQQDCKU5NAFNv   
  18. kEgZojmvQsU5Bj7Qawkfr+eRcp109QfX0cTZ2d4DFnirDRNNuXDlEjmTfgSZ28V8dgK0J3eDFsoZ   
  19. AkEAoHgdGs1rrhSrFLzQB4F0t2JqYNkzCFbvIV4rWXZ10pbBABxnbLz25bxbm0fQfcA4OPzTwn54   
  20. nqbV2AUEyHaNug==   
  21.   
  22. inputStr: abc   
  23.   
  24. outputStr: abc  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值