Skip to content
</> Mücahit TopalA developer's notebook

Blog/C#

Encryption with C#: Symmetric, Asymmetric and Hash Encryption

Mücahit Topal 7 min read 47,208 views TREN

To keep our data secure, we feel the need to encrypt our code or our data. Let's look at how they are used by working through an example of each: the algorithms used when we want to get back to the encrypted data by reversing it, and the well-known algorithms that cannot be reversed.

.Net comes with many encryption libraries ready to use. These encryption classes are located in the System.Security.Cryptography library.

First of all, it is useful to classify the encryption methods; there are currently 3 different encryption methods in the world. These are 

  1. Hash Encryption Methods
    1. MD5
    2. SHA1
    3. SHA256
    4. SHA384
    5. SHA512
  2. Symmetric Encryption Methods
    1. DES
    2. Triple DES
    3. RC2
    4. Rijndael
  3. Asymmetric Encryption Methods
    1. DSA
    2. RSA

Hash Encryption Methods

 

It is not possible to get back to the encrypted data. Suppose you encrypted 1000 characters of data with md5, sha 1, sha256 or sha512; in that case the encrypted data you get will be a string of a standard size depending on the type of algorithm. Naturally, a question like this will come up: "if I cannot get back to the data I encrypted, why should I encrypt it". The answer to this question is very simple: in some of the applications we build, we do not need to see the unencrypted data. For example, say you have opened a forum and your users will sign up to the system to enter the forum. This is where, acting as an honest programmer, it is more correct to encrypt the password the user enters with a hash algorithm and store it in our database. That way, during login, we can encrypt the data the user enters again and compare it with the encrypted data in the database. So we do not see the user's password and thereby respect the user's private information, and we also ensure data security.

public static byte[] ByteDonustur(string deger)
{

UnicodeEncoding ByteConverter = new UnicodeEncoding();
return ByteConverter.GetBytes(deger);

}

public static byte[] Byte8(string deger)
{
char[] arrayChar = deger.ToCharArray();
byte[] arrayByte = new byte[arrayChar.Length];
for (int i = 0; i < arrayByte.Length; i++)
{
arrayByte[i] = Convert.ToByte(arrayChar[i]);
}
return arrayByte;
}

MD5 Encryption

public string MD5(string strGiris)
{
if (strGiris == "" || strGiris==null)
{
throw new ArgumentNullException("No data to encrypt");
}
else
{
MD5CryptoServiceProvider sifre = new MD5CryptoServiceProvider();
byte[] arySifre = ByteDonustur(strGiris);
byte[] aryHash = sifre.ComputeHash(arySifre);
return BitConverter.ToString(aryHash);
}
}

SHA1 Encryption

public string SHA1(string strGiris)
{
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt.");
}else
{
SHA1CryptoServiceProvider sifre = new SHA1CryptoServiceProvider();
byte[] arySifre = ByteDonustur(strGiris);
byte[] aryHash = sifre.ComputeHash(arySifre);
return BitConverter.ToString(aryHash);
}
}

SHA256 Encryption

public string SHA256(string strGiris)
{
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No Data To Encrypt");
}else
{
SHA256Managed sifre = new SHA256Managed();
byte[] arySifre = ByteDonustur(strGiris);
byte[] aryHash = sifre.ComputeHash(arySifre);
return BitConverter.ToString(aryHash);
}
}

SHA384 Encryption

public string SHA384(string strGiris)
{
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt was found.");
}else
{
SHA384Managed sifre = new SHA384Managed();
byte[] arySifre = ByteDonustur(strGiris);
byte[] aryHash = sifre.ComputeHash(arySifre);
return BitConverter.ToString(aryHash);
}
}

SHA512 Encryption

public string SHA512(string strGiris)
{
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt.");
}
else
{
SHA512Managed sifre = new SHA512Managed();
byte[] arySifre = ByteDonustur(strGiris);
byte[] aryHash = sifre.ComputeHash(arySifre);
return BitConverter.ToString(aryHash);
}
}

 

Symmetric Encryption 

In symmetric encryption methods, to get to the encrypted data, the party decrypting it needs the same key as the party that encrypted the data. 

public static byte[] ByteDonustur(string deger)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
return ByteConverter.GetBytes(deger);
}

