Наследование: SymmetricAlgorithm
Пример #1
1
 public RijndaelHelper(byte[] key, byte[] vector)
 {
     encoding = new UTF8Encoding();
     rijndael = Rijndael.Create();
     rijndael.Key = key;
     rijndael.IV = vector;
 }
Пример #2
0
    public string Decrypt(byte[] soup, string key) // key must be 32chars
    {
        string outString = "";

        try
        {
            byte[] iv       = Encoding.ASCII.GetBytes("1234567890123456");
            byte[] keyBytes = Encoding.ASCII.GetBytes(key);

            // Create a new instance of the Rijndael
            // class.  This generates a new key and initialization
            // vector (IV).
            using (System.Security.Cryptography.Rijndael myRijndael = System.Security.Cryptography.Rijndael.Create())
            {
                myRijndael.Key = keyBytes;
                myRijndael.IV  = iv;

                // Decrypt the bytes to a string.
                outString = DecryptStringFromBytes(soup, myRijndael.Key, myRijndael.IV);
            }
        }
        catch
        {
        }

        return(outString);
    }
Пример #3
0
    internal static void Decrypt(string fileIn, string fileOut)
    {
        System.IO.FileStream fsIn  = new System.IO.FileStream(fileIn, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        System.IO.FileStream fsOut = new System.IO.FileStream(fileOut, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(Password,
                                                                                                                    new byte[] { 0x49, 0x49, 0x35, 0x6e, 0x76, 0x4d,
                                                                                                                                 0x65, 0x64, 0x76, 0x76, 0x64, 0x65, 0x76 });
        System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV  = pdb.GetBytes(16);

        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(fsOut, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

        int bufferLen = 4096;

        byte[] buffer = new byte[bufferLen];
        int    bytesRead;

        do
        {
            // read a chunk of data from the input file
            bytesRead = fsIn.Read(buffer, 0, bufferLen);
            // Decrypt it
            cs.Write(buffer, 0, bytesRead);
        } while (bytesRead != 0);
        cs.Close();
        fsIn.Close();
    }
Пример #4
0
            public static string Decrypt(string strDecrypt, bool retStrOriginal)
            {
                string result = string.Empty;

                System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
                try
                {
                    byte[] bytes  = System.Text.Encoding.UTF8.GetBytes(Secret.AES.Key);
                    byte[] bytes2 = System.Text.Encoding.UTF8.GetBytes(Secret.AES.IV);
                    byte[] array  = Convert.FromBase64String(strDecrypt);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateDecryptor(bytes, bytes2), System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(array, 0, array.Length);
                            cryptoStream.FlushFinalBlock();
                            result = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
                        }
                    }
                }
                catch
                {
                    if (retStrOriginal)
                    {
                        result = strDecrypt;
                    }
                    else
                    {
                        result = string.Empty;
                    }
                }
                rijndael.Clear();
                return(result);
            }
Пример #5
0
    public byte[] Encrypt(string original, string key) // key must be 32chars
    {
        byte[] encrypted = null;

        try
        {
            byte[] iv       = Encoding.ASCII.GetBytes("1234567890123456");
            byte[] keyBytes = Encoding.ASCII.GetBytes(key);

            // Create a new instance of the Rijndael
            // class.  This generates a new key and initialization
            // vector (IV).
            using (System.Security.Cryptography.Rijndael myRijndael = System.Security.Cryptography.Rijndael.Create())
            {
                myRijndael.Key = keyBytes;
                myRijndael.IV  = iv;

                // Encrypt the string to an array of bytes.
                encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
            }
        }
        catch
        {
        }

        return(encrypted);
    }
Пример #6
0
 public static byte[] smethod_3(byte[] byte_0, string string_0)
 {
     System.Security.Cryptography.Rijndael           rijndael           = System.Security.Cryptography.Rijndael.Create();
     System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(string_0, new byte[]
     {
         38,
         220,
         255,
         0,
         173,
         237,
         122,
         238,
         197,
         254,
         7,
         175,
         77,
         8,
         34,
         60
     });
     rijndael.Key = rfc2898DeriveBytes.GetBytes(32);
     rijndael.IV  = rfc2898DeriveBytes.GetBytes(16);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(byte_0, 0, byte_0.Length);
     cryptoStream.Close();
     return(memoryStream.ToArray());
 }
Пример #7
0
 public Encryption()
 {
     aes = Rijndael.Create();
     aes.Mode = CipherMode.ECB;
     aes.KeySize = 128;
     aes.Padding = PaddingMode.None;
 }
 public RijndaelDecryptionCfbTransform(Rijndael rijndael, int feedbackSizeInBits, byte[] initializationVector,
                                       PaddingMode paddingMode)
     : base(rijndael, paddingMode)
 {
     _FeedbackSizeInBytes = feedbackSizeInBits/Constants.BitsPerByte;
     _FeedbackIterations = rijndael.BlockSize/feedbackSizeInBits;
     _LastVector = ByteUtilities.Clone(initializationVector);
 }
 private static void InitRijndael(Rijndael rij, byte[] key)
 {
     rij.Padding = PaddingMode.None;
     rij.Mode = CipherMode.ECB;
     rij.BlockSize = 128;	// byte[16]
     rij.IV = new byte[16];
     rij.Key = key;			// byte[32]
 }
Пример #10
0
 internal static System.Security.Cryptography.Rijndael NewRijndaelSymmetricAlgorithm()
 {
     System.Security.Cryptography.Rijndael symmetricAlgorithm = GetSymmetricAlgorithm(null, "http://www.w3.org/2001/04/xmlenc#aes128-cbc") as System.Security.Cryptography.Rijndael;
     if (symmetricAlgorithm == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(System.IdentityModel.SR.GetString("CustomCryptoAlgorithmIsNotValidSymmetricAlgorithm", new object[] { "http://www.w3.org/2001/04/xmlenc#aes128-cbc" })));
     }
     return(symmetricAlgorithm);
 }
