Implementation of RSA encryption decryption and signature and verification in C #

Source: Internet
Author: User
Tags md5 encryption asymmetric encryption

RSA encryption algorithm is an asymmetric encryption algorithm. RSA is widely used in public key cryptography standards and in electronic commerce. RSA was introduced in 1977 by Ronald Leevist (Ron rivest), Adi Samor (Adi Shamir) and Lennard Adman (Leonard Adleman). At the time, all three of them worked at MIT. RSA is the first letter of their three surnames to be composed together. NET, we are able to leverage the cryptographic services provided by the classes in the. NET Framework to ensure data security. At present, the most widely used encryption method is using RSA algorithm to encrypt. There are two main classes in the. Net framework that are related to RSA cryptography: The RSA class and the RSACryptoServiceProvider class. According to MSDN, the RSA class is "The base class that represents all implementations of the RSA algorithm inherit from it", while the RSACryptoServiceProvider class is "performing asymmetric encryption and decryption using the implementation of the RSA algorithm provided by the cryptographic service provider (CSP)." In addition, the RSAParameters structure "representing the standard parameters of the RSA algorithm" is also important, which preserves the parameters of the RSA algorithm.
Here 's how to use the RSA algorithm provided by the framework in C # to encrypt, sign, verify, sign, and decrypt our information implementation of these steps

Class Program
{
static void Main ()
{
Try
{
String str_datatosign = @ "Data to sign! Data to sign! Data to sign! ";
Console.WriteLine ("Original:" + str_datatosign);
Console.WriteLine ("Length:" + str_DataToSign.Length.ToString ());
Console.WriteLine ();

String filePath = @ "C:\md5\main.js";
String str_datatosign = GetFileMD5 (FilePath);
Console.WriteLine (str_datatosign);
Writedatetofile (@ "C:\md5\md5.txt", str_datatosign);


RSACryptoServiceProvider rsaalg = new RSACryptoServiceProvider ();

String str_private_key = Convert.tobase64string (Rsaalg.exportcspblob (true));
String str_public_key = Convert.tobase64string (Rsaalg.exportcspblob (false));
Console.WriteLine ("Public Key:" + Str_public_key);
Writedatetofile (@ "C:\md5\public.txt", Str_public_key);
Console.WriteLine ();
Console.WriteLine ("Private key:" + Str_private_key);
Writedatetofile (@ "C:\md5\private.txt", Str_private_key);
Console.WriteLine ();

String str_signeddata = Hashandsign (str_datatosign, Str_private_key);//Hash and sign the data.
Console.WriteLine ("Signature data:" + str_signeddata);
Writedatetofile (@ "C:\md5\sign.txt", str_signeddata);
Console.WriteLine ();

if (Verifysignedhash (Str_datatosign, Str_signeddata, Str_public_key))
{
Console.WriteLine ("Verify signature OK.");
}
Else
{
Console.WriteLine ("Signature mismatch!");
}
Console.readkey ();
}
catch (ArgumentNullException)
{
Console.WriteLine ("The data is not signed or verified");
}
}

Sign the data
public static string Hashandsign (String str_datatosign, String str_private_key)
{
ASCIIEncoding byteconverter = new ASCIIEncoding ();
byte[] datatosign = byteconverter.getbytes (str_datatosign);
Try
{
RSACryptoServiceProvider rsaalg = new RSACryptoServiceProvider ();
Rsaalg.importcspblob (convert.frombase64string (Str_private_key));
byte[] Signeddata = Rsaalg.signdata (datatosign, New SHA1CryptoServiceProvider ());
String str_signeddata = Convert.tobase64string (Signeddata);
return str_signeddata;
}
catch (Cryptographicexception e)
{
Console.WriteLine (E.message);
return null;
}
}

Verifying signatures
public static bool Verifysignedhash (string str_datatoverify, String str_signeddata, String str_public_key)
{
byte[] Signeddata = convert.frombase64string (Str_signeddata);

ASCIIEncoding byteconverter = new ASCIIEncoding ();
byte[] datatoverify = byteconverter.getbytes (str_datatoverify);
Try
{
RSACryptoServiceProvider rsaalg = new RSACryptoServiceProvider ();
Rsaalg.importcspblob (convert.frombase64string (Str_public_key));

Return Rsaalg.verifydata (datatoverify, New SHA1CryptoServiceProvider (), signeddata);

}
catch (Cryptographicexception e)
{
Console.WriteLine (E.message);

return false;
}
}

<summary>
MD5 Encryption of files
</summary>
<param name= "filepath" > File path </param>
<returns></returns>
public static string GetFileMD5 (String filepath)
{
StringBuilder sb = new StringBuilder ();
using (MD5 MD5 = MD5. Create ())
{
using (FileStream fs = File.openread (filepath))
{
byte[] newb = Md5.computehash (FS);
foreach (Byte item in NEWB)
{
Sb. Append (item. ToString ("X2"));
}
}
}

Return SB. ToString ();
}

<summary>
Write file operations
</summary>
<param name= "FilePath" ></param>
<param name= "Content" ></param>
public static void Writedatetofile (string filePath, string content)
{
using (StreamWriter SW = new StreamWriter (File.Open (FilePath, FileMode.Create, FileAccess.Write, Fileshare.none)))
{
Write file
Sw. WriteLine (content);
Sw. Flush ();
}
}
}

Related code

Implementation of RSA encryption decryption and signature and verification in C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.