Encrypt and Decrypt String : Encrypt Decrypt « Security « C# / C Sharp





Encrypt and Decrypt String

    


using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

public static class Utility
{
    private static byte[] _bytes = ASCIIEncoding.ASCII.GetBytes("AAAAAAAA");
    public static string Encrypt(string originalString)
    {
        if (String.IsNullOrEmpty(originalString))
        {
            throw new ArgumentNullException("The string which needs to be encrypted can not be empty.");
        }

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(_bytes, _bytes), CryptoStreamMode.Write);
        StreamWriter writer = new StreamWriter(cryptoStream);
        writer.Write(originalString);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();

        return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
    }

    public static string Decrypt(string cryptedString)
    {
        if (String.IsNullOrEmpty(cryptedString))
        {
            throw new ArgumentNullException("The string which needs to be decrypted can not be empty.");
        }

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(cryptedString));
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(_bytes, _bytes), CryptoStreamMode.Read);
        StreamReader reader = new StreamReader(cryptoStream);

        return reader.ReadToEnd();
    }
}

   
    
    
    
  










Related examples in the same category

1.Encrypt Utils
2.Decrypt Utils
3.Provides the Unix crypt() encryption algorithm.
4.Encrypts the value by password and salt.
5.Encrypt/Decrypt String To Bytes
6.Encrypt the given string using AES
7.Decrypt/Encrypt String AES
8.Encrypt String
9.Encrypt a string
10.Crypto Utility
11.Crypto Utilities
12.Encryption Helper
13.Key Creator
14.S3 Upload Policy