Пример #11
0
        static Crypto()
        {
            RijndaelCbc = Rijndael.Create();
            RijndaelCbc.Padding = PaddingMode.None;
            RijndaelCbc.Mode = CipherMode.CBC;

            RijndaelEcb = Rijndael.Create();
            RijndaelEcb.Padding = PaddingMode.None;
            RijndaelEcb.Mode = CipherMode.ECB;
        }
Пример #12
0
 private static byte[] AES_Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
 {
     System.IO.MemoryStream memoryStream            = new System.IO.MemoryStream();
     System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
     rijndael.Key = Key;
     rijndael.IV  = IV;
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(cipherData, 0, cipherData.Length);
     cryptoStream.Close();
     return(memoryStream.ToArray());
 }
Пример #13
0
        public SimpleAES(string password)
        {
            _rijndael = Rijndael.Create();
            _rijndael.Padding = PaddingMode.Zeros;

            using (var pdb = new Rfc2898DeriveBytes(password, SALT))
            {
                _rijndael.Key = pdb.GetBytes(32);
                _rijndael.IV = pdb.GetBytes(16);
            }
        }
Пример #14
0
        private void Initialize()
        {

            rijndael = new RijndaelManaged() { Padding = PaddingMode.None };
            aesInitializationVector = new byte[CRYPTO_BLOCK_SIZE];
            int rawLength = 2 * password.Length;
            byte[] rawPassword = new byte[rawLength + 8];
            byte[] passwordBytes = Encoding.Unicode.GetBytes(password);
            for (int i = 0; i < rawLength; i++)
            {
                rawPassword[i] = passwordBytes[i];
            }
            for (int i = 0; i < salt.Length; i++)
            {
                rawPassword[i + rawLength] = salt[i];
            }

            SHA1 sha = new SHA1CryptoServiceProvider();

            const int noOfRounds = (1 << 18);
            IList<byte> bytes = new List<byte>();
            byte[] digest;

            //TODO slow code below, find ways to optimize
            for (int i = 0; i < noOfRounds; i++)
            {
                bytes.AddRange(rawPassword);

                bytes.AddRange(new[] { (byte)i, (byte)(i >> 8), (byte)(i >> CRYPTO_BLOCK_SIZE) });
                if (i % (noOfRounds / CRYPTO_BLOCK_SIZE) == 0)
                {
                    digest = sha.ComputeHash(bytes.ToArray());
                    aesInitializationVector[i / (noOfRounds / CRYPTO_BLOCK_SIZE)] = digest[19];
                }
            }

            digest = sha.ComputeHash(bytes.ToArray());
            //slow code ends

            byte[] aesKey = new byte[CRYPTO_BLOCK_SIZE];
            for (int i = 0; i < 4; i++)
                for (int j = 0; j < 4; j++)
                    aesKey[i * 4 + j] = (byte)
                        (((digest[i * 4] * 0x1000000) & 0xff000000 |
                        (uint)((digest[i * 4 + 1] * 0x10000) & 0xff0000) |
                          (uint)((digest[i * 4 + 2] * 0x100) & 0xff00) |
                          (uint)(digest[i * 4 + 3] & 0xff)) >> (j * 8));

            rijndael.IV = new byte[CRYPTO_BLOCK_SIZE];
            rijndael.Key = aesKey;
            rijndael.BlockSize = CRYPTO_BLOCK_SIZE * 8;

        }
