java C# RSA加密/解密 通用

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()));
	}
	*/
	
	
	
}


 

分割线———————————————————————————————————————————————————————————————

 

 /// <summary>  
        /// RSA加密(加密步骤)  
        /// 1,读取公钥
        /// 2,用RSA加密数据  
        /// </summary>  
        /// <param name="encryptedSource">已加密的内容</param>  
        /// <param name="key">密钥</param>  
        public static string RSAEncrypt(string content)
        {
            string publickey = @"<RSAKeyValue><Modulus>rc/Y0TpCBiipaq/8wVGi7UtiQhY6oZ91UpBtvHHnY/PNWHvi62syyCP9
                               kxjBgcncECR3Y40QL7HHvF07p/MOjbopxvDTXBUIFwTj/V8B/SdU0YVwwpOny2wHl/KvNVCWCIyptU9Dy+D4r
                              /Kv8hASY5s4bzCcUQ/JFpc+RXaYVcM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            return Convert.ToBase64String(cipherbytes);
        }


 

        /// <summary>
        /// RSA解密
        /// 1,读取私钥
        /// 2,用私钥解密数据
        /// </summary>
        /// <param name="privatekey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RSADecrypt(byte[] content)
        {
            string privatekey = @"<RSAKeyValue><Modulus>rc/Y0TpCBiipaq/8wVGi7UtiQhY6oZ91UpBtvHHnY
                                 /PNWHvi62syyCP9kxjBgcncECR3Y40QL7HHvF07p/MOjbopxvDTXBUIFwTj/V8B/
                                 SdU0YVwwpOny2wHl/KvNVCWCIyptU9Dy+D4r/Kv8hASY5s4bzCcUQ/JFpc+RXaYV
                                 cM=</Modulus><Exponent>AQAB</Exponent><P>7uQdFVbIS21baJesL
                                3I3CUYal0pt1wmZvW6RmmYR/JXywt4FiB+d4Ydf0uWSgYmTPP5ye0Hi+iI/zmHt+0
                                q6yw==</P><Q>ukKOZGdfh/raYuq38SCwf1Y2TBTlskQxTEgoid+YLWT//gTY6mf5
                                +ZuDgEfwUHGcqQ1oVGqWsgGZIC+hLrOZ6Q==</Q><DP>gsih33fWSe0BuR4oJwWJe
                                etGTYNy5OIdp+arkfLFcBoLgIGaV66vebPqUwRaE87kq+TFehNVFwm/EtbsOcHsxw==
                                </DP><DQ>bqTo10X9HtbqcgZCnI+xqQL6oDlttXcC3fCjfDuBt72ewDP680wu15MFC+
                                gwHmlPCbF4P2VN/ZIrd04z7n0sOQ==</DQ><InverseQ>3H5kdMjeJiTTtLRQZFevyw
                                Bn44C5PK69xFoS4sYy5vOrAy8vcPWOwvY8nUrssXP9LGHS88fSmPu7wlEzPUzrRg==
                                </InverseQ><D>hVHBMDNsg0bbNF9LE4mn3DYPZzufu2sRVcQ8t+fyoaNXJgDYvNTb/
                                dJFZXf+rawFJUijXvPLr5nA6AXnhVqVFPDTnlSIKi4QEXSvHRlboYy+XsRxdOf
                                Owy6mcowqPrbdDCnjGdn0bj7vkGXlaaiJqXrVd/am4WKoU5Q27hnxotE=</D></RSAKeyValue>";
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(privatekey);
            cipherbytes = rsa.Decrypt(content, false);
            return Encoding.UTF8.GetString(cipherbytes);
        }



 

没有更多推荐了,返回首页