I have to encrypt/decrypt some sensitive information in a Xml file? Yes I can do that by writing my own custom algorithms. I am wondering if there is already a built in way in .NET to do that and also what points I always need to take care..
            Asked
            
        
        
            Active
            
        
            Viewed 2.0k times
        
    2 Answers
30
            Here's a couple of functions that use the .NET framework to encrypt and decrypt a string:
public string EncryptString(string plainText)
{
    // Instantiate a new RijndaelManaged object to perform string symmetric encryption
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    // Set key and IV
    rijndaelCipher.Key = Convert.FromBase64String("ABC");
    rijndaelCipher.IV = Convert.FromBase64String("123");
    // Instantiate a new MemoryStream object to contain the encrypted bytes
    MemoryStream memoryStream = new MemoryStream();
    // Instantiate a new encryptor from our RijndaelManaged object
    ICryptoTransform rijndaelEncryptor = rijndaelCipher.CreateEncryptor();
    // Instantiate a new CryptoStream object to process the data and write it to the 
    // memory stream
    CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelEncryptor, CryptoStreamMode.Write);
    // Convert the plainText string into a byte array
    byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
    // Encrypt the input plaintext string
    cryptoStream.Write(plainBytes, 0, plainBytes.Length);
    // Complete the encryption process
    cryptoStream.FlushFinalBlock();
    // Convert the encrypted data from a MemoryStream to a byte array
    byte[] cipherBytes = memoryStream.ToArray();
    // Close both the MemoryStream and the CryptoStream
    memoryStream.Close();
    cryptoStream.Close();
    // Convert the encrypted byte array to a base64 encoded string
    string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
    // Return the encrypted data as a string
    return cipherText;
}
public string DecryptString(string cipherText)
{
    // Instantiate a new RijndaelManaged object to perform string symmetric encryption
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    // Set key and IV
    rijndaelCipher.Key = Convert.FromBase64String("ABC");
    rijndaelCipher.IV = Convert.FromBase64String("123");
    // Instantiate a new MemoryStream object to contain the encrypted bytes
    MemoryStream memoryStream = new MemoryStream();
    // Instantiate a new encryptor from our RijndaelManaged object
    ICryptoTransform rijndaelDecryptor = rijndaelCipher.CreateDecryptor();
    // Instantiate a new CryptoStream object to process the data and write it to the 
    // memory stream
    CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelDecryptor, CryptoStreamMode.Write);
    // Will contain decrypted plaintext
    string plainText = String.Empty;
    try
    {
        // Convert the ciphertext string into a byte array
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        // Decrypt the input ciphertext string
        cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
        // Complete the decryption process
        cryptoStream.FlushFinalBlock();
        // Convert the decrypted data from a MemoryStream to a byte array
        byte[] plainBytes = memoryStream.ToArray();
        // Convert the encrypted byte array to a base64 encoded string
        plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
    }
    finally
    {
        // Close both the MemoryStream and the CryptoStream
        memoryStream.Close();
        cryptoStream.Close();
    }
    // Return the encrypted data as a string
    return plainText;
}
Of course I don't advise hardcoding the key and initialisation vector like this :)
 
    
    
        Cocowalla
        
- 13,822
- 6
- 66
- 112
- 
                    2"ABC" & "123" are invalid lengths for a Base-64 char array. – JeffO Feb 08 '10 at 18:34
- 
                    1It was only meant to be an illustration, but fair point ;) – Cocowalla Feb 24 '10 at 03:54
- 
                    Just to add value for the other visitors here - the length of both key and IV can be 24 characters. For example: "keJhDo9YvJsp01j4JUdVuE==" – Miro J. Mar 12 '13 at 13:07
- 
                    4Just a sidenote: Use Encoding.UTF8 instead of Encoding.ASCII, because the world is NOT an english-only place. – Stefan Steiger Apr 15 '13 at 06:00
- 
                    @Quandary It was only meant to be an illustration, but fair point ;) – Cocowalla Apr 15 '13 at 06:31
- 
                    2IV must be different for each encryption. – David Thibault Feb 11 '14 at 19:57
- 
                    1@DavidThibault the fixed IV was only meant as an illustration, but yes, it should be different each time you encrypt. You should normally use `rijndaelCipher.GenerateIV()` to generate a unique IV – Cocowalla Feb 12 '14 at 10:29
10
            
            
        You will probably want to dive into the System.Security.Cryptography namespace. I guess the articles Cryptography Overview, Encrypting Data and Decrypting Data at MSDN could be good starters.
 
    
    
        Fredrik Mörk
        
- 155,851
- 29
- 291
- 343
 
    