Пример #15
0
        public Login()
        {
            InitializeComponent();
            pop3Client = new Pop3Client();

            /// Makes the onclick work
            view_mails.AfterSelect += new TreeViewEventHandler(ListMessagesMessageSelected);
            atached_file.AfterSelect += new TreeViewEventHandler(ListAttachmentsAttachmentSelected);

            /// Makes the Rijndael Key
            myKey = Rijndael.Create();
        }
Пример #16
0
    /// <summary>
    /// Encriptamos el objecto
    /// </summary>
    /// <param name="pObject">Objecto a Encriptar</param>
    /// <param name="pKey">Clave 1</param>
    /// <param name="pIV">Clave 2</param>
    /// <returns>Retorna el objecto Encriptado</returns>
    private static byte[] EncryptObjectToBytes(object pObject, byte[] pKey, byte[] pIV)
    {
        //Verifica si los parametros son nulo
        if (pObject == null)
        {
            throw new ArgumentNullException();
        }
        if (pKey == null || pKey.Length <= 0)
        {
            throw new ArgumentNullException();
        }
        if (pIV == null || pIV.Length <= 0)
        {
            throw new ArgumentNullException();
        }

        //Creamos la variable byte[] que almacena el objecto encriptado
        byte[] encrypted;

        //Creamos el algoritmo
        System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();

        //Usamos el algoritmo
        using (rijndael)
        {
            //Le pasamos los valores de las claves al algoritmno
            rijndael.Key = pKey;
            rijndael.IV  = pIV;

            //Creamos el Encriptador
            System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor(rijndael.Key, rijndael.IV);

            //Se crean las corrientes para el cifrado
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Escribe los datos en la secuencia
                        swEncrypt.Write(pObject);
                    }

                    //Almacenamos la encriptacion en el objecto
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        //Retornamos el objecto encriptado
        return(encrypted);
    }
Пример #17
0
    internal static byte[] MD5Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
    {
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
        alg.Key = Key;
        alg.IV  = IV;

        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
        cs.Write(cipherData, 0, cipherData.Length);
        cs.Close();
        byte[] decryptedData = ms.ToArray();
        return(decryptedData);
    }
Пример #18
0
        /// <summary>
        /// Constructs a new instance of <see cref="AesCrypto"/> from the specified values.
        /// </summary>
        /// <param name="salt">The <see cref="Salt"/> used in encryption.</param>
        /// <param name="passphrase">The <see cref="Passphrase"/> used in encryption.</param>
        public AesCrypto(string passphrase, byte[] salt)
        {
            Passphrase = passphrase;
            Salt = salt;

            _encryptor = Rijndael.Create();
            _encryptor.Padding = PaddingMode.PKCS7;
            _pdb = new Rfc2898DeriveBytes(Passphrase, Salt);
            _encryptor.Key = _pdb.GetBytes(_encryptor.KeySize / 8);
            _encryptor.IV = _pdb.GetBytes(_encryptor.BlockSize / 8);

            _encryptorTransform = _encryptor.CreateEncryptor();
            _decryptorTransform = _encryptor.CreateDecryptor();
        }
Пример #19
0
    /// <summary>
    /// Desencripta un objecto
    /// </summary>
    /// <param name="pObject">Objecto Encriptado</param>
    /// <param name="pKey">Clave 1</param>
    /// <param name="pIV">Clave 2</param>
    /// <returns>Retorna el Objecto Desencriptado</returns>
    private static object DecryptObjectFromBytes(byte[] pObject, byte[] pKey, byte[] pIV)
    {
        //Verifica si los parametros son nulo
        if (pObject == null || pObject.Length <= 0)
        {
            throw new ArgumentNullException();
        }
        if (pKey == null || pKey.Length <= 0)
        {
            throw new ArgumentNullException();
        }
        if (pIV == null || pIV.Length <= 0)
        {
            throw new ArgumentNullException();
        }

        //Variable que almacenara el valor del objecto encritado
        object vlDecodeObject = null;

        //Creamos el algoritmo
        System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();

        //Usamos el algoritmo
        using (rijndael)
        {
            //Le pasamos los valores de las claves al algoritmno
            rijndael.Key = pKey;
            rijndael.IV  = pIV;

            //Creamos el Desencriptador
            System.Security.Cryptography.ICryptoTransform decryptor = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);

            //Se crean las corrientes para el cifrado
            using (MemoryStream msDecrypt = new MemoryStream(pObject))
            {
                using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        //Escribe los datos en la secuencia, como un objecto (string)
                        vlDecodeObject = srDecrypt.ReadToEnd();
                    }
                }
            }
        }

        //Retornamos el objecto desencriptado
        return(vlDecodeObject);
    }
