using System; using System.Security.Cryptography; class RSASample { public static string Base64Encode(byte[] plainTextBytes) { return System.Convert.ToBase64String(plainTextBytes); } static void Main() { try { //Create a new instance of RSA. using (RSA rsa = RSA.Create()) { //The hash to sign. byte[] hash; using (SHA256 sha256 = SHA256.Create()) { byte[] data = System.Text.Encoding.UTF8.GetBytes("hello world!"); hash = sha256.ComputeHash(data); } String publicKey = rsa.ToXmlString(false); String privateKey = rsa.ToXmlString(true); //Create an RSASignatureFormatter object and pass it the //RSA instance to transfer the key information. RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsa); //Set the hash algorithm. RSAFormatter.SetHashAlgorithm("SHA256"); //Create a signature for HashValue and return it. byte[] SignedHash = RSAFormatter.CreateSignature(hash); Console.WriteLine("Public Key:"); Console.WriteLine(publicKey); Console.WriteLine("Private Key:"); Console.WriteLine(privateKey); Console.WriteLine("Sign:"); Console.WriteLine(Base64Encode(SignedHash)); } } catch (CryptographicException e) { Console.WriteLine(e.Message); } } }
Standard input is empty
Public Key: <RSAKeyValue><Modulus>wzCS7AYAnfIRFY6i2Tpz2J6K2BNjqJpb5VvtbnCjcnzKzyp1gTl9rNvFzFQZQ7xUOpdkQsDVx4b+G5bKzdbnL4dDvunCheLgsQNdO99V0IrTYxCFClOcgOOGyoFC+QLqqQ2d4dRoKulq69uT+eGiwV4FXlZG7Pwu0nksc3mlJ7s=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue> Private Key: <RSAKeyValue><Modulus>wzCS7AYAnfIRFY6i2Tpz2J6K2BNjqJpb5VvtbnCjcnzKzyp1gTl9rNvFzFQZQ7xUOpdkQsDVx4b+G5bKzdbnL4dDvunCheLgsQNdO99V0IrTYxCFClOcgOOGyoFC+QLqqQ2d4dRoKulq69uT+eGiwV4FXlZG7Pwu0nksc3mlJ7s=</Modulus><Exponent>AQAB</Exponent><P>9KGnwrMYbNJGks9D99bKx/kQysZs0Tdj2uM6uBiU1k9xWaOqzUiLaZB4gch2G+1OV1R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