在Java中将RSA密钥对象导出为XML [英] Exporting RSA key object to XML in Java
问题描述
我在Java中成功运行RSA加密/解密。这就是我生成密钥的方式。
I am successfully running RSA encryption/decryption in Java. This is how I generated the key.
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keypair = kpg.generateKeyPair();
oos.writeObject(keypair);
但现在我需要将我的系统与.Net代码集成。是否可以按以下格式将此KeyPair对象导出为XML(因为.Net代码只能接受XML格式的密钥):
But now I need to integrate my system with .Net code. Is it possible to export this KeyPair object into XML in the following format(as that .Net code can only accept keys in XML format):
<RSAKeyValue>
<Modulus>.....</Modulus>
<Exponent>......</Exponent>
<P>.....</P>
<Q>....</Q>
<DP>.......</DP>
<DQ>......</DQ>
<InverseQ>.........</InverseQ>
<D>........</D>
</RSAKeyValue>
推荐答案
试试这个:
// key pair is in 'kp'
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateCrtKeySpec ks = kf.getKeySpec(
kp.getPrivate(), RSAPrivateCrtKeySpec.class);
System.out.println("<RSAKeyValue>");
System.out.println(" <Modulus>" + ks.getModulus() + "</Modulus>");
System.out.println(" <Exponent>" + ks.getPublicExponent() + "</Exponent>");
System.out.println(" <P>" + ks.getPrimeP() + "</P>");
System.out.println(" <Q>" + ks.getPrimeQ() + "</Q>");
System.out.println(" <DP>" + ks.getPrimeExponentP() + "</DP>");
System.out.println(" <DQ>" + ks.getPrimeExponentQ() + "</DQ>");
System.out.println(" <InverseQ>" + ks.getCrtCoefficient() + "</InverseQ>");
System.out.println(" <D>" + ks.getPrivateExponent() + "</D>");
System.out.println("</RSAKeyValue>");
这适用于内部使用'CRT'表示的所有RSA密钥对,并允许导出;这是JDK默认使用您显示的代码生成的密钥对的情况。
This will work for all RSA key pairs which internally use the 'CRT' representation, and allow export; this is the case for the key pairs that the JDK will generate by default with the code you show.
(这里我打印出上的密钥System.out
而不是将其写入文件,但你明白了。)
(Here I print out the key on System.out
instead of writing it to a file, but you get the idea.)
这篇关于在Java中将RSA密钥对象导出为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!