Commonly Used Encryption Algorithms in C#

Commonly Used Encryption Algorithms in C# Follow Script Home and join millions of developers

Commonly Used Encryption Algorithms in C#

Author | kiba518

Produced by | Script Home (ID: jb51net)

Introduction

This article mainly explains the commonly used encryption algorithms in C#.

MD5 Encryption

MD5 encryption is the most common encryption method. Since MD5 is irreversible, many systems store passwords using MD5 encryption.

Although MD5 cannot be decoded, because the MD5 encrypted string is fixed, theoretically, one only needs to create a huge database, encrypt all strings, and then one can decode all MD5 ciphertexts.

While establishing a database that can decode all MD5s is not very realistic, a database with several billion entries can decode most strings, as in most cases, our passwords also have length limits.

In practical applications, MD5 has 64-bit and 32-bit encryption. The code is as follows:

#region MD5 Encryption 32 and 64
public static string GetMd532(string ConvertString)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
    t2 = t2.Replace("-", "");
    return t2;
}
public static string Get64Md5(string str)
{
    string cl = str;
    string pwd = "";
    var md5 = MD5.Create();
    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
    for (int i = 0; i < s.Length; i++)
    {
        pwd = pwd + s[i].ToString("X2");
    }
    return pwd;
}
#endregion

Let’s run the encryption function.

Console.WriteLine($"MD5-64:{ MD5Helper.Get64Md5("Kiba518")}");
Console.WriteLine($"MD5-32:{ MD5Helper.Get32Md5("Kiba518")}");

The results are shown in the figure below:

Commonly Used Encryption Algorithms in C#

SHA1 Encryption

The SHA1 encryption algorithm is similar to MD5 encryption; both are irreversible but differ in algorithms. Thus, like MD5, it also has the problem of being easily decoded by large datasets.

The code is as follows:

