C# java 通用 RSA 加密/解密

2 篇文章 0 订阅
 
 
 
package cn.shinkong.cxf.util;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.PKCS8EncodedKeySpec;

import org.apache.ws.security.util.Base64;

public class RSAPrivateKeyAsCSharp {

	
	/** java privateKey 转换成C# privateKey
	 * RSAPrivateKey privateKey;
	 * @param byte[] privateKey.getEncoded()
	 * @return C# privatekey
	 * @throws Exception
	 */
	public static String getRSAPrivateKeyAsNetFormat(byte[] encodedPrivkey) {
		try {
			StringBuffer buff = new StringBuffer(1024);

			PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(
					encodedPrivkey);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			RSAPrivateCrtKey pvkKey = (RSAPrivateCrtKey) keyFactory
					.generatePrivate(pvkKeySpec);
			buff.append("<RSAKeyValue>");
			buff.append("<Modulus>"
					+ Base64.encode(removeMSZero(pvkKey.getModulus()
							.toByteArray())) + "</Modulus>");
			buff.append("<Exponent>"
					+ Base64.encode(removeMSZero(pvkKey.getPublicExponent()
							.toByteArray())) + "</Exponent>");
			buff.append("<P>"
					+ Base64.encode(removeMSZero(pvkKey.getPrimeP()
							.toByteArray())) + "</P>");
			buff.append("<Q>"
					+ Base64.encode(removeMSZero(pvkKey.getPrimeQ()
							.toByteArray())) + "</Q>");
			buff.append("<DP>"
					+ Base64.encode(removeMSZero(pvkKey.getPrimeExponentP()
							.toByteArray())) + "</DP>");
			buff.append("<DQ>"
					+ Base64.encode(removeMSZero(pvkKey.getPrimeExponentQ()
							.toByteArray())) + "</DQ>");
			buff.append("<InverseQ>"
					+ Base64.encode(removeMSZero(pvkKey.getCrtCoefficient()
							.toByteArray())) + "</InverseQ>");
			buff.append("<D>"
					+ Base64.encode(removeMSZero(pvkKey.getPrivateExponent()
							.toByteArray())) + "</D>");
			buff.append("</RSAKeyValue>");
			return buff.toString().replaceAll("[ \t\n\r]", "");
		} catch (Exception e) {
			System.err.println(e);
			return null;
		}
	}
	/** java publicKey 转换成C# publicKey
	 * RSAPrivateKey privateKey;
	 * @param  byte[] privateKey.getEncoded()
	 * @return C# privatekey
	 * @throws Exception
	 */
	public static String getRSAPublicKeyAsNetFormat(byte[] encodedPrivkey) {
		try {
			StringBuffer buff = new StringBuffer(1024);
			// 根据给定的编码密钥创建一个新的 PKCS8EncodedKeySpec。
			PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(
					encodedPrivkey);
			// 返回转换指定算法的 public/private 关键字的 KeyFactory 对象。
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			// 根据提供的密钥规范(密钥材料)生成私钥对象。
			RSAPrivateCrtKey pvkKey = (RSAPrivateCrtKey) keyFactory
					.generatePrivate(pvkKeySpec);
			buff.append("<RSAKeyValue>");
			buff.append("<Modulus>"
					+ Base64.encode(removeMSZero(pvkKey.getModulus()
							.toByteArray())) + "</Modulus>");
			buff.append("<Exponent>"
					+ Base64.encode(removeMSZero(pvkKey.getPublicExponent()
							.toByteArray())) + "</Exponent>");
			buff.append("</RSAKeyValue>");
			return buff.toString().replaceAll("[ \t\n\r]", "");
		} catch (Exception e) {
			System.err.println(e);
			return null;
		}
	}
	// 我们得到的modulus是257个字节,需要去掉首字节的0,用剩下的256个字节实例化BigInteger。
	private static byte[] removeMSZero(byte[] data) {
		byte[] data1;
		int len = data.length;
		if (data[0] == 0) {
			data1 = new byte[data.length - 1];
			System.arraycopy(data, 1, data1, 0, len - 1);
		} else
			data1 = data;
		return data1;
	}
	
	/**
	 * main 方法调用方式
	 * 公钥 C# string publickey = @"
	 * <RSAKeyValue>
	 * <Modulus>
	 * 5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ
	 * 6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=
	 * </Modulus>
	 * <Exponent>
	 * AQAB
	 * </Exponent>
	 * </RSAKeyValue>
	 * "; 
	 *   
	 * 私钥 C# string privatekey = @"
	 * <RSAKeyValue>
	 * <Modulus>
	 * 5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4g
	 * Z6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=
	 * </Modulus>
	 * <Exponent>
	 * AQAB
	 * </Exponent>
	 * <P>
	 * /hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==
	 * </P>
	 * <Q>
	 * 6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==
	 * </Q>
	 * <DP>
	 * ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==
	 * </DP>
	 * <DQ>
	 * MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==
	 * </DQ>
	 * <InverseQ>
	 * EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==
	 * </InverseQ>
	 * <D>
	 * vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzK
	 * ioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=
	 * </D>
	 * </RSAKeyValue>
	 * ";   
	 public static void main(String[] args) throws Exception {
		RSAPublicKey publicKey;
		ObjectInputStream ois = null;
		ois = new ObjectInputStream(new FileInputStream(
				"PublicKey"));
		publicKey = (RSAPublicKey) ois.readObject();
		RSAPrivateKey privateKey;
		ObjectInputStream ois1 = null;
		ois1 = new ObjectInputStream(new FileInputStream("PrivateKey"));
		privateKey = (RSAPrivateKey) ois1.readObject();
		//privateKey.getEncoded() 返回基本编码格式的密钥,如果此密钥不支持编码,
		System.out.println(RSAPrivateKeyAsCSharp.getRSAPublicKeyAsNetFormat(privateKey.getEncoded()));
	}
	*/		
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值