fork download
  1. using System;
  2. using System.Security.Cryptography;
  3.  
  4. class RSASample
  5. {
  6. public static string Base64Encode(byte[] plainTextBytes) {
  7. return System.Convert.ToBase64String(plainTextBytes);
  8. }
  9.  
  10. static void Main()
  11. {
  12. try
  13. {
  14. //Create a new instance of RSA.
  15. using (RSA rsa = RSA.Create())
  16. {
  17. //The hash to sign.
  18. byte[] hash;
  19. using (SHA256 sha256 = SHA256.Create())
  20. {
  21. byte[] data = System.Text.Encoding.UTF8.GetBytes("hello world!");
  22. hash = sha256.ComputeHash(data);
  23. }
  24.  
  25. String publicKey = rsa.ToXmlString(false);
  26. String privateKey = rsa.ToXmlString(true);
  27.  
  28. //Create an RSASignatureFormatter object and pass it the
  29. //RSA instance to transfer the key information.
  30. RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsa);
  31.  
  32. //Set the hash algorithm.
  33. RSAFormatter.SetHashAlgorithm("SHA256");
  34.  
  35. //Create a signature for HashValue and return it.
  36. byte[] SignedHash = RSAFormatter.CreateSignature(hash);
  37.  
  38. Console.WriteLine("Public Key:");
  39. Console.WriteLine(publicKey);
  40. Console.WriteLine("Private Key:");
  41. Console.WriteLine(privateKey);
  42.  
  43. Console.WriteLine("Sign:");
  44. Console.WriteLine(Base64Encode(SignedHash));
  45. }
  46. }
  47. catch (CryptographicException e)
  48. {
  49. Console.WriteLine(e.Message);
  50. }
  51. }
  52. }
Success #stdin #stdout 0.17s 22612KB
stdin
Standard input is empty
stdout
Public Key:
<RSAKeyValue><Modulus>wzCS7AYAnfIRFY6i2Tpz2J6K2BNjqJpb5VvtbnCjcnzKzyp1gTl9rNvFzFQZQ7xUOpdkQsDVx4b+G5bKzdbnL4dDvunCheLgsQNdO99V0IrTYxCFClOcgOOGyoFC+QLqqQ2d4dRoKulq69uT+eGiwV4FXlZG7Pwu0nksc3mlJ7s=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
Private Key:
<RSAKeyValue><Modulus>wzCS7AYAnfIRFY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