C# .NET - encrypt and decrypt string

Asked By alic Sunfu on 12-Jul-11 04:04 AM
Hi,
I want to encrypt and decrypt a string.
i have a string "hello" length is 5
after encrypt, length is still 5
Please help me. Thanks
Ravi S replied to alic Sunfu on 12-Jul-11 04:07 AM
HI

try htis

public class Crypto
{
    private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");
    /// <summary>
    /// Encrypt the given string using AES.  The string can be decrypted using 
    /// DecryptStringAES().  The sharedSecret parameters must match.
    /// </summary>
    /// <param name="plainText">The text to encrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
    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;
    }
    /// <summary>
    /// Decrypt the given string.  Assumes the string was encrypted using 
    /// EncryptStringAES(), using an identical sharedSecret.
    /// </summary>
    /// <param name="cipherText">The text to decrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
    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;
    }
}

refer the link
http://stackoverflow.com/questions/202011/encrypt-decrypt-string-in-net
http://www.codeproject.com/KB/security/DotNetCrypto.aspx
TSN ... replied to alic Sunfu on 12-Jul-11 04:07 AM
hi try this..

private string base64Encode(string sData)
{
try
{
byte[] encData_byte = new byte[sData.Length];

encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);

string encodedData = Convert.ToBase64String(encData_byte);

return encodedData;

}
catch(Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}

HOW TO DECODE IT


public string base64Decode(string sData)

{

System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();

System.Text.Decoder utf8Decode = encoder.GetDecoder();

byte[] todecode_byte = Convert.FromBase64String(sData);

int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);

char[] decoded_char = new char[charCount];

utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

string result = new String(decoded_char);

return result;

}

Jitendra Faye replied to alic Sunfu on 12-Jul-11 04:08 AM

To Encrypt and Decrypt Use these functions-
 

public static string ProtectPassword(string password)
{
    byte[] bytes = Encoding.Unicode.GetBytes(password);
    byte[] protectedPassword = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
    return Convert.ToBase64String(protectedPassword);
}

public static string UnprotectPassword(string protectedPassword)
{
    byte[] bytes = Convert.FromBase64String(protectedPassword);
    byte[] password = ProtectedData.Unprotect(bytes, null, DataProtectionScope.CurrentUser);
    return Encoding.Unicode.GetString(password);
}

hope this will help you.


dipa ahuja replied to alic Sunfu on 12-Jul-11 04:09 AM
//Encrypt
private string EnryptString (string strEncrypted)
{     
  byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted);
  string encryptedConnectionString = Convert.ToBase64String(b);  
  return encryptedConnectionString;   
}
//Decrypt
private string DecryptString(string encrString)
{
  byte[] b = Convert.FromBase64String(encrString);
  string decryptedConnectionString = System.Text.ASCIIEncoding.ASCII.GetString(b);
  return decryptedConnectionString;
}
Web Star replied to alic Sunfu on 12-Jul-11 04:11 AM
There are a good article on eggheadcafe which describe encrypt and decrypt in details
http://www.eggheadcafe.com/tutorials/aspnet/0ab3fff9-6c37-485f-af15-373d73282b44/encryptingdecrypting-a-string-in-dotnet.aspx
http://www.codeproject.com/KB/cs/NET_Encrypt_Decrypt.aspx