public static byte[] Byte8(string deger)
{
char[] arrayChar = deger.ToCharArray();
byte[] arrayByte = new byte[arrayChar.Length];
for (int i = 0; i < arrayByte.Length; i++)
{
arrayByte[i] = Convert.ToByte(arrayChar[i]);
}
return arrayByte;
}

DES Encryption Method with C#

public string DESSifrele(string strGiris)
{
string sonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt");
}
else
{
byte[] aryKey = Byte8("12345678"); // ENTER AN 8 bit string VALUE HERE
byte[] aryIV = Byte8("12345678"); // ENTER AN 8 bit string VALUE HERE
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(aryKey, aryIV), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cs);
writer.Write(strGiris);
writer.Flush();
cs.FlushFinalBlock();
writer.Flush();
sonuc = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
writer.Dispose();
cs.Dispose();
ms.Dispose();
}
return sonuc;
}

public string DESCoz(string strGiris)
{
string strSonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt.");
}
else
{
byte[] aryKey = Byte8("12345678");
byte[] aryIV = Byte8("12345678");
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(strGiris));
CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(aryKey, aryIV), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cs);
strSonuc = reader.ReadToEnd();
reader.Dispose();
cs.Dispose();
ms.Dispose();
}
return strSonuc;
}

TripleDES Encryption Method with C#
The TripleDES algorithm uses a 24 bit key and an 8 bit iv value.

public string Sifrele(string strGiris)
{
string sonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt.");
}
else
{
byte[] aryKey = Byte8("123456781234567812345678");
byte[] aryIV = Byte8("12345678");
TripleDESCryptoServiceProvider dec = new TripleDESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, dec.CreateEncryptor(aryKey, aryIV), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cs);
writer.Write(strGiris);
writer.Flush();
cs.FlushFinalBlock();
writer.Flush();
sonuc = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
writer.Dispose();
cs.Dispose();
ms.Dispose();
}
return sonuc;
}

public string Coz(string strGiris)
{
string strSonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt.");
}
else
{
byte[] aryKey = Byte8("123456781234567812345678");
byte[] aryIV = Byte8("12345678");
TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(strGiris));
CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(aryKey, aryIV), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cs);
strSonuc = reader.ReadToEnd();
reader.Dispose();
cs.Dispose();
ms.Dispose();
}
return strSonuc;
}

RC2 Encryption Method with C#
The RC2 algorithm uses an 8 bit key and an 8 bit iv value.

public string Sifrele(string strGiris)
{
string sonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt.");
}
else
{
byte[] aryKey = Byte8("12345678");
byte[] aryIV = Byte8("12345678");
RC2CryptoServiceProvider dec = new RC2CryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, dec.CreateEncryptor(aryKey, aryIV), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cs);
writer.Write(strGiris);
writer.Flush();
cs.FlushFinalBlock();
writer.Flush();
sonuc = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
writer.Dispose();
cs.Dispose();
ms.Dispose();
}
return sonuc;
}

public string Coz(string strGiris)
{
string strSonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to decrypt.");
}
else
{
byte[] aryKey = Byte8("12345678");
byte[] aryIV = Byte8("12345678");
RC2CryptoServiceProvider cp = new RC2CryptoServiceProvider();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(strGiris));
CryptoStream cs = new CryptoStream(ms, cp.CreateDecryptor(aryKey, aryIV), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cs);
strSonuc = reader.ReadToEnd();
reader.Dispose();
cs.Dispose();
ms.Dispose();
}
return strSonuc;
}

Rijndael Encryption Method with C#
The Rijndael algorithm uses an 8 key and a 16 bit iv value.

public string Sifrele(string strGiris)
{
string sonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to encrypt.");
}
else
{
byte[] aryKey = Byte8("12345678");
byte[] aryIV = Byte8("1234567812345678");
RijndaelManaged dec = new RijndaelManaged();
dec.Mode = CipherMode.CBC;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, dec.CreateEncryptor(aryKey, aryIV), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cs);
writer.Write(strGiris);
writer.Flush();
cs.FlushFinalBlock();
writer.Flush();
sonuc = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
writer.Dispose();
cs.Dispose();
ms.Dispose();
}
return sonuc;
}
public string Coz(string strGiris)
{
string strSonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No data to decrypt.");
}
else
{
byte[] aryKey = Byte8("12345678");
byte[] aryIV = Byte8("1234567812345678");
RijndaelManaged cp = new RijndaelManaged();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(strGiris));
CryptoStream cs = new CryptoStream(ms, cp.CreateDecryptor(aryKey, aryIV), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cs);
strSonuc = reader.ReadToEnd();
reader.Dispose();
cs.Dispose();
ms.Dispose();
}
return strSonuc;
}

