Answered by:
Encrypt and Decrypt a String in c#

Question
-
Hi,
How to encrypt and decrypt a given string using any possible algorithm. I need the code in C#. Can someone pls help ?
Thanks
Thursday, July 12, 2012 11:30 AM
Answers
-
Hi,
Check with,
you can change these
static readonly string PasswordHash = "P@@Sw0rd"; static readonly string SaltKey = "S@LT&KEY"; static readonly string VIKey = "@1B2c3D4e5F6g7H8";
for encrypt
public static string Encrypt(string plainText) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); byte[] cipherTextBytes; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); cryptoStream.Close(); } memoryStream.Close(); } return Convert.ToBase64String(cipherTextBytes); }
to decrypt
public static string Decrypt(string encryptedText) { byte[] cipherTextBytes = Convert.FromBase64String(encryptedText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None }; var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); var memoryStream = new MemoryStream(cipherTextBytes); var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray()); }
I hope this helps you...If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".
Thursday, July 12, 2012 5:49 PM -
Here is an encrption using popular RSA Alogorithm.
public string EncryptString( string inputString, int dwKeySize, string xmlString ) { RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider( dwKeySize ); rsaCryptoServiceProvider.FromXmlString( xmlString ); int keySize = dwKeySize / 8; byte[] bytes = Encoding.UTF32.GetBytes( inputString ); RSACryptoServiceProvider here int maxLength = keySize - 42; int dataLength = bytes.Length; int iterations = dataLength / maxLength; StringBuilder stringBuilder = new StringBuilder(); for( int i = 0; i <= iterations; i++ ) { byte[] tempBytes = new byte[ ( dataLength - maxLength * i > maxLength ) ? maxLength : dataLength - maxLength * i ]; Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, tempBytes.Length ); byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes, true ); stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) ); } return stringBuilder.ToString(); } public string DecryptString( string inputString, int dwKeySize, string xmlString ) { RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider( dwKeySize ); rsaCryptoServiceProvider.FromXmlString( xmlString ); int base64BlockSize = ( ( dwKeySize / 8 ) % 3 != 0 ) ? ( ( ( dwKeySize / 8 ) / 3 ) * 4 ) + 4 : ( ( dwKeySize / 8 ) / 3 ) * 4; int iterations = inputString.Length / base64BlockSize; ArrayList arrayList = new ArrayList(); for( int i = 0; i < iterations; i++ ) { byte[] encryptedBytes = Convert.FromBase64String( inputString.Substring( base64BlockSize * i, base64BlockSize ) ); Array.Reverse( encryptedBytes ); arrayList.AddRange( rsaCryptoServiceProvider.Decrypt( encryptedBytes, true ) ); } return Encoding.UTF32.GetString( arrayList.ToArray( Type.GetType( "System.Byte" ) ) as byte[] ); }
2) Here is one example in MSDN for md5static void Main(string[] args) { string source = "Hello World!"; using (MD5 md5Hash = MD5.Create()) { string hash = GetMd5Hash(md5Hash, source); Console.WriteLine("The MD5 hash of " + source + " is: " + hash + "."); Console.WriteLine("Verifying the hash..."); if (VerifyMd5Hash(md5Hash, source, hash)) { Console.WriteLine("The hashes are the same."); } else { Console.WriteLine("The hashes are not same."); } } } static string GetMd5Hash(MD5 md5Hash, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } // Verify a hash against a string. static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash) { // Hash the input. string hashOfInput = GetMd5Hash(md5Hash, input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; if (0 == comparer.Compare(hashOfInput, hash)) { return true; } else { return false; } }
Thursday, July 12, 2012 12:51 PM -
All replies
-
Thursday, July 12, 2012 11:32 AM
-
Look here:
Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...Thursday, July 12, 2012 11:41 AM -
Thursday, July 12, 2012 11:59 AM
-
Here is an encrption using popular RSA Alogorithm.
public string EncryptString( string inputString, int dwKeySize, string xmlString ) { RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider( dwKeySize ); rsaCryptoServiceProvider.FromXmlString( xmlString ); int keySize = dwKeySize / 8; byte[] bytes = Encoding.UTF32.GetBytes( inputString ); RSACryptoServiceProvider here int maxLength = keySize - 42; int dataLength = bytes.Length; int iterations = dataLength / maxLength; StringBuilder stringBuilder = new StringBuilder(); for( int i = 0; i <= iterations; i++ ) { byte[] tempBytes = new byte[ ( dataLength - maxLength * i > maxLength ) ? maxLength : dataLength - maxLength * i ]; Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, tempBytes.Length ); byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes, true ); stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) ); } return stringBuilder.ToString(); } public string DecryptString( string inputString, int dwKeySize, string xmlString ) { RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider( dwKeySize ); rsaCryptoServiceProvider.FromXmlString( xmlString ); int base64BlockSize = ( ( dwKeySize / 8 ) % 3 != 0 ) ? ( ( ( dwKeySize / 8 ) / 3 ) * 4 ) + 4 : ( ( dwKeySize / 8 ) / 3 ) * 4; int iterations = inputString.Length / base64BlockSize; ArrayList arrayList = new ArrayList(); for( int i = 0; i < iterations; i++ ) { byte[] encryptedBytes = Convert.FromBase64String( inputString.Substring( base64BlockSize * i, base64BlockSize ) ); Array.Reverse( encryptedBytes ); arrayList.AddRange( rsaCryptoServiceProvider.Decrypt( encryptedBytes, true ) ); } return Encoding.UTF32.GetString( arrayList.ToArray( Type.GetType( "System.Byte" ) ) as byte[] ); }
2) Here is one example in MSDN for md5static void Main(string[] args) { string source = "Hello World!"; using (MD5 md5Hash = MD5.Create()) { string hash = GetMd5Hash(md5Hash, source); Console.WriteLine("The MD5 hash of " + source + " is: " + hash + "."); Console.WriteLine("Verifying the hash..."); if (VerifyMd5Hash(md5Hash, source, hash)) { Console.WriteLine("The hashes are the same."); } else { Console.WriteLine("The hashes are not same."); } } } static string GetMd5Hash(MD5 md5Hash, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } // Verify a hash against a string. static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash) { // Hash the input. string hashOfInput = GetMd5Hash(md5Hash, input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; if (0 == comparer.Compare(hashOfInput, hash)) { return true; } else { return false; } }
Thursday, July 12, 2012 12:51 PM -
-
Its simple, you can do like this:
public static string Encrypt(string data) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Mode = CipherMode.ECB; DES.Key = GetKey("a1!B78s!5("); DES.Padding = PaddingMode.PKCS7; ICryptoTransform DESEncrypt = DES.CreateEncryptor(); Byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(data); return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); } public static string Decrypt(string data) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Mode = CipherMode.ECB; DES.Key = GetKey("a1!B78s!5("); DES.Padding = PaddingMode.PKCS7; ICryptoTransform DESEncrypt = DES.CreateDecryptor(); Byte[] Buffer = Convert.FromBase64String(data.Replace(" ","+")); return Encoding.UTF8.GetString(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); }
And when you want call you make: Encrypt("blablablabla") or Decrypt("891bw01s13")- Edited by Norkk Thursday, July 12, 2012 1:41 PM
Thursday, July 12, 2012 1:41 PM -
Hi,
Check with,
you can change these
static readonly string PasswordHash = "P@@Sw0rd"; static readonly string SaltKey = "S@LT&KEY"; static readonly string VIKey = "@1B2c3D4e5F6g7H8";
for encrypt
public static string Encrypt(string plainText) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); byte[] cipherTextBytes; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); cryptoStream.Close(); } memoryStream.Close(); } return Convert.ToBase64String(cipherTextBytes); }
to decrypt
public static string Decrypt(string encryptedText) { byte[] cipherTextBytes = Convert.FromBase64String(encryptedText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None }; var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); var memoryStream = new MemoryStream(cipherTextBytes); var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray()); }
I hope this helps you...If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".
Thursday, July 12, 2012 5:49 PM -
what is GetKey("...") actually calling when you do DES.Key. There is not method in your code called GetKey.
Friday, July 12, 2013 1:22 PM -
@Kris444
Great piece of code, I've used it in a messaging program across my network.
What is this encryption method called? Like if I wanted to decrypt messages in another program, not written in C#, like on a Mac for example, how would I go about doing that?Thanks :D
Wednesday, August 14, 2013 12:54 AM -
There's a bug above in the EncryptString() function: You need to comment out the line with:
"RSACryptoServiceProvider here"
This was inadvertently left behind as part of an earlier comment.
Sunday, October 26, 2014 3:00 AM -
Hi, can this be used for commercial use?
Thanks
Thursday, June 18, 2015 9:58 AM -
found the missing peace here:
http://stackoverflow.com/a/30187412/1411724
- Edited by Avraham Essoudry Monday, November 21, 2016 1:47 PM
Monday, November 21, 2016 1:47 PM -
The encryption used here is how many bit encryption
Thursday, July 13, 2017 3:11 AM -
I keep getting error saying in quotes "specified initialization vector (IV) does not match the block size for this algorithm."
Please help
Thursday, July 13, 2017 3:17 AM -
please, what algorithm or method that you had use in this encrypt, decryptFriday, May 11, 2018 2:14 PM
-
Encrypt/Decrypt is different from encode/decode.
You need passkey to encrypt/decrypt a message so only people who hold the key can get the original message, while you don't need one to encode/decode a message so anyone can get the original one.
Btw, don't needlessly dig an old thread.
- Edited by cheong00Editor Thursday, May 17, 2018 10:07 AM
Thursday, May 17, 2018 10:06 AMAnswerer -
I know that this is from 2012 but im getting an error on the GetKey, do you still have the metod?
Thanks
- Proposed as answer by Satyajit Prakash Tuesday, May 21, 2019 10:46 PM
- Unproposed as answer by Satyajit Prakash Tuesday, May 21, 2019 10:53 PM
Wednesday, December 12, 2018 6:45 PM -
You can use the below method.
public static byte[] GetKey(string strKey) { byte[] Key = Convert.FromBase64String(strKey); return Key; }
Tuesday, May 21, 2019 11:04 PM -
using System;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using System.Text;
class
Program
{
privatestaticRSAParameterspublicKey;
privatestaticRSAParametersprivateKey;
publicenumKeySizes
{
SIZE_512 = 512,
SIZE_1024 = 1024,
SIZE_2048 = 2048,
SIZE_4096 = 4096
}
staticvoidMain(string[] args)
{
stringprivateKeyFile = System.AppDomain.CurrentDomain.BaseDirectory + "PrivateKey2.xml";
//string publicKeyFile = System.AppDomain.CurrentDomain.BaseDirectory + "PublicKey2.xml";
////GenerateRsa(privateKeyPath, publicKeyPath, 2048)
stringCiphertext = "PLLX2FuYEYmLD08eD56bgz/xYJJv4Cmtz9S96bm2wgvi4QN8YJ9XggAlkqkwEE+DKPGIY7S2FZc3djswFPn2bv8pNteA6xNcJZEIA4gF57ekBZh6lzoLFXex3kQO0v4g3iWqPfmuN62oEkAhLe3DYaIgt19AX8DJKPEfP/UNyikrAn6YA73kSLePogZHszDXGLMSHrZS1QdLnhEbkVRVQr8iCi2pcsChNR1ZqiObFQp2ErJ6JFqrFEoX8Dbm88Xam/pubtxPX6e5EPxIyB+YmliDVeGm/RL5+LOf7sSospoQPl3oKeummtWHInaLTHEJ58FYOMdEn6oTYykkTiKxsQ==";
byte[] Encrypted = Convert.FromBase64String(Ciphertext);
byte[] decrypted = Decrypt(privateKeyFile, Encrypted);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(decrypted));
Console.ReadLine();
}
privatestaticbyte[] Decrypt(stringprivateKeyFile, byte[] Encrypted)
{
byte[] decodedtxt;
using(varrsa = newRSACryptoServiceProvider((int)2048))
{
rsa.PersistKeyInCsp =
false;
stringprivateKey = File.ReadAllText(privateKeyFile);
rsa.FromXmlString(privateKey);
decodedtxt = rsa.Decrypt(Encrypted,
false);
}
returndecodedtxt;
}
}
For Encryption below is the code
void Encrypt(public_key);
public voidEncrypt(stringpublic_key)
{
privateRSACryptoServiceProvidercipher = null;
RSACryptoServiceProvider cipher = newRSACryptoServiceProvider();
cipher.FromXmlString(public_key);
byte[] data = Encoding.UTF8.GetBytes(txtUnencrypt.Text);
byte[] cipherText = cipher.Encrypt(data, false);
lblUnencryptMessage.Text = Convert.ToBase64String(cipherText);
}
Tuesday, September 24, 2019 12:35 PM -
using System;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using System.Text;
class
Program
{
privatestaticRSAParameterspublicKey;
privatestaticRSAParametersprivateKey;
publicenumKeySizes
{
SIZE_512 = 512,
SIZE_1024 = 1024,
SIZE_2048 = 2048,
SIZE_4096 = 4096
}
staticvoidMain(string[] args)
{
stringprivateKeyFile = System.AppDomain.CurrentDomain.BaseDirectory + "PrivateKey2.xml";
//string publicKeyFile = System.AppDomain.CurrentDomain.BaseDirectory + "PublicKey2.xml";
////GenerateRsa(privateKeyPath, publicKeyPath, 2048)
stringCiphertext = "PLLX2FuYEYmLD08eD56bgz/xYJJv4Cmtz9S96bm2wgvi4QN8YJ9XggAlkqkwEE+DKPGIY7S2FZc3djswFPn2bv8pNteA6xNcJZEIA4gF57ekBZh6lzoLFXex3kQO0v4g3iWqPfmuN62oEkAhLe3DYaIgt19AX8DJKPEfP/UNyikrAn6YA73kSLePogZHszDXGLMSHrZS1QdLnhEbkVRVQr8iCi2pcsChNR1ZqiObFQp2ErJ6JFqrFEoX8Dbm88Xam/pubtxPX6e5EPxIyB+YmliDVeGm/RL5+LOf7sSospoQPl3oKeummtWHInaLTHEJ58FYOMdEn6oTYykkTiKxsQ==";
byte[] Encrypted = Convert.FromBase64String(Ciphertext);
byte[] decrypted = Decrypt(privateKeyFile, Encrypted);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(decrypted));
Console.ReadLine();
}
privatestaticbyte[] Decrypt(stringprivateKeyFile, byte[] Encrypted)
{
byte[] decodedtxt;
using(varrsa = newRSACryptoServiceProvider((int)2048))
{
rsa.PersistKeyInCsp =
false;
stringprivateKey = File.ReadAllText(privateKeyFile);
rsa.FromXmlString(privateKey);
decodedtxt = rsa.Decrypt(Encrypted,
false);
}
returndecodedtxt;
}
}
For Encryption below is the code
void Encrypt(public_key);
public voidEncrypt(stringpublic_key)
{
privateRSACryptoServiceProvidercipher = null;
RSACryptoServiceProvider cipher = newRSACryptoServiceProvider();
cipher.FromXmlString(public_key);
byte[] data = Encoding.UTF8.GetBytes(txtUnencrypt.Text);
byte[] cipherText = cipher.Encrypt(data, false);
lblUnencryptMessage.Text = Convert.ToBase64String(cipherText);
}
Hello,
When posting code, please use the code button and not simply pasted code directly into a post.
Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
NuGet BaseConnectionLibrary for database connections.
Tuesday, September 24, 2019 12:43 PM -
Padding = PaddingMode.None on Decrypt should be set to Zero, as in Encrypt
Otherwise some text decrypt will fail (such as containing 0)
Thursday, April 30, 2020 8:51 PM