c#rsa加密java解密_C# Java间进行RSA加密解密交互(二)

import java.io.UnsupportedEncodingException;

import java.lang.reflect.Method;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.NoSuchAlgorithmException;

import java.security.PublicKey;

import java.security.interfaces.RSAPrivateCrtKey;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;

/**

* @author Administrator

*

*/

public class RSAJavaToCSharp {

public static void main(String[] args) throws Exception {

HashMap map = getKeys();

RSAPublicKey publicKey = (RSAPublicKey) map.get("PUBLIC");

RSAPrivateKey privateKey = (RSAPrivateKey) map.get("PRIVATE");

String publicKeyString = getRSAPublicKeyAsNetFormat(publicKey.getEncoded());

String privateKeyString = getRSAPrivateKeyAsNetFormat(privateKey.getEncoded());

System.out.println(encodeBase64(publicKey.getEncoded()));//此处为客户端加密时需要的公钥字符串

System.out.println(encodePublicKeyToXml(publicKey));

System.out.println(publicKeyString);

System.out.println(privateKeyString);

}

/**获取密钥对

* @return

* @throws NoSuchAlgorithmException

*/

public static HashMap getKeys()

throws NoSuchAlgorithmException {

HashMap map = new HashMap();

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

keyPairGen.initialize(1024);

KeyPair keyPair = keyPairGen.generateKeyPair();

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

map.put("PUBLIC", publicKey);

map.put("PRIVATE", privateKey);

return map;

}

/**

* 私钥转换成C#格式

* @param encodedPrivkey

* @return

*/

private static String getRSAPrivateKeyAsNetFormat(byte[] encodedPrivateKey) {

try {

StringBuffer buff = new StringBuffer(1024);

PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(

encodedPrivateKey);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

RSAPrivateCrtKey pvkKey = (RSAPrivateCrtKey) keyFactory

.generatePrivate(pvkKeySpec);

buff.append("");

buff.append(""

+ encodeBase64(removeMSZero(pvkKey.getModulus()

.toByteArray())) + "");

buff.append(""

+ encodeBase64(removeMSZero(pvkKey.getPublicExponent()

.toByteArray())) + "");

buff.append("

"

+ encodeBase64(removeMSZero(pvkKey.getPrimeP()

.toByteArray())) + "

");

buff.append(""

+ encodeBase64(removeMSZero(pvkKey.getPrimeQ()

.toByteArray())) + "");

buff.append(""

+ encodeBase64(removeMSZero(pvkKey.getPrimeExponentP()

.toByteArray())) + "");

buff.append(""

+ encodeBase64(removeMSZero(pvkKey.getPrimeExponentQ()

.toByteArray())) + "");

buff.append(""

+ encodeBase64(removeMSZero(pvkKey.getCrtCoefficient()

.toByteArray())) + "");

buff.append(""

+ encodeBase64(removeMSZero(pvkKey.getPrivateExponent()

.toByteArray())) + "");

buff.append("");

return buff.toString();

} catch (Exception e) {

System.err.println(e);

return null;

}

}

/**

* 公钥转成C#格式

* @param encodedPrivkey

* @return

*/

private static String getRSAPublicKeyAsNetFormat(byte[] encodedPublicKey) {

try {

StringBuffer buff = new StringBuffer(1024);

//Only RSAPublicKeySpec and X509EncodedKeySpec supported for RSA public keys

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

RSAPublicKey pukKey = (RSAPublicKey) keyFactory

.generatePublic(new X509EncodedKeySpec(encodedPublicKey));

buff.append("");

buff.append(""

+ encodeBase64(removeMSZero(pukKey.getModulus()

.toByteArray())) + "");

buff.append(""

+ encodeBase64(removeMSZero(pukKey.getPublicExponent()

.toByteArray())) + "");

buff.append("");

return buff.toString();

} catch (Exception e) {

System.err.println(e);

return null;

}

}

/**

* 公钥转换成C#格式

* @param key

* @return

* @throws Exception

*/

public static String encodePublicKeyToXml(PublicKey key) throws Exception {

if (!RSAPublicKey.class.isInstance(key)) {

return null;

}

RSAPublicKey pubKey = (RSAPublicKey) key;

StringBuilder sb = new StringBuilder();

sb.append("");

sb.append("")

.append(encodeBase64(removeMSZero(pubKey.getModulus()

.toByteArray()))).append("");

sb.append("")

.append(encodeBase64(removeMSZero(pubKey.getPublicExponent()

.toByteArray()))).append("");

sb.append("");

return sb.toString();

}

/**

* @param data

* @return

*/

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;

}

/**

* base64编码

* @param input

* @return

* @throws Exception

*/

public static String encodeBase64(byte[] input) throws Exception {

Class clazz = Class

.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");

Method mainMethod = clazz.getMethod("encode", byte[].class);

mainMethod.setAccessible(true);

Object retObj = mainMethod.invoke(null, new Object[] { input });

return (String) retObj;

}

/**

* base64解码

* @param input

* @return

* @throws Exception

*/

public static byte[] decodeBase64(String input) throws Exception {

Class clazz = Class

.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");

Method mainMethod = clazz.getMethod("decode", String.class);

mainMethod.setAccessible(true);

Object retObj = mainMethod.invoke(null, input);

return (byte[]) retObj;

}

public static String byteToString(byte[] b)

throws UnsupportedEncodingException {

return new String(b, "utf-8");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值