Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

encrypt with public key and decrypt with private key c#

private static string _privateKey;
private static string _publicKey;
private static UnicodeEncoding _encoder = new UnicodeEncoding();

private static void RSA()
{
  var rsa = new RSACryptoServiceProvider();
  _privateKey = rsa.ToXmlString(true);
  _publicKey = rsa.ToXmlString(false);

  var text = "Test1";
  Console.WriteLine("RSA // Text to encrypt: " + text);
  var enc = Encrypt(text);
  Console.WriteLine("RSA // Encrypted Text: " + enc);
  var dec = Decrypt(enc);
  Console.WriteLine("RSA // Decrypted Text: " + dec);
}

public static string Decrypt(string data)
{
  var rsa = new RSACryptoServiceProvider();
  var dataArray = data.Split(new char[] { ',' });
  byte[] dataByte = new byte[dataArray.Length];
  for (int i = 0; i < dataArray.Length; i++)
  {
    dataByte[i] = Convert.ToByte(dataArray[i]);
  }

  rsa.FromXmlString(_privateKey);
  var decryptedByte = rsa.Decrypt(dataByte, false);
  return _encoder.GetString(decryptedByte);
}

public static string Encrypt(string data)
{
  var rsa = new RSACryptoServiceProvider();
  rsa.FromXmlString(_publicKey);
  var dataToEncrypt = _encoder.GetBytes(data);
  var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();
  var length = encryptedByteArray.Count();
  var item = 0;
  var sb = new StringBuilder();
  foreach (var x in encryptedByteArray)
  {
    item++;
    sb.Append(x);

    if (item < length)
      sb.Append(",");
  }

  return sb.ToString();
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: convert pdf to image c# 
Csharp :: c# get assembly directory 
Csharp :: c# loop array 
Csharp :: how to use curl in asp.net c# 
Csharp :: c# chunk array linq 
Csharp :: C# api get value from header 
Csharp :: c# combobox lock edit 
Csharp :: sequelize top 
Csharp :: c# modulo 
Csharp :: Convert Json String to model Class or Object 
Csharp :: set the page that FormsAuthentication.RedirectFromLoginPage redirects to 
Csharp :: c# return tuple 
Csharp :: c# write iformfile 
Csharp :: add list to list c# 
Csharp :: wpf datagrid get selected items 
Csharp :: get file name from stream c# 
Csharp :: unity rb.addexplosionforce 2d 
Csharp :: remove duplicates in the list using linq 
Csharp :: remove from list based on condition c# 
Csharp :: C# 1 minute delay 
Csharp :: aspx element visibility ould not find 
Csharp :: c# convertir caracter con tilde 
Csharp :: moving camera with touch screen unity 
Csharp :: async where linq 
Csharp :: ontriggerenter2d 
Csharp :: unity collision.impulse 
Csharp :: Show empty message in data table angular material, If no data found 
Csharp :: c# if string in licbox 
Csharp :: load a form from button c# 
Csharp :: uwp roaming data sample 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =