In the C # program, you may be familiar with the MD5 encryption and decryption method, but you may not be familiar with RSA. The following describes the RSA encryption and decryption algorithms:
Using system;
Using system. Security. cryptography;
Using system. text;
Class rsacspsample
{
Static void main ()
{
Try
{
String str_plain_text = "how are you? How are you? How are you? How are you? =-Popopola ";
Console. writeline ("plaintext:" + str_plain_text );
Console. writeline ("Length:" + str_plain_text.length.tostring ());
Console. writeline ();
Rsacryptoserviceprovider RSA = new rsacryptoserviceprovider ();
String str_public_key;
String str_private_key;
String str_cypher_text = rsa_encrypt (str_plain_text, out str_public_key, out str_private_key );
Console. writeline ("ciphertext:" + str_cypher_text );
Console. writeline ("Public Key:" + str_public_key );
Console. writeline ("Private Key:" + str_private_key );
String str_plain_text2 = rsa_decrypt (str_cypher_text, str_private_key );
Console. writeline ("decryption:" + str_plain_text2 );
Console. writeline ();
}
Catch (argumentnullexception)
{
Console. writeline ("encryption failed .");
}
}
// RSA encryption: Generates public/private key pairs randomly and returns them as output parameters.
Static Public String rsa_encrypt (string str_plain_text, out string str_public_key, out string str_private_key)
{
Str_public_key = "";
Str_private_key = "";
Unicodeencoding byteconverter = new unicodeencoding ();
Byte [] datatoencrypt = byteconverter. getbytes (str_plain_text );
Try
{
Rsacryptoserviceprovider RSA = new rsacryptoserviceprovider ();
Str_public_key = convert. tobase64string (RSA. exportcspblob (false ));
Str_private_key = convert. tobase64string (RSA. exportcspblob (true ));
// OAEP padding is only available on Microsoft Windows XP or later.
Byte [] bytes_cypher_text = RSA. Encrypt (datatoencrypt, false );
Str_public_key = convert. tobase64string (RSA. exportcspblob (false ));
Str_private_key = convert. tobase64string (RSA. exportcspblob (true ));
String str_cypher_text = convert. tobase64string (bytes_cypher_text );
Return str_cypher_text;
}
Catch (cryptographicexception E)
{
Console. writeline (E. Message );
Return NULL;
}
}
// RSA decryption
Static Public String rsa_decrypt (string str_cypher_text, string str_private_key)
{
Byte [] datatodecrypt = convert. frombase64string (str_cypher_text );
Try
{
Rsacryptoserviceprovider RSA = new rsacryptoserviceprovider ();
// RSA. importparameters (rsakeyinfo );
Byte [] bytes_public_key = convert. frombase64string (str_private_key );
RSA. importcspblob (bytes_public_key );
// OAEP padding is only available on Microsoft Windows XP or later.
Byte [] bytes_plain_text = RSA. decrypt (datatodecrypt, false );
Unicodeencoding byteconverter = new unicodeencoding ();
String str_plain_text = byteconverter. getstring (bytes_plain_text );
Return str_plain_text;
}
Catch (cryptographicexception E)
{
Console. writeline (E. tostring ());
Return NULL;
}
}
}