private static readonly Encoding Encoder = Encoding.UTF8;
public static String Sha1(String content)
{
    try
    {
        SHA1 sha1 = new SHA1CryptoServiceProvider(); // Create SHA1 object
        byte[] bytes_in = Encoder.GetBytes(content); // Convert the string to byte
        byte[] bytes_out = sha1.ComputeHash(bytes_in); // Hash operation
        sha1.Dispose(); // Release all resources used by the current instance
        String result = BitConverter.ToString(bytes_out); // Convert result to string
        result = result.Replace("-", "").ToUpper();
        return result;
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

Run the encryption function; the result is shown in the figure below:

Commonly Used Encryption Algorithms in C#

Base64 Encryption

To be precise, Base64 is an encoding rather than encryption. Typically, Base64 encoded strings are used for data transmission. However, due to the unreadability of Base64 encoded strings, many people also use it as an encryption algorithm.

The code is as follows:

private static readonly Encoding Encoder = Encoding.UTF8;
public static string EncodeBase64(string source)
{
    string target = "";
    byte[] bytes = Encoder.GetBytes(source);
    try
    {
        target = Convert.ToBase64String(bytes);
    }
    catch
    {
        target = source;
    }
    return target;
}
public static string DecodeBase64(string result)
{
    string decode = "";
    byte[] bytes = Convert.FromBase64String(result);
    try
    {
        decode = Encoder.GetString(bytes);
    }
    catch
    {
        decode = result;
    }
    return decode;
}

Run the Base64 encoding function.

string base64Str = Base64Helper.EncodeBase64("Kiba518");
Console.WriteLine($"SHA1 Encoding:{ base64Str}");
Console.WriteLine($"SHA1 Decoding:{ Base64Helper.DecodeBase64(base64Str)}");

The results are shown in the figure below:

Commonly Used Encryption Algorithms in C#

DES Encryption

DES encryption algorithm keeps the key secret, and only those with the same key can decrypt.

The DES encryption algorithm requires the key to be 8 characters long, such as abcdefgh.

The code is as follows:

public static string Encrypt(string stringToEncrypt, string shortKey)
{
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(stringToEncrypt);
    des.Key = ASCIIEncoding.UTF8.GetBytes(shortKey);
    des.IV = ASCIIEncoding.UTF8.GetBytes(shortKey);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();
    StringBuilder ret = new StringBuilder();
    foreach (byte b in ms.ToArray())
    {
        ret.AppendFormat("{0:X2}", b);
    }
    ret.ToString();
    return ret.ToString();}
public static string Decrypt(string stringToDecrypt, string sKey)
{
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    byte[] inputByteArray = new byte[stringToDecrypt.Length / 2];
    for (int x = 0; x < stringToDecrypt.Length / 2; x++)
    {
        int i = (Convert.ToInt32(stringToDecrypt.Substring(x * 2, 2), 16));
        inputByteArray[x] = (byte)i;
    }
    des.Key = ASCIIEncoding.UTF8.GetBytes(sKey);
    des.IV = ASCIIEncoding.UTF8.GetBytes(sKey);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();
    StringBuilder ret = new StringBuilder();
    return System.Text.Encoding.Default.GetString(ms.ToArray());}

As shown in the code, we use the DESCryptoServiceProvider class for DES encryption.

The Mode property of the DESCryptoServiceProvider class can specify the encryption operation mode.

The encryption operation modes are as follows:

  • CBC: Cipher Block Chaining mode.

  • ECB: Electronic Codebook mode.

  • OFB: Output Feedback mode.

  • CFB: Cipher Feedback mode.

  • CTS: Cipher Text Stealing mode.

In C#, the default encryption operation mode is CBC—Cipher Block Chaining mode.

In Java, the default encryption operation mode is ECB—Electronic Codebook mode.

That is, if the ciphertext is transmitted between C# and Java projects, the same encryption operation mode must be configured.

Run the DES encryption function code as follows:

string key_8 = "abcdefgh";
string desShortKeyStr = DESHelper.Encrypt("Kiba518", key_8);
Console.WriteLine($"DES Encryption:{ desShortKeyStr}");
Console.WriteLine($"DES Decryption:{ DESHelper.Decrypt(desShortKeyStr, key_8)}");

The results are shown in the figure below:

Commonly Used Encryption Algorithms in C#

Sometimes, if our key is not exactly 8 characters, we can take the first 8 characters as the key.

RSA Encryption

RSA encryption uses a public key for encryption and a private key for decryption. The HTTPS digital certificate also uses this mode of encryption.

The code is as follows:

public static string RSADecrypt(string xmlPrivateKey, string enptStr)
{
    RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    provider.FromXmlString(xmlPrivateKey);
    byte[] rgb = Convert.FromBase64String(enptStr);
    byte[] bytes = provider.Decrypt(rgb, RSAEncryptionPadding.OaepSHA1);
    return new UnicodeEncoding().GetString(bytes);
}
public static string RSAEncrypt(string xmlPublicKey, string enptStr)
{
    RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    provider.FromXmlString(xmlPublicKey);
    byte[] bytes = new UnicodeEncoding().GetBytes(enptStr);
    return Convert.ToBase64String(provider.Encrypt(bytes, RSAEncryptionPadding.OaepSHA1));
}

Run the DES encryption function code as follows:

// Encryption public key  
string publicKey = "<rsakeyvalue><modulus>18+I2j3HU/fXQasRXOWGegP3dG75I/It2n42rgeIATeftBkoQNH73Rz0IYW++arqd0Yy5hFpNkqzY/dOmD+bDXWUheWA0P/dVZf+qeWwVV+iW3lRAU8SmnPcaD35Ic1jMEPFQVeX1zGI2ofD8aGodeSRA4+JKo+KLgyGVGDI+d0=</modulus><exponent>AQAB</exponent></rsakeyvalue>";
// Decryption private key 
string privateKey = "<rsakeyvalue>  <modulus>18+I2j3HU/fXQasRXOWGegP3dG75I/It2n42rgeIATeftBkoQNH73Rz0IYW++arqd0Yy5hFpNkqzY/dOmD+bDXWUheWA0P/dVZf+qeWwVV+iW3lRAU8SmnPcaD35Ic1jMEPFQVeX1zGI2ofD8aGodeSRA4+JKo+KLgyGVGDI+d0=</modulus><exponent>AQAB</exponent><p>2EEAI+cO1fyvmGpg3ywMLHHZ1/X3ZrF6xZBNM2AL7bJFVfL8RS8UznUCdsL/R/o1b+lGo1CetlI++n6IvYYwyw==</p><q>/3muAXWOU3SMKFWSDpHUgeM9kZev0ekQDefRSayXM8q9ItkaWTOJcIN614A0UGdYE6VX1ztPgveQFzm0qJDy9w==</q><dp>NM/i/eGewOmd5IYONFJogq4nOlOKYNz1E6yC/gn1v83qmuvlaevuk+EFggVrHKPhSvxYUOgOao45bSlbsZVE8w==</dp><dq>MKU7w91dh3iWw4tfr1SHUWAytglbGi41t2Af0taBSARftUX/pWKR1hHDD0vDKlgzRjJiooIRps966WE8jChliw==</dq><inverseq>YEIfQArVNP27AJn3WOBswHP/+gJ6Bk434MZ80CJONp4b6e+Ilxd2dwloxGKNbGgCyaNJEFI5J8qYSNNe0KqPkw==</inverseq><d>ZAscSPesqLtS+WlBMkxgy719AGfVbRl+sjQiSwjIvq+3hDjJVUtCs90RO10SDBF0gfhz7f2SRY3ZnXTu5VtPF9KEQyUaY0F6eXwz4YQNzJTI2c1o5SFXZP8Ynqwltg8gNIhMe8bB6nVgASeADBim22DlSFCzmD3vt1gTI8nxmO0=</d></rsakeyvalue>";
string myname = "my name is Kiba518!my name is Kiba518!!!!43"; // Maximum length 43
string rsaStr = RSAHelper.RSAEncrypt(publicKey, myname);
Console.WriteLine($"RSA Encryption:{ rsaStr}");
string dersaStr = RSAHelper.RSADecrypt(privateKey, rsaStr);
Console.WriteLine($"RSA Decryption:{ dersaStr}");

The results are shown in the figure below:

Commonly Used Encryption Algorithms in C#

RSA encryption has a characteristic that it has a length limit for the string being encrypted.

Length limit rule: The number of bytes to be encrypted cannot exceed the key length divided by 8 minus 11 (i.e., RSACryptoServiceProvider.KeySize / 8 – 11), while the byte count of the resulting ciphertext is exactly the key length divided by 8 (i.e., RSACryptoServiceProvider.KeySize / 8). Note: This length refers to the length of the byte[] array, not the length of the string.

In simple terms, the string to be encrypted cannot be too long.

However, in real business, the strings we need to encrypt are often very long. So what should we do in this case, given that RSA has a length limit? It’s simple: split the string to be encrypted into segments, each with a length less than or equal to the limit, and encrypt each segment. This solves the problem.

The code for segmented encryption is as follows:

public static String SubRSAEncrypt(string xmlPublicKey, string enptStr)
{
    RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    provider.FromXmlString(xmlPublicKey);
    Byte[] bytes = Encoder.GetBytes(enptStr);
    int MaxBlockSize = provider.KeySize / 8 - 11; // Maximum length limit for encryption blocks
    if (bytes.Length <= MaxBlockSize)
        return Convert.ToBase64String(provider.Encrypt(bytes, false));
    using (MemoryStream PlaiStream = new MemoryStream(bytes))
    using (MemoryStream CrypStream = new MemoryStream())
    {
        Byte[] Buffer = new Byte[MaxBlockSize];
        int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
        while (BlockSize > 0)
        {
            Byte[] ToEncrypt = new Byte[BlockSize];
            Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize);
            Byte[] Cryptograph = provider.Encrypt(ToEncrypt, false);
            CrypStream.Write(Cryptograph, 0, Cryptograph.Length);
            BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
        }
        return Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None);
    }}
