11:25
0
http://msdn.microsoft.com/en-us/library/system.security.cryptography(v=vs.110).aspx


Một số code mẫu:

MD5 Hash
//MD5 Hash
public class MD5Hash
    {
        // Hash an input string and return the hash as
        // a 32 character hexadecimal string.
        public static string Encoded(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.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.
        public static bool Verify(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = Encoded(input);

            // Create a StringComparer an comare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }  
    }

DES
    public class DES
    {
        static byte[] bytes = ASCIIEncoding.ASCII.GetBytes("MQTUTEHY");
        /// 
        /// Encrypt a string.
        /// 
        /// The original string.
        /// The encrypted string.
        /// This exception will be thrown when the original string is null or empty.
        public static string Encrypt(string originalString)
        {
            if (String.IsNullOrEmpty(originalString))
            {
                throw new ArgumentNullException("The string which needs to be encrypted can not be null.");
            }

            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);
        }

        /// 
        /// Decrypt a crypted string.
        /// 
        /// The crypted string.
        /// The decrypted string.
        /// This exception will be thrown when the crypted string is null or empty.
        public static string Decrypt(string cryptedString)
        {
            if (String.IsNullOrEmpty(cryptedString))
            {
                throw new ArgumentNullException("The string which needs to be decrypted can not be null.");
            }

            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();
        }
    }


TripleDES
class TrippleDESCSPSample
{

    static void Main()
    {
        try
        {
            // Create a new TripleDESCryptoServiceProvider object 
            // to generate a key and initialization vector (IV).
            TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();

            // Create a string to encrypt. 
            string sData = "Here is some data to encrypt.";

            // Encrypt the string to an in-memory buffer. 
            byte[] Data = EncryptTextToMemory(sData, tDESalg.Key, tDESalg.IV);

            // Decrypt the buffer back to a string. 
            string Final = DecryptTextFromMemory(Data, tDESalg.Key, tDESalg.IV);

            // Display the decrypted string to the console.
            Console.WriteLine(Final);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

    }

    public static byte[] EncryptTextToMemory(string Data,  byte[] Key, byte[] IV)
    {
        try
        {
            // Create a MemoryStream.
            MemoryStream mStream = new MemoryStream();

            // Create a CryptoStream using the MemoryStream  
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(mStream, 
                new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV), 
                CryptoStreamMode.Write);

            // Convert the passed string to a byte array. 
            byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);

            // Write the byte array to the crypto stream and flush it.
            cStream.Write(toEncrypt, 0, toEncrypt.Length);
            cStream.FlushFinalBlock();

            // Get an array of bytes from the  
            // MemoryStream that holds the  
            // encrypted data. 
            byte[] ret = mStream.ToArray();

            // Close the streams.
            cStream.Close();
            mStream.Close();

            // Return the encrypted buffer. 
            return ret;
        }
        catch(CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }

    }

    public static string DecryptTextFromMemory(byte[] Data,  byte[] Key, byte[] IV)
    {
        try
        {
            // Create a new MemoryStream using the passed  
            // array of encrypted data.
            MemoryStream msDecrypt = new MemoryStream(Data);

            // Create a CryptoStream using the MemoryStream  
            // and the passed key and initialization vector (IV).
            CryptoStream csDecrypt = new CryptoStream(msDecrypt, 
                new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), 
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data. 
            byte[] fromEncrypt = new byte[Data.Length];

            // Read the decrypted data out of the crypto stream 
            // and place it into the temporary buffer.
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            //Convert the buffer into a string and return it. 
            return new ASCIIEncoding().GetString(fromEncrypt);
        }
        catch(CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }
}

Rijndael
private static bool CryptStreamExecute(FileStream fin, FileStream fout, String strKey, String strIV,bool bEncypt=true)
        {
            try
            {
                SymmetricAlgorithm rijn = SymmetricAlgorithm.Create("Rijndael");
                
                rijn.Padding = pdMode;
                rijn.Mode = cpMode;

                byte[] rgbIV = Encoding.ASCII.GetBytes(strIV);
                byte[] key = Encoding.ASCII.GetBytes(strKey);

                CryptoStream cs ;
                if(bEncypt)
                    cs = new CryptoStream(fout, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
                else
                    cs = new CryptoStream(fout, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);


                int rdlen = 0;
                int len = 0;
                long itoend = fin.Length;
                byte[] bData = new byte[16];
                while (rdlen < itoend)
                {
                    len = fin.Read(bData, 0, 16);
                    cs.Write(bData, 0, len);
                    rdlen = rdlen + len;
                }
                fin.Close();
                cs.Close();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

Rijndael chuỗi
public static string Encode(string source,String strKey, String strIV)
        {
            byte[] binarySource = Encoding.UTF8.GetBytes(source);
            System.Security.Cryptography.SymmetricAlgorithm rijn = System.Security.Cryptography.SymmetricAlgorithm.Create("Rijndael");
            rijn.Padding = PaddingMode.PKCS7;

            MemoryStream ms = new MemoryStream();
            byte[] rgbIV = Encoding.ASCII.GetBytes(strIV);
            byte[] key = Encoding.ASCII.GetBytes(strKey);
            CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
            cs.Write(binarySource, 0, binarySource.Length);
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }

        private static string Decode(string source, String strKey, String strIV)
        {
            byte[] binarySource = Convert.FromBase64String(source);
            MemoryStream ms = new MemoryStream();
            System.Security.Cryptography.SymmetricAlgorithm rijn = System.Security.Cryptography.SymmetricAlgorithm.Create("Rijndael");
            rijn.Padding = PaddingMode.PKCS7;

            byte[] rgbIV = Encoding.ASCII.GetBytes(strIV);
            byte[] key = Encoding.ASCII.GetBytes(strKey);
            CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
            CryptoStreamMode.Write);
            cs.Write(binarySource, 0, binarySource.Length);
            cs.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
        }

EncodingUTF8
public class EnCodingUTF8
    {
        public static string Encode(string input)
        {
            input = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(input));
            string str = "";
            foreach (char c in input)
            {
                if (char.IsLower(c))
                    str += char.ToUpper(c);
                else
                    str += char.ToLower(c);
            }
            return str;
        }

        public static string Decode(string input)
        {
            string str = "";
            foreach (char c in input)
            {
                if (char.IsLower(c))
                    str += char.ToUpper(c);
                else
                    str += char.ToLower(c);
            }

            byte[] b = Convert.FromBase64String(str);
            return UTF8Encoding.UTF8.GetString(b);
        }
    }



Chương trình Demo cho thuật toán Rijndael: ( Vào mục hỏi đáp để yêu cầu cần source code tham khảo)






0 nhận xét:

Đăng nhận xét