Пример #20
0
        /// <summary>
        /// Decode a string endoced using Rijndael with specified password and IV strings.
        /// </summary>
        /// <param name="sourceString">The string to decode</param>
        /// <param name="password">The password string</param>
        /// <param name="IV">The IV string</param>
        /// <returns>The decoded string</returns>
        public string DecodeString(string sourceString, string password, String IV)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Please specify the password", nameof(password));
            }

            if (string.IsNullOrEmpty(IV))
            {
                throw new ArgumentException("Please specify the Initialize Vector", nameof(IV));
            }

            if (!string.IsNullOrEmpty(sourceString))
            {
                byte[] cipherText = Convert.FromBase64String(sourceString);

                string plaintext = null;

                // Create an Rijndael object
                // with the specified key and IV.
                using (System.Security.Cryptography.Rijndael rijAlg = System.Security.Cryptography.Rijndael.Create())
                {
                    rijAlg.Key = GeneratePassword(password);
                    rijAlg.IV  = GeneratePassword(IV);

                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                    // Create the streams used for decryption.
                    using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                    {
                        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();
                            }
                        }
                    }
                }
                return(plaintext);
            }
            else
            {
                return(string.Empty);
            }
        }
Пример #21
0
        public string Encrypt(string value)
        {
            System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
            byte[]           tmp       = null;
            ICryptoTransform encryptor = rijndael.CreateEncryptor(key, iv);

            using (MemoryStream ms = new MemoryStream()) {
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) {
                    StreamWriter writer = new StreamWriter(cs);
                    writer.Write(value);
                    writer.Flush();
                }
                tmp = ms.ToArray();
            }
            return(Convert.ToBase64String(tmp));
        }
Пример #22
0
        public static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Rijndael object
            // with the specified key and IV.
            using (System.Security.Cryptography.Rijndael rijAlg = System.Security.Cryptography.Rijndael.Create())
            {
                rijAlg.Key = Key;
                rijAlg.IV  = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    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();
                        }
                    }
                }
            }

            return(plaintext);
        }
Пример #23
0
 private void Initialize()
 {
     int i;
     byte[] buffer3;
     RijndaelManaged managed = new RijndaelManaged();
     managed.Padding = PaddingMode.None;
     this.rijndael = managed;
     this.aesInitializationVector = new byte[0x10];
     int num = 2 * this.password.Length;
     byte[] source = new byte[num + 8];
     byte[] bytes = Encoding.Unicode.GetBytes(this.password);
     for (i = 0; i < num; i++)
     {
         source[i] = bytes[i];
     }
     for (i = 0; i < this.salt.Length; i++)
     {
         source[i + num] = this.salt[i];
     }
     SHA1 sha = new SHA1CryptoServiceProvider();
     IList<byte> destination = new List<byte>();
     for (i = 0; i < 0x40000; i++)
     {
         Utility.AddRange<byte>(destination, source);
         Utility.AddRange<byte>(destination, new byte[] { (byte) i, (byte) (i >> 8), (byte) (i >> 0x10) });
         if ((i % 0x4000) == 0)
         {
             buffer3 = sha.ComputeHash(Enumerable.ToArray<byte>(destination));
             this.aesInitializationVector[i / 0x4000] = buffer3[0x13];
         }
     }
     buffer3 = sha.ComputeHash(Enumerable.ToArray<byte>(destination));
     byte[] buffer4 = new byte[0x10];
     for (i = 0; i < 4; i++)
     {
         for (int j = 0; j < 4; j++)
         {
             buffer4[(i * 4) + j] = (byte) ((((((buffer3[i * 4] * 0x1000000) & 0xff000000L) |
                 ((uint) ((buffer3[(i * 4) + 1] * 0x10000) & 0xff0000))) |
                 ((uint) ((buffer3[(i * 4) + 2] * 0x100) & 0xff00))) |
                 ((uint) (buffer3[(i * 4) + 3] & 0xff))) >> (j * 8));
         }
     }
     this.rijndael.IV = new byte[0x10];
     this.rijndael.Key = buffer4;
     this.rijndael.BlockSize = 0x80;
 }
