前言

  最近由于项目需求,服务端由c#编写,客户端由java编写。通信数据使用RSA非对称加密。但是java和c#生成的密钥格式是不一样的,所以需要转换格式才可以正常使用。网上搜到使用java进行格式转换的代码(如:http://blog.csdn.net/road2010/article/details/40071881 ),本文将给出一种c#的实现方法。

密钥格式

java密钥格式如下:

私钥:

MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKSZSSEdPhv77O5ocnLNGXeQ21qJDArC1+yId+9/pY5bXkZk5vCB49EpfMwNukLv6AJqofThZPNOs1t015fdEYIUnkIc2QVxRwa0xTeFP6N8D4WQXRWs4fNG27JK5kP45s+9KlJtx5hs7G97aMczehIWpHaO6j9inOmjlU8l62KZAgMBAAECgYEAmK3TRtMwRJb33OGnn9OeFumYfy92qxi3X6Hq1o6qDBW2qkd4bImfv+ni6AinyOVuaadt2Y+lq4dKGcCVJzoZvPm1VKxD2y7xKa8/vEbPRiRTt0qnPq9T7UJkpDsiXf/zOMfWdjc3uA1bPnQ65RWHSJ7zAE+Gd7xnyCE5MEyijLECQQDVYqQWDqOVLZ5lJUuIfUIrhv26GvuoTX8v60+opCz4/Mdfh6JlefICVD6SAaYvufXBHVFY26JicNlR62ZOiBoNAkEAxXhsuEnNJNQcQHEVTPZoulbMbTV1VZIDQ1zjG8fvu8sv6IBYcR5+EsC8n3/6RkW8/iCJDzxE++VHzhoSQSoDvQJBAM6/63J/rpndAIrJ7vyJOPLJsc9/U3SH2gMJAT7KC9UXvuldlsixtf3xuEpplKbLjEUXbfklnZm586a+6XqPvoUCQDFotltOLARBBmihYuEE7qNhQHk63QbyJ9rdDP5Qgo2Mg4o7QuXa6VSr4QZPsUGQBX/YiDLFs8ULU3IgV9zyNEkCQADAYR8DctYzg0eBGdcOrDA5Szc62pYrS2wk89wUxyL4FyDL3omkVMKvtu5tccy7Xht2ikJZRqefZ3dS7ASm8/4=

公钥:

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkmUkhHT4b++zuaHJyz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eyValue>

公钥:

<RSAKeyValue>
<Modulus>pJlJIR0+G/vs7mhycs0Zd5DbWokMCsLX7Ih373+ljlteRmTm8IHj0Sl8zA26Qu/oAmqh9OFk806zW3TXl90RghSeQhzZBXFHBrTFN4U/o3wPhZBdFazh80bbskrmQ/jmz70qUm3HmGzsb3toxzN6Ehakdo7qP2Kc6aOVTyXrYpk=</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>

  

转换实现代码(c#)

  格式转换要用到一个开源加密库Bouncy Castle Crypto APIs,官网地址: http://www.bouncycastle.org/csharp/

  具体实现代码如下:

using System;
using System.Xml;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509; /// <summary>
/// RSA密钥格式转换
/// </summary>
public class RSAKeyConvert
{
/// <summary>
/// RSA私钥格式转换,java->.net
/// </summary>
/// <param name="privateKey">java生成的RSA私钥</param>
/// <returns></returns>
public static string RSAPrivateKeyJava2DotNet(string privateKey)
{
RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)); return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
} /// <summary>
/// RSA私钥格式转换,.net->java
/// </summary>
/// <param name="privateKey">.net生成的私钥</param>
/// <returns></returns>
public static string RSAPrivateKeyDotNet2Java(string privateKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(privateKey);
BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText)); RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
return Convert.ToBase64String(serializedPrivateBytes);
} /// <summary>
/// RSA公钥格式转换,java->.net
/// </summary>
/// <param name="publicKey">java生成的公钥</param>
/// <returns></returns>
public static string RSAPublicKeyJava2DotNet(string publicKey)
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
} /// <summary>
/// RSA公钥格式转换,.net->java
/// </summary>
/// <param name="publicKey">.net生成的公钥</param>
/// <returns></returns>
public static string RSAPublicKeyDotNet2Java(string publicKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(publicKey);
BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
RsaKeyParameters pub = new RsaKeyParameters(false, m, p); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
return Convert.ToBase64String(serializedPublicBytes);
}
}

  

以上就介绍了RSA密钥之C#格式与Java格式转换,包括了方面的内容,希望对.NET教程有兴趣的朋友有所帮助。

