التشفير في C# (.NET): التشفير والتجزئة
أمان البيانات هو أحد الجوانب الرئيسية في التطوير الحديث. توفر منصة .NET مجموعة أدوات قوية ومرنة لحماية المعلومات المشفرة في مساحة الأسماء System.Security.Cryptography. في هذه المقالة، سنستعرض الإمكانيات الرئيسية للتشفير في C# (.NET): التشفير المتماثل وغير المتماثل، تجزئة كلمات المرور، وإنشاء التوقيعات الرقمية.
1. التشفير المتماثل (AES)
يستخدم التشفير المتماثل نفس المفتاح لتشفير وفك تشفير البيانات. الخوارزمية الأكثر شيوعًا هي AES (معيار التشفير المتقدم). في .NET، يتم تنفيذها بواسطة الفئة Aes.
مثال على تشفير وفك تشفير سلسلة باستخدام AES:
using System;using System.IO;using System.Security.Cryptography;using System.Text;
public class AesExample{ public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV) { using (Aes aes = Aes.Create()) { aes.Key = Key; aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } return msEncrypt.ToArray(); } } } }
public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV) { using (Aes aes = Aes.Create()) { aes.Key = Key; aes.IV = IV;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { return srDecrypt.ReadToEnd(); } } } } }}2. التشفير غير المتماثل (RSA)
يستخدم التشفير غير المتماثل زوجًا من المفاتيح: مفتاح عام (public key) للتشفير ومفتاح خاص (private key) لفك التشفير. في .NET، يتم تنفيذ هذه الآلية بواسطة الفئة RSA. غالبًا ما يُستخدم RSA لنقل المفاتيح المتماثلة بشكل آمن.
مثال على توليد المفاتيح والتشفير باستخدام RSA:
using System;using System.Security.Cryptography;using System.Text;
public class RsaExample{ public static void RsaEncryptDecrypt() { using (RSA rsa = RSA.Create()) { // توليد المفاتيح (2048 بت) RSAParameters publicKey = rsa.ExportParameters(false); // المفتاح العام فقط RSAParameters privateKey = rsa.ExportParameters(true); // كلا المفتاحين
string original = "رسالة سرية لـ RSA";
// التشفير باستخدام المفتاح العام byte[] encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(original), RSAEncryptionPadding.OaepSHA256);
// فك التشفير باستخدام المفتاح الخاص byte[] decryptedData = rsa.Decrypt(encryptedData, RSAEncryptionPadding.OaepSHA256); string decrypted = Encoding.UTF8.GetString(decryptedData);
Console.WriteLine($"الأصل: {original}"); Console.WriteLine($"تم فك التشفير: {decrypted}"); } }}3. تجزئة البيانات (SHA-256, MD5)
التجزئة