Пример #24
0
        /// <summary>
        /// Encode a string using Rijndael with specified password and IV strings.
        /// </summary>
        /// <param name="sourceString">The string to encode</param>
        /// <param name="password">The password string</param>
        /// <param name="IV">The IV string</param>
        /// <returns>The encoded string</returns>
        public string EncodeString(string sourceString, string password, String IV)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Please specify the password", nameof(password));
            }

            if (string.IsNullOrEmpty(IV))
            {
                throw new ArgumentException("Please specify the Initialize Vector", nameof(IV));
            }

            if (!string.IsNullOrEmpty(sourceString))
            {
                byte[] encrypted;
                // Create an Rijndael object
                // with the specified key and IV.
                using (System.Security.Cryptography.Rijndael rijAlg = System.Security.Cryptography.Rijndael.Create())
                {
                    rijAlg.Key = GeneratePassword(password);
                    rijAlg.IV  = GeneratePassword(IV);

                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.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(sourceString);
                            }
                            encrypted = msEncrypt.ToArray();
                        }
                    }
                }
                return(Convert.ToBase64String(encrypted));
            }
            else
            {
                return(string.Empty);
            }
        }
 public static RijndaelTransform Create(Rijndael rijndael, CipherMode mode, byte[] initializationVector,
                                        int feedbackSizeInBits, PaddingMode paddingMode)
 {
     switch (mode)
     {
         case CipherMode.ECB:
             return new RijndaelEncryptionEcbTransform(rijndael, paddingMode);
         case CipherMode.CBC:
             return new RijndaelEncryptionCbcTransform(rijndael, initializationVector, paddingMode);
         case CipherMode.OFB:
             return new RijndaelOfbTransform(rijndael, initializationVector, paddingMode);
         case CipherMode.CFB:
             return new RijndaelEncryptionCfbTransform(rijndael, feedbackSizeInBits, initializationVector,
                                                       paddingMode);
         default:
             throw new NotImplementedException(mode + " has not been implemented");
     }
 }
Пример #26
0
    static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
        {
            throw new ArgumentNullException("plainText");
        }
        if (Key == null || Key.Length <= 0)
        {
            throw new ArgumentNullException("Key");
        }
        if (IV == null || IV.Length <= 0)
        {
            throw new ArgumentNullException("IV");
        }
        byte[] encrypted;
        // Create an Rijndael object
        // with the specified key and IV.
        using (System.Security.Cryptography.Rijndael rijAlg = System.Security.Cryptography.Rijndael.Create())
        {
            rijAlg.Key = Key;
            rijAlg.IV  = IV;

            // Create an encryptor to perform the stream transform.
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.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);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        // Return the encrypted bytes from the memory stream.
        return(encrypted);
    }
Пример #27
0
    /// <summary>
    /// Manda a encriptar un objecto
    /// </summary>
    /// <param name="pObject">Objecto a encriptar</param>
    /// <returns>Retorna el Objecto Encriptado con las Claves</returns>
    public static object Encode(object pObject)
    {
        //Creamos el algoritmo
        System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();

        //Almacenamos las claves
        object vlKey = rijndael.Key;
        object vlIV  = rijndael.IV;

        //Usamos el algoritmo
        using (rijndael)
        {
            //Encriptamos el objecto
            object vlEncrypted = EncryptObjectToBytes(pObject, rijndael.Key, rijndael.IV);

            //Almacenamos en un string[] el objecto encritado
            string[] vlEnEncrypted = ((IEnumerable)vlEncrypted).Cast <object>()
                                     .Select(x => x.ToString())
                                     .ToArray();

            //Almacenamos en un string[] la clave 1
            string[] vlEnKey = ((IEnumerable)vlKey).Cast <object>()
                               .Select(x => x.ToString())
                               .ToArray();

            //Almacenamos en un string[] la clave 2
            string[] vlEnIV = ((IEnumerable)vlIV).Cast <object>()
                              .Select(x => x.ToString())
                              .ToArray();

            //Creamos el string con los datos encriptados
            string vlValueEncode = string.Empty;
            vlValueEncode = vlValueEncode + string.Join(",", vlEnEncrypted);
            vlValueEncode = vlValueEncode + "/" + string.Join(",", vlEnKey);
            vlValueEncode = vlValueEncode + "/" + string.Join(",", vlEnIV);

            //Almacenamos en un objecto el string
            object vlValueFinal = vlValueEncode;

            //Retornamos el objecto
            return(vlValueFinal);
        }
    }
