Java 实现RSA加解密Demo

public class TestRSA {

	public static void main(String[] args) throws Exception {
		/**
		 * 生成公私钥文件
		 */
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(1024);
		KeyPair kp = kpg.generateKeyPair();
		PublicKey public1 = kp.getPublic();
		PrivateKey private1 = kp.getPrivate();
		FileOutputStream fos = new FileOutputStream("D:\\pub.key");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(public1);
		oos.close();
		fos.close();
		fos = new FileOutputStream("D:\\pri.key");
		oos = new ObjectOutputStream(fos);
		oos.writeObject(private1);
		oos.close();
		fos.close();
		System.out.println("ok");
		/**
		 * 读取公私钥文件,生成公私钥对象,再BASE64加密为  公私钥字符串
		 */
		InputStream resourceAsStream = TestRSA.class.getResourceAsStream("/com/zlk/rsa/pub.key");
		ObjectInputStream ois = new ObjectInputStream(resourceAsStream);
		PublicKey public2 = (PublicKey) ois.readObject();
		String encodeBuffer = new BASE64Encoder().encodeBuffer(public2.getEncoded());
		System.out.println(public2);
		System.out.println(encodeBuffer);
		
		ObjectInputStream ois2 = new ObjectInputStream(TestRSA.class.getResourceAsStream("/com/zlk/rsa/pri.key"));
		PrivateKey private2 = (PrivateKey) ois2.readObject();
		String encodeBuffer2 = new BASE64Encoder().encodeBuffer(private2.getEncoded());
		System.out.println(private2);
		System.out.println(encodeBuffer2);
		
		/**
		 * BASE64解密公私钥字符串为字节数组,再生成公私钥对象
		 */
		KeyFactory key = KeyFactory.getInstance("RSA");
		byte[] decodeBuffer = new BASE64Decoder().decodeBuffer(encodeBuffer);
		X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decodeBuffer);
		PublicKey generatePublic = key.generatePublic(x509EncodedKeySpec);
		System.out.println(generatePublic);
		
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(encodeBuffer2));
		PrivateKey generatePrivate = key.generatePrivate(pkcs8EncodedKeySpec);
		System.out.println(generatePrivate);
		
		/**
		 * 加解密
		 */
		String oriMsg = "古德拉克";
		String charset = "UTF-8";
		byte[] bytes = oriMsg.getBytes(charset);
		
		/**
		 * 加密,处理为BASE64后的字符串,方便传递
		 */
		Cipher cipher = Cipher.getInstance("RSA");
		int opmode = Cipher.ENCRYPT_MODE;
		cipher.init(opmode , generatePublic);
		byte[] doFinal = cipher.doFinal(bytes);
		String encodeBuffer3 = new BASE64Encoder().encodeBuffer(doFinal);
		System.out.println(encodeBuffer3);
		
		int opmode2 =Cipher.DECRYPT_MODE;
		cipher.init(opmode2, generatePrivate);
		byte[] decodeBuffer2 = new BASE64Decoder().decodeBuffer(encodeBuffer3);
		byte[] doFinal2 = cipher.doFinal(decodeBuffer2);
		String decOriMsg = new String(doFinal2, charset);
		System.out.println(decOriMsg);
	}
}

java实现的RSA算法的加解密,相关说明已在注释中体现。

/**
 * RSAKeyGen.class.getResourceAsStream("/com/vito/base/tool/pri.key")
 * maven项目,不能直接通过这种方法获取包路径下的文件
 * 找到的是本地Git仓库,并不是工作区
 * target目录下的classes文件夹并未存放 文件,即不会自动放入,如果要通过上面的方法,只能手动放入
 */
		
  String path = RSAKeyGen.class.getResource("/").getPath()+"conf/";
  String pubPath = path+"pub.key";

将公私钥文件放置在配置文件目录下,通过上述方法获取公私钥文件,进而生成公私钥对象。

java中的BASE64Encoder和BASE64Decoder已不可用,可采用

    org.apache.tools.ant.util.Base64Converter;(只能编码)

    org.apache.commons.net.util.Base64;(可处理编解码)

替换。

编码处理后的字符串,如果通过URL链接传输,还需要经过处理,否则编码后的“+”接收后会被处理为空格,即无法通过私钥解码。

处理方式:

java方法:URLEncoder.encode(str,"UTF-8");

                 URLDecoder.decode(str,"UTF-8");

js 方法:encodeURIComponent(str);

处理后,经过网络传输,后台接收到后,无需处理,直接通过

org.apache.commons.net.util.Base64().decode(String xxx);

处理即可,无需URLDecoder再进行处理。

 

 

你可能感兴趣的:(Java)