将.Net RSA xml密钥移植到Java

我有来自.Net系统的私有和公共密钥,采用xml格式。 我必须使用此密钥在Java中执行加密/解密。 有什么办法吗?

公钥看起来像这样:

 jHIxcGzzpByFv...pvhxFnP0ssmlBfMALis AQAB  

私钥:

  4hjg1ibWXHIlH...ssmlBfMAListzrgk= AQAB 

8QZCtrmJcr9uW7VRex+diH...jLHV5StmuBs1+vZZAQ==

8CUvJTv...yeDszMWNCQ== elh2Nv...cygE3657AQ== MBUh5XC...+PfiMfX0EQ== oxvsj4WCbQ....LyjggXg== KrhmqzAVasx...uxQ5VGZmZ6yOAE=

我已经编写了一些代码来加密数据,但我不确定它是否正确。

  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创建私钥来解密数据?

您的示例中的decoder是否在进行Base64解码? 看起来你可能依赖于sun.misc.BASE64Decoder ,依赖于那些内部类通常不是一个好主意(例如,其他JVM不会拥有它)。 您可以使用具有Base64类的Apache Commons Codec进行解码。 以下是RSA加密和解密所需的其余部分:

 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)); 

尝试使用

 RSAPrivateKeySpec privSpec = new RSAPrivateCrtKeySpec(iModulus,iExponentBytes,iDBytes,iPBytes,iQBytes,iDPBytes,iDQBytes,iInverseQBytes) 

并添加所有私钥组件