Пример #28
0
        // Encrypt a byte array into a byte array using a key and an IV

        public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();

            // Algorithm. Rijndael is available on all platforms.

            alg.Key = Key;
            alg.IV  = IV;
            System.Security.Cryptography.CryptoStream cs =
                new System.Security.Cryptography.CryptoStream(ms, alg.CreateEncryptor(),
                                                              System.Security.Cryptography.CryptoStreamMode.Write);

            //CryptoStream is for pumping our data.

            cs.Write(clearData, 0, clearData.Length);
            cs.Close();
            byte[] encryptedData = ms.ToArray();
            return(encryptedData);
        }
Пример #29
0
        public SimpleAES(string password)
        {
            _rijndael = Rijndael.Create();
            _rijndael.Padding = PaddingMode.Zeros;
            Rfc2898DeriveBytes pdb = null;
            try
            {
                pdb = new Rfc2898DeriveBytes(password, SALT);
                _rijndael.Key = pdb.GetBytes(32);
                _rijndael.IV = pdb.GetBytes(16);
            }
            finally
            {
                IDisposable disp = pdb as IDisposable;

                if (disp != null)
                {
                    disp.Dispose();
                }
            }
        }
Пример #30
0
        public string Encode(string input)
        {
            System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
            alg.Key     = Encoding.UTF8.GetBytes("kaudkwudhtbenwnakaudkwudhtbenwna");
            alg.IV      = Encoding.UTF8.GetBytes("HR$2pIjHR$2pIj12");
            alg.Padding = PaddingMode.Zeros;

            ICryptoTransform encryptor = alg.CreateEncryptor(alg.Key, alg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(input);
                    }
                    return(Encoding.Unicode.GetString(msEncrypt.ToArray()));
                }
            }
        }
Пример #31
0
        public string Decode(string input)
        {
            System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
            alg.Key     = Encoding.UTF8.GetBytes("kaudkwudhtbenwnakaudkwudhtbenwna");
            alg.IV      = Encoding.UTF8.GetBytes("HR$2pIjHR$2pIj12");
            alg.Padding = PaddingMode.Zeros;
            string           result;
            ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(Encoding.Unicode.GetBytes(input)))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        result = srDecrypt.ReadToEnd();
                    }
                }
            }
            return(result);
        }
Пример #32
0
        public bool Decrypt(ref string value)
        {
            string result = string.Empty;

            System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
            ICryptoTransform decryptor = rijndael.CreateDecryptor(key, iv);

            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(value))) {
                try {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) {
                        StreamReader reader = new StreamReader(cs);
                        result = reader.ReadLine();
                        reader.Close();
                    }
                } catch (System.Security.Cryptography.CryptographicException ex) {
                    value = ex.Message;
                    return(false);
                }
            }
            value = result;
            return(true);
        }
Пример #33
0
 private void btnEncrypt_Click(object sender, RoutedEventArgs e)
 {
     if (_ifEncrypted)
         return;
     DateTime dt = DateTime.UtcNow;
     switch(AlgIndex)
     {
         case (int)EnumAlgorithm.AES:
             algAES = new AesManaged();
             encrypted = Encrypt.EncryptStringToBytes_Aes(TextPlain.Text, algAES.Key, algAES.IV);
             TextEncrypted.Text = Encoding.Unicode.GetString(encrypted);
             break;
         case (int)EnumAlgorithm.DES:
             tripleDES = new TripleDESCryptoServiceProvider();
             encrypted = Encrypt.EncryptStringToBytes_Des(TextPlain.Text, tripleDES.Key, tripleDES.IV);
             TextEncrypted.Text = Encoding.Unicode.GetString(encrypted);
             break;
         case (int)EnumAlgorithm.RIJ:
             algRIJ = Rijndael.Create();
             encrypted = Encrypt.EncryptStringToBytes_Rij(TextPlain.Text, algRIJ.Key, algRIJ.IV);
             TextEncrypted.Text = Encoding.Unicode.GetString(encrypted);
             break;
         case (int)EnumAlgorithm.DSA:
             break;
         case (int)EnumAlgorithm.RSA:
             rsaCrypt = new RSACryptoServiceProvider();
             string publickeyRSA = rsaCrypt.ToXmlString(false);//公钥
             encrypted = Encrypt.EncryptStringToBytes_Rsa(TextPlain.Text, publickeyRSA);
             TextEncrypted.Text = Encoding.Unicode.GetString(encrypted);
             break;
         default:
             break;
     }
     lbTime.Content = DateTime.UtcNow.Subtract(dt).ToString();
     _ifEncrypted = true;
 }
