1

How can I encode RSA public key in C# so that I can use is later in a Java application ()? Please, note that I need to do it on the .NET side. I'm trying to use BouncyCastle API to achieve this, but I cannot find a single piece of documentation that would describe such functionality.

pangular
  • 699
  • 7
  • 27
  • I suspect you're actually asking the wrong question. Perhaps you really want to ask how to export an RSA public key from C# in a format that is compatible with Java's [X509EncodedKeySpec](http://docs.oracle.com/javase/7/docs/api/java/security/spec/X509EncodedKeySpec.html) One solution is provided [here](http://stackoverflow.com/questions/10368111/encode-a-rsa-public-key-to-der-format). – President James K. Polk Oct 29 '14 at 00:24
  • 1
    @GregS, you are right. Yes, I had already found the solution. Here is the source: http://www.rahulsingla.com/blog/2011/04/serializing-deserializing-rsa-public-private-keys-generated-using-bouncy-castle-library . Thank you! – pangular Oct 29 '14 at 09:31
  • Excellent, please post the solution as an answer and then accept the answer. Also, don't just post a link: post the link *and* the code shown in that link. – President James K. Polk Oct 29 '14 at 11:20

1 Answers1

2

Here's how you do it:

using (var rsa = new RSACryptoServiceProvider(cp))
{
    var keyPair = DotNetUtilities.GetKeyPair(rsa);
    var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
    var serializedPublicBytes = publicKeyInfo.GetEncoded();
    return BitConverter.ToString(serializedPublicBytes).Replace("-", "");
}

You can find more details here: http://www.rahulsingla.com/blog/2011/04/serializing-deserializing-rsa-public-private-keys-generated-using-bouncy-castle-library

pangular
  • 699
  • 7
  • 27