Encrypt/Decrypt string in .NET?

Here's a working example derived from the RijndaelManaged Class" documentation and the MCTS Training Kit Good luck!

Here's a working example derived from the "RijndaelManaged Class" documentation and the MCTS Training Kit. Good luck! Public class Crypto { private static byte _salt = Encoding.ASCII.

GetBytes("o6806642kbM7c5"); /// /// Encrypt the given string using AES. The string can be decrypted using /// DecryptStringAES(). The sharedSecret parameters must match.

/// /// The text to encrypt. /// A password used to generate a key for encryption. Public static string EncryptStringAES(string plainText, string sharedSecret) { if(string.

IsNullOrEmpty(plainText)) throw new ArgumentNullException("plainText"); if(string. IsNullOrEmpty(sharedSecret)) throw new ArgumentNullException("sharedSecret"); string outStr = null; // Encrypted string to return RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data. Try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create a RijndaelManaged object // with the specified key and IV.

AesAlg = new RijndaelManaged(); aesAlg. Key = key. GetBytes(aesAlg.

KeySize / 8); aesAlg. IV = key. GetBytes(aesAlg.

BlockSize / 8); // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg. CreateEncryptor(aesAlg.

Key, aesAlg. IV); // Create the streams used for encryption. Using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.

Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. SwEncrypt. Write(plainText); } } outStr = Convert.

ToBase64String(msEncrypt.ToArray()); } } finally { // Clear the RijndaelManaged object. If (aesAlg! = null) aesAlg.Clear(); } // Return the encrypted bytes from the memory stream.

Return outStr; } /// /// Decrypt the given string. Assumes the string was encrypted using /// EncryptStringAES(), using an identical sharedSecret. /// /// The text to decrypt.

/// A password used to generate a key for decryption. Public static string DecryptStringAES(string cipherText, string sharedSecret) { if (string. IsNullOrEmpty(cipherText)) throw new ArgumentNullException("cipherText"); if (string.

IsNullOrEmpty(sharedSecret)) throw new ArgumentNullException("sharedSecret"); // Declare the RijndaelManaged object // used to decrypt the data. RijndaelManaged aesAlg = null; // Declare the string used to hold // the decrypted text. String plaintext = null; try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create a RijndaelManaged object // with the specified key and IV.

AesAlg = new RijndaelManaged(); aesAlg. Key = key. GetBytes(aesAlg.

KeySize / 8); aesAlg. IV = key. GetBytes(aesAlg.

BlockSize / 8); // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg. CreateDecryptor(aesAlg.

Key, aesAlg. IV); // Create the streams used for decryption. Byte bytes = Convert.

FromBase64String(cipherText); using (MemoryStream msDecrypt = new MemoryStream(bytes)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode. Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) // Read the decrypted bytes from the decrypting stream // and place them in a string. Plaintext = srDecrypt.ReadToEnd(); } } } finally { // Clear the RijndaelManaged object.

If (aesAlg! = null) aesAlg.Clear(); } return plaintext; } }.

1 To Bret - hi thx for your example. Maybye one think - I had issue with key leng - I did modification with MD5, so if somebody will use your example in the feature pls use this for key normalization(or you can use other hash algoritm: HashAlgorithm hash = new MD5CryptoServiceProvider(); UnicodeEncoding UE = new UnicodeEncoding(); byte key = hash. ComputeHash(UE.

GetBytes(encrypt_password)); ps:sorry for my english :) slinti – user593912 Jan 29 at 16:19.

Here is an example using RSA. Replace your_rsa_key with your RSA key. Var provider = new System.Security.Cryptography.

RSACryptoServiceProvider(); provider. ImportParameters(your_rsa_key); var encryptedBytes = provider. Encrypt( System.Text.Encoding.

UTF8. GetBytes(""), true); string decryptedTest = System.Text.Encoding. UTF8.

GetString( provider. Decrypt(encryptedBytes, true)); For more info, visit MSDN - RSACryptoServiceProvider.

– Akash Kava Nov 5 '09 at 17:36 3 Akash Kava: Why don't you ask it on stackoverflow. Com's sister site, superuser.Com? – DrJokepu Nov 5 '09 at 18:36 1 Why RSA?