Пример #34
0
        protected virtual Stream GetOutputStream(Rijndael alg, AppServerConfigOptions options, string configFilePath)
        {
            Stream outStream = new FileStream(configFilePath, FileMode.CreateNew);

            switch (options)
            {
                case AppServerConfigOptions.FileEncrypted:
                    outStream = new CryptoStream(outStream, alg.CreateEncryptor(), CryptoStreamMode.Write);
                    outStream = new GZipStream(outStream, CompressionMode.Compress);
                    break;
            }

            return outStream;
        }
Пример #35
0
        private static void SetupEncryption()
        {
            rijn = Rijndael.Create();
            rijn.KeySize = ENC_Key.Length * 8;
            rijn.Key = ENC_Key;
            rijn.IV = ENC_IV;
            rijn.Padding = PaddingMode.ISO10126;
            rijn.Mode = CipherMode.CBC;

            encryptor = rijn.CreateEncryptor();
            decryptor = rijn.CreateDecryptor();
        }
Пример #36
0
        protected virtual void ConfigurationWriteCompletionBinary(Rijndael alg, AppServerConfigOptions options, int size,
            string configFileConfirmPath, Stream outgoing, Guid ApplicationID)
        {
            byte[] data = null;

            switch (options)
            {
                case AppServerConfigOptions.FileDigitallySigned:
                    data = GenerateHash(outgoing);
                    break;
                case AppServerConfigOptions.FileEncrypted:
                    byte[] buffer = GenerateCryptoBlob(alg, size);
                    if (buffer != null)
                    {
                        data = ProtectedData.Protect(buffer, ApplicationID.ToByteArray(), DataProtectionScope.LocalMachine);
                    }
                    break;
            }

            if (data != null)
                File.WriteAllBytes(configFileConfirmPath, data);
        }
Пример #37
0
 internal RijndaelManagedTransform(Rijndael algo, bool encryption, byte[] key, byte[] iv)
 {
     _st = new RijndaelTransform(algo, encryption, key, iv);
     _bs = algo.BlockSize;
 }
Пример #38
0
        public static String Encrypt(byte[] clearText, String publicKey, Rijndael aes)
        {
            StringWriter cipherText = new StringWriter();

            ArrayList message = new ArrayList();
            message.AddRange(RSAEncrypt(aes.Key, publicKey));
            message.AddRange(RSAEncrypt(aes.IV, publicKey));
            message.AddRange(AESEncrypt(clearText, aes.CreateEncryptor()));

            String messageArmor = Convert.ToBase64String((byte[]) message.ToArray(Type.GetType("System.Byte")));

            cipherText.WriteLine(BeginMessage);
            cipherText.WriteLine("Version: PractiSES {0} (Win32)",
                                 Assembly.GetExecutingAssembly().GetName().Version.ToString(2));
            cipherText.WriteLine();
            cipherText.WriteLine(Util.Wrap(messageArmor, Wrap));
            cipherText.WriteLine(EndMessage);

            return cipherText.ToString();
        }
 /// <summary>Creates a cryptographic object to perform the <see cref="T:System.Security.Cryptography.Rijndael" /> algorithm.</summary>
 /// <returns>A cryptographic object.</returns>
 /// <exception cref="T:System.Reflection.TargetInvocationException">The algorithm was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible.</exception>
 // Token: 0x06002314 RID: 8980 RVA: 0x0007DD99 File Offset: 0x0007BF99
 public new static Rijndael Create()
 {
     return(Rijndael.Create("System.Security.Cryptography.Rijndael"));
 }
Пример #40
0
 public Seguridad()
 {
     rijndael = Rijndael.Create();
     key = UTF8Encoding.UTF8.GetBytes("C80BA5028D1E81E3042EBF1649D8ED31");//LLave maestra
     iv = UTF8Encoding.UTF8.GetBytes("serviciosWeb2015");// Semilla
 }