/// <summary>
/// Segmented decryption to handle long strings
/// </summary>
public static String SubRSADecrypt(string xmlPublicKey, string enptStr)
{
    RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    provider.FromXmlString(xmlPublicKey);
    Byte[] bytes = Convert.FromBase64String(enptStr);
    int MaxBlockSize = provider.KeySize / 8; // Maximum length limit for decryption blocks
    if (bytes.Length <= MaxBlockSize)
        return Encoder.GetString(provider.Decrypt(bytes, false));
    using (MemoryStream CrypStream = new MemoryStream(bytes))
    using (MemoryStream PlaiStream = new MemoryStream())
    {
        Byte[] Buffer = new Byte[MaxBlockSize];
        int BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);
        while (BlockSize > 0)
        {
            Byte[] ToDecrypt = new Byte[BlockSize];
            Array.Copy(Buffer, 0, ToDecrypt, 0, BlockSize);
            Byte[] Plaintext = provider.Decrypt(ToDecrypt, false);
            PlaiStream.Write(Plaintext, 0, Plaintext.Length);
            BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);
        }
        return Encoder.GetString(PlaiStream.ToArray());
    }}

The results are shown in the figure below:

Commonly Used Encryption Algorithms in C#

Conclusion

This concludes the introduction to the commonly used encryption algorithms in C#. Below, let’s take a look at the situation after encrypting the same string.

Commonly Used Encryption Algorithms in C#

As you can see, the length of the ciphertext obtained from different encryption methods varies, with the ciphertext length of DES encryption in Base64 encoding being the shortest, while RSA encryption produces the longest ciphertext.

The code has been uploaded to GitHub. Feel free to download it.

GitHub link: https://github.com/kiba518/EncryptionDemo

Author of this article: kiba518, .NET System Architect

Statement: This article is submitted by the author of the Script Home column. Please do not repost without permission.

Like what you read? Show your appreciation!

Commonly Used Encryption Algorithms in C#

Long press to scan and appreciate me

Commonly Used Encryption Algorithms in C#Commonly Used Encryption Algorithms in C#

Commonly Used Encryption Algorithms in C# Latest internal test codes! Ali Cloud Disk & Teambition Disk are here!

Commonly Used Encryption Algorithms in C# Does everyone owe Microsoft a genuine version?

Commonly Used Encryption Algorithms in C# After going to two outsourcing companies, it overturned my cognition!

● This miraculous operation! I refactored 3000 lines of code into 15 lines!

Points redemption, come and redeem!

Commonly Used Encryption Algorithms in C#

Leave a Comment