RSA使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > RSA使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥

RSA使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥

 2011/11/3 8:13:47  caniggia1986  http://caniggia1986.iteye.com  我要评论(0)
  • 摘要:privatestaticfinalStringKEY_ALGORITHM="RSA";privatestaticfinalStringPUBLIC_KEY="publicKey";privatestaticfinalStringPRIVATE_KEY="privateKey";publicstaticvoidmain(String[]args)throwsException{Map<String,String>keyMap=genKey()
  • 标签:KEY 使用
	private static final String KEY_ALGORITHM = "RSA";  
	private static final String PUBLIC_KEY ="publicKey";
	private static final String PRIVATE_KEY ="privateKey"; 
        public static void main(String[] args) throws Exception{
		Map<String,String> keyMap = genKey();
		RSAPublicKey publicKey = getPublicKey(keyMap.get(PUBLIC_KEY));
		RSAPrivateKey privateKey = getPrivateKey(keyMap.get(PRIVATE_KEY));
		String info ="明文123456";
		//加密
		byte[] bytes = encrypt(info.getBytes("utf-8"),publicKey);
		//解密
		bytes = decrypt(bytes, privateKey);
		System.out.println(new String(bytes,"utf-8"));
		 
	}
	
	public static Map<String,String> genKey() throws NoSuchAlgorithmException{
		Map<String,String> keyMap = new HashMap<String,String>();
		KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		SecureRandom random = new SecureRandom();
		// random.setSeed(keyInfo.getBytes());
		// 初始加密,512位已被破解,用1024位,最好用2048位
		keygen.initialize(1024, random);
		// 取得密钥对
		KeyPair kp = keygen.generateKeyPair();
		RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate();
 		String privateKeyString = Base64.encode(privateKey.getEncoded());
		RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic(); 
		String publicKeyString = Base64.encode(publicKey.getEncoded());
		keyMap.put(PUBLIC_KEY, publicKeyString);
		keyMap.put(PRIVATE_KEY, privateKeyString);
		return keyMap;
	}
	
	public static RSAPublicKey getPublicKey(String publicKey) throws Exception{
		byte[] keyBytes = LBase64.decode(publicKey);
		X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		return (RSAPublicKey) keyFactory.generatePublic(spec);
	}
	
	public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception{
		byte[] keyBytes = LBase64.decode(privateKey);
		PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		return (RSAPrivateKey) keyFactory.generatePrivate(spec);
	}

发表评论
用户名: 匿名