Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, July 12, 2012 11:30 AM
Hi,
How to encrypt and decrypt a given string using any possible algorithm. I need the code in C#. Can someone pls help ?
Thanks
All replies (21)
Thursday, July 12, 2012 12:51 PM ✅Answered | 5 votes
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[] );}
- Here is one example in MSDN for md5
static 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 1:29 PM ✅Answered | 1 vote
Thursday, July 12, 2012 5:49 PM ✅Answered | 38 votes
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 11:32 AM | 1 vote
http://www.codeproject.com/Articles/14150/Encrypt-and-Decrypt-Data-with-C
Thursday, July 12, 2012 11:41 AM | 1 vote
Look here:
Noam B.
Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...
Thursday, July 12, 2012 11:59 AM | 1 vote
http://dotnet-snippets.com/dns/encrypt-and-decrypt-strings-SID205.aspx
regards
joon
Thursday, July 12, 2012 1:41 PM | 1 vote
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")
Friday, July 12, 2013 1:22 PM | 2 votes
what is GetKey("...") actually calling when you do DES.Key. There is not method in your code called GetKey.
Wednesday, August 14, 2013 12:54 AM
@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
Sunday, October 26, 2014 3:00 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.
Thursday, June 18, 2015 9:58 AM
Hi, can this be used for commercial use?
Thanks
Monday, November 21, 2016 1:47 PM
found the missing peace here:
http://stackoverflow.com/a/30187412/1411724
Thursday, July 13, 2017 3:11 AM
The encryption used here is how many bit encryption
Thursday, July 13, 2017 3:17 AM
I keep getting error saying in quotes "specified initialization vector (IV) does not match the block size for this algorithm."
Please help
Friday, May 11, 2018 2:14 PM
please, what algorithm or method that you had use in this encrypt, decrypt
Thursday, May 17, 2018 10:06 AM
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.
Wednesday, December 12, 2018 6:45 PM
I know that this is from 2012 but im getting an error on the GetKey, do you still have the metod?
Thanks
Tuesday, May 21, 2019 11:04 PM
You can use the below method.
public static byte[] GetKey(string strKey)
{
byte[] Key = Convert.FromBase64String(strKey);
return Key;
}
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);
}
Tuesday, September 24, 2019 12:43 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.
Thursday, April 30, 2020 8:51 PM
Padding = PaddingMode.None on Decrypt should be set to Zero, as in EncryptOtherwise some text decrypt will fail (such as containing 0)