问题描述
我从.NET系统中的XML格式的私钥和公钥。我必须用这个键在Java中执行加密/解密。有没有办法做到这一点?
I have private and public keys from the .Net system in the xml format. I have to use this keys to perform encryption/decryption in Java. Is there any way to do it?
公钥看起来是这样的:
<RSAKeyValue>
<Modulus>jHIxcGzzpByFv...pvhxFnP0ssmlBfMALis</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
私钥:
<RSAKeyValue>
<Modulus>4hjg1ibWXHIlH...ssmlBfMAListzrgk=</Modulus>
<Exponent>AQAB</Exponent>
<P>8QZCtrmJcr9uW7VRex+diH...jLHV5StmuBs1+vZZAQ==</P>
<Q>8CUvJTv...yeDszMWNCQ==</Q>
<DP>elh2Nv...cygE3657AQ==</DP>
<DQ>MBUh5XC...+PfiMfX0EQ==</DQ>
<InverseQ>oxvsj4WCbQ....LyjggXg==</InverseQ>
<D>KrhmqzAVasx...uxQ5VGZmZ6yOAE=</D>
</RSAKeyValue>
我已经写了一点code来加密数据,但我不知道它是正确的。
I have written a bit of code to encrypt data but I am not sure if its correct.
Element modulusElem = root.getChild("Modulus");
Element exponentElem = root.getChild("Exponent");
byte[] expBytes = decoder.decodeBuffer(exponentElem.getText().trim());
byte[] modBytes = decoder.decodeBuffer(modulusElem.getText().trim());
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(new BigInteger(1, modBytes), new BigInteger(1, expBytes));
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
如何使从XML私钥来解密数据?
How can I make a private key from the xml to decrypt the data?
推荐答案
是德在你的榜样做的Base64解码codeR
?它看起来像你可能会依赖于 sun.misc.BASE64De codeR
和它一般不依赖于这些内部类(其他JVM的不会有一个好主意它例如)。您可以使用 Apache的共享codeC 具有的Base64类脱code用。下面是你需要什么尽管对于RSA加密和解密的休息:
Is that decoder
in your example doing the Base64 decoding? It looks like you might be relying on sun.misc.BASE64Decoder
and it's generally not a good idea to depend on those internal classes (other JVM's won't have it for instance). You could use Apache Commons Codec that has a Base64 class to decode with. Here's the rest of what you need though for RSA encryption and decryption:
byte[] expBytes = Base64.decodeBase64(exponentElem.getText().trim()));
byte[] modBytes = Base64.decodeBase64(modulusElem.getText().trim());
byte[] dBytes = Base64.decodeBase64(dElem.getText().trim());
BigInteger modules = new BigInteger(1, modBytes);
BigInteger exponent = new BigInteger(1, expBytes);
BigInteger d = new BigInteger(1, dBytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA");
String input = "test";
RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modules, exponent);
PublicKey pubKey = factory.generatePublic(pubSpec);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8"));
System.out.println("encrypted: " + new String(encrypted));
RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modules, d);
PrivateKey privKey = factory.generatePrivate(privSpec);
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println("decrypted: " + new String(decrypted));
这篇关于移植的.Net RSA密钥的XML到Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!