﻿package net.oschina.crypto;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA 算法
 * 
 * @author 张大川
 */

public abstract class RSACoder {
	public static final String KEY_ALGORITHM = "RSA";

	public static final String PUBLIC_KEY = "RSAPublicKey";

	public static final String PRIVATE_KEY = "RSAPrivateKey";
	public static final int KEY_SIZE = 512;

	/**
	 *  
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
		//实例化密钥生成器
		KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		generator.initialize(KEY_SIZE);// 1024 512
		KeyPair keyPair = generator.generateKeyPair();
		RSAPublicKey key = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey key2 = (RSAPrivateKey) keyPair.getPrivate();
		Map<String, Object> map = new HashMap<String, Object>(2);
		map.put(PUBLIC_KEY, key);
		map.put(PRIVATE_KEY, key2);
		return map;
	}
	
	
	/**
	 *  生成密钥对
	 * @param i 可选 512 1024
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	
	public static Map<String, Object> initKey(int i) throws NoSuchAlgorithmException {
		//实例化密钥生成器
		KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		generator.initialize(i);// 1024 512
		KeyPair keyPair = generator.generateKeyPair();
		RSAPublicKey key = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey key2 = (RSAPrivateKey) keyPair.getPrivate();
		Map<String, Object> map = new HashMap<String, Object>(2);
		map.put(PUBLIC_KEY, key);
		map.put(PRIVATE_KEY, key2);
		return map;
	}
	
	public static void main(String[] args) throws NoSuchAlgorithmException {
		Map<String, Object> map = RSACoder.initKey(2048);
		System.out.println(map.get(PUBLIC_KEY));

	}

}

@@ -1,5 +1,4 @@
-%EF%BB%BF
 pack
@@ -21,16 +21,16 @@
 crypto;%0A
+
 %0Aimport 
@@ -571,17 +571,16 @@
 /**%0A%09 * 
- 
 %0A%09 * @re
@@ -701,32 +701,33 @@
 Exception %7B%0A%09%09//
+ 
 %E5%AE%9E%E4%BE%8B%E5%8C%96%E5%AF%86%E9%92%A5%E7%94%9F%E6%88%90%E5%99%A8%0A%09%09KeyPa
@@ -1146,20 +1146,17 @@
 %0A%09%7D%0A
-%09%0A%09
 %0A
+
 %09/**%0A%09 *
   %E7%94%9F%E6%88%90
@@ -1155,16 +1155,20 @@
 %0A%09 *
- 
  %E7%94%9F%E6%88%90%E5%AF%86%E9%92%A5%E5%AF%B9%0A
+%09 * %0A
 %09 * 
@@ -1187,16 +1187,21 @@
 512 1024
+ 2048
 %0A%09 * @re
@@ -1247,18 +1247,17 @@
 on%0A%09 */%0A
-%09
 %0A
+
 %09public 
@@ -1336,16 +1336,17 @@
 n %7B%0A%09%09//
+ 
 %E5%AE%9E%E4%BE%8B%E5%8C%96%E5%AF%86%E9%92%A5%E7%94%9F%E6%88%90%E5%99%A8
@@ -1766,10 +1766,9 @@
 %0A%09%7D%0A
-%09
 %0A
+
 %09pub
@@ -1882,20 +1882,20 @@
 initKey(
-2048
+1024
 );%0A%09%09Sys

Update RSACoder.java