本文网址链接:http://www.codes51.com/article/detail_106585.html

(转)C#与Java的证书密钥转换的更多相关文章

  1. Rsa加解密Java、C#、php通用代码 密钥转换工具

    之前发了一篇"TripleDes的加解密Java.C#.php通用代码",后面又有项目用到了Rsa加解密,还是在不同系统之间进行交互,Rsa在不同语言的密钥格式不一样,所以过程中主 ...

  2. java keytool证书工具使用小结

    java keytool证书工具使用小结 在Security编程中,有几种典型的密码交换信息文件格式: DER-encoded certificate: .cer, .crt    PEM-encod ...

  3. Java对证书的操作

    1 Java程序从证书文件读取证书 import java.io.*; import java.security.cert.*; public class PrintCert{ public stat ...

  4. Cer Crt Pem Pfx 证书格式转换

    1.从pfx格式的证书提取出密钥和证书set OPENSSL_CONF=openssl.cnfopenssl pkcs12 -in my.pfx -nodes -out server.pemopens ...

  5. java keytool证书工具使用小结【转】

    java keytool证书工具使用小结 keytool导入导出多条目对比 在Security编程中,有几种典型的密码交换信息文件格式: DER-encoded certificate: .cer, ...

  6. Java程序实现密钥库的维护

    1 Java程序列出密钥库所有条目 import java.util.*; import java.io.*; import java.security.*; public class ShowAli ...

  7. java keytool证书工具使用小结(转)

    Keytool 是一个Java数据证书的管理工具 ,Keytool将密钥(key)和证书(certificates)存在一个称为keystore的文件中在keystore里,包含两种数据:密钥实体(K ...

  8. java keytool证书工具使用小结(转载)

    原文地址:http://www.micmiu.com/lang/java/keytool-start-guide/ Keytool 是一个Java数据证书的管理工具 ,Keytool将密钥(key)和 ...

  9. Java页面中文编码要转换两次encodeURI

    1.js文件中使用encodeURI()方法. login_name = encodeURI(encodeURI(login_name)); 2.action中URLDecoder解码 loginNa ...

随机推荐

  1. (转)配置Website的IIS时遇到的问题与解决方法

    在部署WebSite时遇到问题,刚好发现Eric Sun的文章,因此转载做个副本. 原文地址:http://www.cnblogs.com/mingmingruyuedlut/archive/2011 ...

  2. PreparedStatement和Statment

    使用Statment安全性差,存在SQL注入隐患 public static void main(String[] args) { Connection conn=null; Statement st ...

  3. jquery实现跨域提交(原创)

    jquery实现跨域提交(原创)   我们在运营一个产品的时候往往会遇到这样那样的表单提交,如客户数据收集.申请加盟.意见反馈等,由此我们开发了这样一个产品,可以理解为万能型数据收集平台,不难想到,我 ...

  4. VS error retrieving information from user datastore

    搭建好VS2005+PB6.0的开发环境后,新建MFC智能设备应用程序工程出错,错误信息如下: error retrieving information from user datastore 很奇怪 ...

  5. jmeter随笔(2)--上传接口报错

    黑夜小怪(2016-8-24  23:45) 微信订阅号: 问题:今天同事遇到问题,一个图片上传接口,单独跑是ok的,但是放在和其他接口一起就跑不通,如图 分析:查看该接口fiddler的抓包,发现请 ...

  6. 百度校招面试经历及总结(已发offer)

    听说发面经可以攒rp,希望早点给我确定的offer通知,也希望看到这个面经的小伙伴能顺利拿到心仪的offer~ 职位:机器学习-数据挖掘工程师 9.15 上午11点 一面 1.介绍项目 2.考研意向, ...

  7. NSString用法

    1 创造字符串 NSString *str1 = @"hello"; NSString *str2 = [NSString string]; NSString *str3 = [N ...

  8. [linux] 替换字符串

    Linux下批量替换多个文件中的字符串的简单方法.用sed命令可以批量替换多个文件中的字符串. 命令如下:sed -i “s/原字符串/新字符串/g” `grep 原字符串 -rl 所在目录` 例如: ...

  9. No.013 Roman to Integer

    13. Roman to Integer Total Accepted: 95998 Total Submissions: 234087 Difficulty: Easy Given a roman ...

  10. oracle中,行转列函数wm_concat()结果有长度限制,重写该函数解决

    --Type CREATE OR REPLACE TYPE zh_concat_im AUTHID CURRENT_USER AS OBJECT ( CURR_STR clob, STATIC FUN ...