5

I want to generate RSA key pair in C#. I am able to get xml strings of keys, but i need base64 representations of them. Here is my code for xml

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

privateKeyXmlText = rsa.ToXmlString(true);
publicKeyXmlText = rsa.ToXmlString(false);

but what i want is something like

privateKeyStr=="MIICITAjBgoqhkiG9w0BDAEDMBUEEKaTCK5mE2MsQANxDAfaJe8CAQoEggH47qb6bFO+a2Fj...";
publicKeyStr == "MIIBKjCB4wYHKoZIzj0CATCB1wIBATAsBgcqhkjOPQEBAiEA/////wAA...";

any ideas?

Liath
  • 9,913
  • 9
  • 51
  • 81
  • For Base64 pick a standard container format like PEM/DER: [C# Export Private/Public RSA key from RSACryptoServiceProvider to PEM string](http://stackoverflow.com/questions/23734792/c-sharp-export-private-public-rsa-key-from-rsacryptoserviceprovider-to-pem-strin) – Alex K. Jan 09 '15 at 11:55
  • The XML content are base64. Simply extract these. – President James K. Polk Jan 09 '15 at 12:48

1 Answers1

0

(answer from) C# Export Private/Public RSA key from RSACryptoServiceProvider to PEM string

public static Func<string, string> ToBase64PemFromKeyXMLString= (xmlPrivateKey) =>
        {
            if (string.IsNullOrEmpty(xmlPrivateKey))
                throw new ArgumentNullException("RSA key must contains value!");
            var keyContent = new PemReader(new StringReader(xmlPrivateKey));
            if (keyContent == null)
                throw new ArgumentNullException("private key is not valid!");
            var ciphrPrivateKey = (AsymmetricCipherKeyPair)keyContent.ReadObject();
            var asymmetricKey = new AsymmetricKeyEntry(ciphrPrivateKey.Private);

            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricKey.Key);
            var serializedPrivateKey = privateKeyInfo.ToAsn1Object().GetDerEncoded();
            return Convert.ToBase64String(serializedPrivateKey);
        };
Mohamed.Abdo
  • 2,054
  • 1
  • 19
  • 12