I have public key generated using java with algorithm RSA and able to reconstruct using following code:
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(arrBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(pubKeySpec);
QUESTION How to construct PublicKey on dotnet side using csharp?
sample public key would be:, In above code i pass data contained in element encoded
<sun.security.rsa.RSAPublicKeyImpl resolves-to="java.security.KeyRep">
<type>PUBLIC</type>
<algorithm>RSA</algorithm>
<format>X.509</format>
<encoded>MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMf54mcK3EYJn9tT9BhRoTX+8AkqojIyeSfog9ncYEye
0VXyBULGg2lAQsDRt8lZsvPioORZW7eB6IKawshoWUsCAwEAAQ==</encoded>
</sun.security.rsa.RSAPublicKeyImpl>
Unfortunately, C# doesn't provide any simple way to do this. But this will correctly decode an x509 public key (make sure to Base64 decode the x509key parameter first):
The above code is based off of this question (which only worked for certain key sizes). The above code will work for pretty much any RSA key size though, and has been tested with the key you provided as well as 2048-bit and 4096-bit keys.
An alternative solution would be to generate a certificate using a tool (XCA is a good one), export the cert to a p12 (PKCS12) file and then load the cert in both Java and C# to get at the keys.
In C# you can load a PKCS12 file using the
X509Certificate2
class.In Java you can load a PKCS12 file using the
KeyStore
class.In Java, cast
publicKey
fromPublicKey
toRSAPublicKey
.That has
getModulus
andgetExponent
will get youBigIntegers
, from which you usetoByteArray
to get the bytes.I don't know Java keeps leading 0s in the
BigInteger
class, so check if you have to strip leading null (0x00) bytes from the public exponent.Encode the byte arrays into base 64 using either the Apache Commons Codec or Java 8's Base64 Encoder.
You may need to check byte order (maybe reverse the modulus, not sure).
Serialize these by constructing this XML:
"<RSAKeyValue><Modulus>
{your base 64 encoded public modulus here}</Modulus><Exponent>
{your base 64 encoded public exponent here}</Exponent></RSAKeyValue>"
.In CSharp:
Now you have an RSA CSP loaded with your public key.
The same process can be extended to load a private key by adding P, Q, DP, DQ and InverseQ XML elements.
Hello you can try this way also,