FireStats error processing pending hits: Internal error : no id for referrer http://www.cyberforum.ru/yaproger/thread48473.html


Симметричное шифрование данных

Данный статический класс предназначен для удобного симметрического шифрования строки или массива байт:

///
/// Provides base functions for encrypting and decrypting data through the symmetric algorithm
///
public static class Cryptography
{
    ///
    /// Encrypts data
    ///
    /// Data for the encryption
    /// Encryption key
    /// Encrypted data
    public static byte[] Encrypt(byte[] data, string password)
    {
        SymmetricAlgorithm sa = Rijndael.Create();
        ICryptoTransform ct = sa.CreateEncryptor(
            (new PasswordDeriveBytes(password, null)).GetBytes(16),
            new byte[16]);

        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);

        cs.Write(data, 0, data.Length);
        cs.FlushFinalBlock();

        return ms.ToArray();
    }

    ///
    /// Encrypts data
    ///
    /// Data for the encryption
    /// Encryption key
    /// Encrypted data
    public static string Encrypt(string data, string password)
    {
        return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data), password));
    }

    ///
    /// Decrypts data
    ///
    /// Data for the decryption
    /// Decryption key
    /// Decrypted data
    static public byte[] Decrypt(byte[] data, string password)
    {
        BinaryReader br = new BinaryReader(InternalDecrypt(data, password));
        return br.ReadBytes((int)br.BaseStream.Length);
    }

    ///
    /// Decrypts data
    ///
    /// Data for the decryption
    /// Decryption key
    /// Decrypted data
    static public string Decrypt(string data, string password)
    {
        CryptoStream cs = InternalDecrypt(Convert.FromBase64String(data), password);
        StreamReader sr = new StreamReader(cs);
        return sr.ReadToEnd();
    }

    static CryptoStream InternalDecrypt(byte[] data, string password)
    {
        SymmetricAlgorithm sa = Rijndael.Create();
        ICryptoTransform ct = sa.CreateDecryptor(
            (new PasswordDeriveBytes(password, null)).GetBytes(16),
            new byte[16]);

        MemoryStream ms = new MemoryStream(data);
        return new CryptoStream(ms, ct, CryptoStreamMode.Read);
    }
}

2 comments сентября 10, 2009


Метки