Asymmetric Encryption

Asymmetric encryption methods are advanced encryption methods. In this type of algorithm, the party encrypting the data and the party that will decrypt it use different keys.

public static byte[] ByteDonustur(string deger)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
return ByteConverter.GetBytes(deger);
}

public static byte[] Byte8(string deger)
{
char[] arrayChar = deger.ToCharArray();
byte[] arrayByte = new byte[arrayChar.Length];
for (int i = 0; i < arrayByte.Length; i++)
{
arrayByte[i] = Convert.ToByte(arrayChar[i]);
}
return arrayByte;
}

RSA Encryption Method with C#

public string Sifrele(string strGiris, out RSAParameters prm)
{
string strSonuc = "";
if (strGiris == "")
{
throw new ArgumentNullException("No data to encrypt.");
}
else
{
byte[] aryDizi = ByteDonustur(strGiris);
RSACryptoServiceProvider dec = new RSACryptoServiceProvider();
prm = dec.ExportParameters(true);
byte[] aryDonus = dec.Encrypt(aryDizi, false);
strSonuc = Convert.ToBase64String(aryDonus);
}
return strSonuc;
}

public string Coz(string strGiris, RSAParameters prm)
{
string strSonuc = "";
if (strGiris == "" || strGiris == null)
{
throw new ArgumentNullException("No record to decrypt");
}
else
{
RSACryptoServiceProvider dec = new RSACryptoServiceProvider();
byte[] aryDizi = Convert.FromBase64String(strGiris);
UnicodeEncoding UE = new UnicodeEncoding();
dec.ImportParameters(prm);
byte[] aryDonus = dec.Decrypt(aryDizi, false);
strSonuc = UE.GetString(aryDonus);
}
return strSonuc;

 

If you like, you can use these encryption methods to achieve stronger encryption, or you can create your own encryption algorithm , the choice is yours...

,,,,,,,,,,,,,,,,

Share X Facebook LinkedIn WhatsApp

More from this category

Comments 10

Burak TAŞKIRAN

     Merhabalar,

     Resim şifreleme konusunda nasıl bir yol izlemem gerekiyor? Picturebox daki resmin piksellerine ulaşıp resmi puzzle gibi düşünüp herbir parçasını kendi içinde karıştırıp şifrelemem gerekiyor. Daha sonra şifrelenmiş resmi başka bir picturebox a göndermem lazım. Diğer bir butonun clickevent ına ise şifrelenmiş resmin kodunu çözecek komutları yazmam gerek.(galiba bu işlem sonunda resim ilk resim ile tıpatıp aynı olmuyormuş resmin bazı bölgeleri beyaz oluyormuş).Yukarıdaki yöntemlerden mi hareket etmem gerek, yoksa başka komutlar mı kullanmalıyım? 

admin

basit olarak ilk önce şçyle yapabilirsiniz, öncelikle resimi bir dosya olarak ele alın ve üzerinde pixel olarak değil de dosyayı byte şeklinde kullanın ve bunu yukarıdaki her hangi bir geri dönüşebilir bir şifreleme yöntemini kullanarak şifreleyin ve onu kaydedin yeniden geri çevirebilirsiniz şifrelenmiş pictureboxta da karışık bir resim gösterebilirsiniz.

Ama demek istediğiniz sanırım puzzle tarzı bir uygulama resimler net belli olacak ama yerleri değişik olacak şu linkleri inceleyebilirsiniz isterseniz:

http://csharphelper.com/blog/2014/12/make-a-jigsaw-puzzle-in-c/

http://kerimozben.com/drag-drop-mantigi-ile-puzzle-oyunu/

http:// https://social.msdn.microsoft.com/Forums/tr-TR/07e7324b-f138-4510-a455-30cca4ee115b/c-puzzle-resm-karstrma-butonu?forum=csharptr

http://jetgamedev.blogspot.com.tr/2012/05/lesson-0229-c-lab-4-create-image-puzzle.html

 

mustafa

Hocam elinize dilinize  sağlık cok güzel anlatmışsınız..

kafama takılan bunları "txt" dosyasıyla uygulayabiliyoruz ben "exe" şifrelemk istiyorum yaptıgım programın "exe" şifrelmek "exe" hem şifrelenecen hemde okunacak calışacak .Encrypt,Decrypt ikisini bir Arada  nasıl kullanırım. berber calışma ortamı nasıl oluştururum bu konuda yardımcı olurmusunuz......

Oğuzhan

Merhaba ben pascal üçgeninde ki sayılarla uygun bi yol ile çarpma işlemi yapıyorum.Bunu yaparken ordaki sayı ikilileri ile uygun bi algoritma ile yapıyorum.Ancak rsa ve hash şifreleme algoritmalarına katkı yapmak anlamında sorayım.Özünde asal sayıları ayırmak zor oluyor birde büyük basamaklı ise rsa şifreleme de asal sayı arama değil aralarında asal olan sayıları çarpanlarına ayırma mantığına dayanıyor bildiğim kadarıyla sayılar teorisi de asal sayıları kabul eder ama onu çabucak çarpanlarına ayırcak yada bi sayının asal sayı olup olmayacağını veren bi formül olduğunu öngörmez.Gerçi bu ikisi ayrı şey.Demek istediğim bu pascalda sayıları önceden bileceğiz.Bu mantıkla oluşacak çok büyük basamakta sayıları bu üçgende kullanabiliriz.Ancak metin şifrelemekten cok dış yapı kapsülasyon şifreleme de işe yarar mı diye sormak istedim.Yani kelimelere karşılık olarak metine karşılık olarak bu üçgenden sayılar secip pascal mantığı programlanabilirse  şifreleme algoritmalarına katkı sağyalabilir diye düşünüyorum.Burda hash yöntemi bana daha makul geldi.gerekirse düşündüğüm şeyi resim olarak atabilirim..

Mustafa BÜKÜLMEZ

Selam hocam 

C# ile RSA Şifreleme Yöntemi ni nasıl kullanacağız peki. Bu işlere yeni başlıyorum yani ilk defa yapacağım. Bu sebeple nasıl kullanmam gerektiğini bilmiyorum. Yardımcı olabilir misiniz?. 

admin

İlk fırsatta her biri için küçük uygulamalar hazırlamayı düşünüyorum , öncelikle bu şifreleme türleri fonksiyon olarak hazırlanmış durumda google üzerinden fonksiyon kullanımını araştırabilirsiniz.

Anonim

Hocam iyi güzelde aslında çok nasıl çözülebilir eğer ki verdiğiniz örnekten yola çıkalım. Forum açtım kullanıcı kayıt oldu.Kullanıcının parolası şifrelendi ve db eklendi. kullanıcı foruma girerken aynı şifreyi girdiğinde db deki şifrelenmiş veriyi döndüeüyorsa şifreleme yöntemi o zaman her kelimenin belli karşılığı vardır ve bunu geri çeviricide yapılabilir öyle değil mi? yoksa yanlış mı düşünüyorum.

admin

@Anonim Şifrelenen parola db de bulunuyor bunu nasıl şifrelediğiniz de önemli geri okunacak bir şifrleme türü seçmişseniz sıkıntı oluşturabilir. Hem zaten kullanıcı foruma girerken şifrelenmiş veriyi girmeyecek parolasını girecek böylelikle gelen parola aynı şifreleme fonksiyonundan geçirilip veritabanı ile karşılaştırılacak doğru ise işlem başarılı olacak. Bu şifreleme fonksiyonundan çıkan tam menti kullanmayabilirsiniz başından veya sonunda karakter silebilirsiniz veya başka bir şifreleme fonksiyonundan geçirebilirsiniz böylelikle verilerin ele geçmesi durumunda bile parolalar güvende kalma olasılığı yükselir.

Onur TURAN

Merhabalar,Bir Sorum olcaktı, SHA256 ile şifrelenmiş bir string değeri veritabanına kaydettikten sonra veritabanına erişen biri hash kodunu kopyalayıp login ekranına yapıştırıp girebilirse passwordu şifrelemek ne işe yarar ki?İlaveten, diyelim ki hangi algoritmayla haslandiğini bilmediğim bir şifre buldum bu şifreyi encode etmek için tüm algoritma tiplerini deneyerek bulamazmıyım?Teşekkürler.

Onur AYDIN

AES ile Kriptografi kütüphanesi kullanmadan nasıl şifrele ve şifreyi çöz yapılır?

Leave a comment

Comments appear after approval.