Пример #41
0
 public Rijndael()
 {
     this._r = System.Security.Cryptography.Rijndael.Create();
 }
 public RijndaelEncryptionCbcTransform(Rijndael rijndael, byte[] initializationVector, PaddingMode paddingMode)
     : base(rijndael, paddingMode)
 {
     _LastVector = ByteUtilities.Clone(initializationVector);
 }
Пример #43
0
 public EDObject(Rijndael _rijindael)
 {
     rijndael = _rijindael;
 }
Пример #44
0
 protected virtual byte[] GenerateCryptoBlob(Rijndael alg, int size)
 {
     byte[] blob = new byte[12 + alg.Key.Length + alg.IV.Length];
     int position = 0;
     position = WriteInt32(alg.Key.Length, blob, 0);
     position = WriteInt32(alg.IV.Length, blob, position);
     position = WriteInt32(size, blob, position);
     Buffer.BlockCopy(alg.Key, 0, blob, position, alg.Key.Length);
     position += alg.Key.Length;
     Buffer.BlockCopy(alg.IV, 0, blob, position, alg.IV.Length);
     return blob;
 }
Пример #45
0
        //initialize from an encrypted file
        public TimeBomb(String file, Rijndael crypt, DetonateHandler detonate, DecryptFile decrypt)
        {
            //read the date time value from the file
            BinaryReader reader = decrypt.Invoke(file, crypt);
            String str = reader.ReadString();
            this.detonateTime = DateTime.Parse(str);//reader.ReadLine()

            this.detonate.detonate += detonate;

            thrd = new Thread(new ThreadStart(() => {
                while (true) {
                    //if we are past time to detonate, then detonate
                    if (detonateTime.CompareTo(DateTime.Now) < 0) {
                        this.detonate.OnDetonateEvent();
                        return;
                    }

                    Thread.Sleep(1000);
                }//end loop
            }));
            thrd.Priority = ThreadPriority.Lowest;
            thrd.Start();
        }
 public RijndaelDecryptionEcbTransform(Rijndael rijndael, PaddingMode paddingMode)
     : base(rijndael, paddingMode)
 {
 }
Пример #47
0
        /// <summary>
        /// This is the reset method to set the content.
        /// </summary>
        public override void Reset()
        {
            if (mDataStream != null)
                mDataStream.Close();
            mDataStream = null;

            mFileStream = null;

            mCompressed = true;
            mCompStream = null;

            mEncrypted = false;
            mEncrStream = null;
            mRijndaelAlg = null;

            mHashed = true;
            mDataHash = null;

            mCreateTime = null;
            mDataStoreLocation = null;
            mMessageID = null;
            base.Reset();
        }
Пример #48
0
 public void Dispose()
 {
     if (_rijndael != null)
     {
         _rijndael.Clear();
         _rijndael = null;
     }
 }
		internal RijndaelManagedTransform (Rijndael algo, bool encryption, byte[] key, byte[] iv)
		{
			_st = new RijndaelTransform (algo, encryption, key, iv);
			_bs = algo.BlockSize;
		}
Пример #50
0
        /// <summary>
        /// This method reads the metadata from the metadata stream.
        /// </summary>
        /// <param name="r">The binary reader for the stream.</param>
        public virtual void Read(BinaryReader r)
        {
            mEncrypted = r.ReadBoolean();

            if (Encrypted)
            {
                byte[] mRijndaelAlgKey, mRijndaelAlgIV;
                ReadVal(r, out mRijndaelAlgKey);
                ReadVal(r, out mRijndaelAlgIV);
                RijndaelAlg = new RijndaelManaged();
                RijndaelAlg.Key = mRijndaelAlgKey;
                RijndaelAlg.IV = mRijndaelAlgIV;
            }

            mHashed = r.ReadBoolean();
            if (Hashed)
            {
                ReadVal(r, out mDataHash);
            }

            mCompressed = r.ReadBoolean();
            Length = r.ReadInt64();

            ReadVal(r, out mCreateTime);
        }
Пример #51
0
        public static BinaryReader Decrypt(String file, Rijndael crypt)
        {
            ICryptoTransform transform = crypt.CreateDecryptor();
            FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
            CryptoStream cs = new CryptoStream(fs, transform, CryptoStreamMode.Read);

            return new BinaryReader(cs);
        }
Пример #52
0
	public void SetUp () 
	{
		aes = Rijndael.Create ();
	}
Пример #53
0
 protected RijndaelTransform(Rijndael rijndael, PaddingMode paddingMode)
 {
     _Rijndael = rijndael;
     _PaddingMode = paddingMode;
 }