RSA 加密解密

RSA作为迄今为止经得起历史考验的非对称加密算法,已经得到了广泛的应用。但是现在有人已经破解了768bits的因素分解。不过现在的如今的RSA算法已经是2048位。这在破解提供难度的同事,也给生成这些密钥增加了不少难度。

现在写个简单RSA 加解密实例case
首先利用java的密钥生成器来随机生成密钥:
/**
	 * java 自带公钥私钥生成器
	 * @throws Exception
	 */
	private static void generateKeyPair() throws Exception {
		SecureRandom sr = new SecureRandom();
		
		KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
		/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
		kpg.initialize(KEYSIZE, sr);
		/** 生成密匙对 */
		KeyPair kp = kpg.generateKeyPair();
		Key publicKey = kp.getPublic();
		Key privateKey = kp.getPrivate();
		/** 用对象流将生成的密钥写入文件 */
		ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
		ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
		oos1.writeObject(publicKey);
		oos2.writeObject(privateKey);
		oos1.close();
		oos2.close();
	}



然后根据上面生成的公钥来进行加密:
/**
	 * 公钥加密
	 * @param source
	 * @return
	 * @throws Exception 
	 */
	public static String encrypt(String source) throws Exception {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
		Key key = (Key)ois.readObject();
		ois.close();
		/** 得到Cipher对象来实现对源数据的RSA加密 */
		Cipher cipher =  Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		byte[] b = source.getBytes();
		byte[] b1 = cipher.doFinal(b);
		return new String(Base64.encodeBase64(b1));
	}


最后根据私钥来进行解密:
/**
	 * 私钥解密
	 * @param target
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String target) throws  Exception {
		@SuppressWarnings("resource")
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
		Key key = (Key) ois.readObject();
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] bs = Base64.decodeBase64(target);
		return new String(cipher.doFinal(bs));
	}

猜你喜欢

转载自xfxlch.iteye.com/blog/2030243