RSA has its uses, but nothing indicated that this is one of them. – CodeInChaos Jul 17 at 13:35 @CodeInChaos: Because when I have provided this answer, almost 3 years ago, the question originally didn't indicate anything. That was added later.

I have answered the original question. Look at the question history and see it for yourself. – DrJokepu Jul 26 at 23:35 2 Even in the original question there is no indication that RSA might be a good fit.

Asymmetric encryption has its uses, but it's not the right choice as a default encryption. Your example code will fail for longer strings because the RSA class isn't designed for general purpose encryption. If you need the asymmetric features you should encrypt a symmetric key with RSA and encrypt the actual data with that symmetric key.

So I still believe your answer is bad advice. – CodeInChaos Jul 27 at 9:08.

Every other answer pretty much covered using the . Net cryptography classes. Whatever you do, please don't try to make up your own encryption technique.

This never ends well. Unless you are a world-class mathematician with a team of other mathematicians, you have no reason for trying to improve that wheel.

Love your nick name :-) – aristo May 29 at 14:28.

Here is a working example: codeproject.com/KB/security/DotNetCrypto....

Good as a tutorial, but uses a lot of deprecated methods...not surprising since the code sample is from 2003. – Adam Neal Sep 16 at 13:04.

Using System; using System. Data; using System. Configuration; using System.

Text; using System.Security. Cryptography; namespace Encription { class CryptorEngine { public static string Encrypt(string ToEncrypt, bool useHasing) { byte keyArray; byte toEncryptArray = UTF8Encoding. UTF8.

GetBytes(ToEncrypt); //System.Configuration. AppSettingsReader settingsReader = new AppSettingsReader(); string Key = "Bhagwati"; if (useHasing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5. ComputeHash(UTF8Encoding.

UTF8. GetBytes(Key)); hashmd5.Clear(); } else { keyArray = UTF8Encoding. UTF8.

GetBytes(Key); } TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider(); tDes. Key = keyArray; tDes. Mode = CipherMode.

ECB; tDes. Padding = PaddingMode. PKCS7; ICryptoTransform cTransform = tDes.CreateEncryptor(); byte resultArray = cTransform.

TransformFinalBlock(toEncryptArray, 0, toEncryptArray. Length); tDes.Clear(); return Convert. ToBase64String(resultArray, 0, resultArray.

Length); } public static string Decrypt(string cypherString, bool useHasing) { byte keyArray; byte toDecryptArray = Convert. FromBase64String(cypherString); //byte toEncryptArray = Convert. FromBase64String(cypherString); //System.Configuration.

AppSettingsReader settingReader = new AppSettingsReader(); string key = "Bhagwati"; if (useHasing) { MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider(); keyArray = hashmd. ComputeHash(UTF8Encoding. UTF8.

GetBytes(key)); hashmd.Clear(); } else { keyArray = UTF8Encoding. UTF8. GetBytes(key); } TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider(); tDes.

Key = keyArray; tDes. Mode = CipherMode. ECB; tDes.

Padding = PaddingMode. PKCS7; ICryptoTransform cTransform = tDes.CreateDecryptor(); try { byte resultArray = cTransform. TransformFinalBlock(toDecryptArray, 0, toDecryptArray.

Length); tDes.Clear(); return UTF8Encoding. UTF8. GetString(resultArray,0,resultArray.

Length); } catch (Exception ex) { throw ex; } } } }.

Take a look at the System.Security. Cryptography namespace. Those classes should work in both the Microsoft and Mono implementations.

What kind of encryption are you trying to do?

Needed something simple... this link worked for me saipanyam.net/2010/03/encrypt-query-stri....

Mono already supports the same classes that Microsoft . NET does when it comes to encryption. So you can use DES, AES, RSA, or whatever you want.

I have used this method in the past C# encryption.

Try this one, Symmetric key encryption and decryption using Rijndael algorithm: obviex.com/samples/Code.aspx?Source=Encr....

Here's a working example derived from the "RijndaelManaged Class" documentation and the MCTS Training Kit .

Here is an example using RSA. Replace your_rsa_key with your RSA key.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions