コード例 #1
0
        public static string AES_EncryptString(string plaintext)
        {
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt);
            AesManaged         aes = new AesManaged();

            aes.Key = key.GetBytes(32);
            aes.IV  = key.GetBytes(16);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cs);

            sw.WriteLine(plaintext);
            sw.Close();
            cs.Close();
            byte[] buffer          = ms.ToArray();
            string encryptedString = BytesToHexString(buffer);

            ms.Close();
            key.Reset();
            return(encryptedString);
        }
コード例 #2
0
        public IEnumerable <Password> GetPasswords(int moduleId, string strMasterPassword)
        {
            IEnumerable <Password> t;

            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository <Password>();
                t = rep.Get(moduleId);
            }
            IEnumerator <Password> passEnum = t.GetEnumerator();
            List <Password>        retList  = new List <Password>();

            while (passEnum.MoveNext())
            {
                // Try to decrypt, thus showing it can be round-tripped.
                byte[] salt1 = new byte[SALT_LEN];
                using (RNGCryptoServiceProvider rngCsp = new
                                                         RNGCryptoServiceProvider())
                {
                    // Fill the array with a random value.
                    rngCsp.GetBytes(salt1);
                }
                Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(strMasterPassword, passEnum.Current.PasswordSalt);
                Aes decAlg            = Aes.Create();
                decAlg.Key = k2.GetBytes(KEY_LEN);
                decAlg.IV  = passEnum.Current.PasswordIV;
                MemoryStream decryptionStreamBacking = new MemoryStream();
                CryptoStream decrypt = new CryptoStream(
                    decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
                decrypt.Write(passEnum.Current.PasswordText, 0, passEnum.Current.PasswordText.Length);
                decrypt.Flush();
                decrypt.Close();
                k2.Reset();
                passEnum.Current.PasswordPlainText = new UTF8Encoding(false).GetString(
                    decryptionStreamBacking.ToArray());
                retList.Add(passEnum.Current);
            }
            return(retList);
        }
コード例 #3
0
        public AesPasswordLocker(string pw, int keylen = 256)
        {
            // Check if the provided key length is standard
            if (!_stdaeskeylengths.Contains(keylen))
            {
                throw new Exception("AES key length can only be 128, 192 or 256");
            }

            // Create new objects
            _aesem  = new AesEncryptionManager();
            _keylen = keylen;
            // Generate safe random numbers, and fill up _salt with them
            _salt = new byte[_keylenBytes];
            RandomNumberGenerator.Create().GetNonZeroBytes(_salt);

            _deriveBytes = new Rfc2898DeriveBytes(pw, _salt);

            // Derive a key from the password and the generated salt, then take (keylength / 8) bytes
            _aesem.Aes.Key = _deriveBytes.GetBytes(_keylenBytes);
            _aesem.Aes.GenerateIV();

            _deriveBytes.Reset();
        }
コード例 #4
0
        /// <param name="key">32 bytes</param>
        /// <param name="vector">16 bytes</param>
        /// <param name="salt">Minimum 8 characters</param>
        /// <param name="fast">true to perform faster encryption / decryption by performing less iterations (at the cost of producing less secure keys). This should be left as false wherever possible.</param>
        public AESEncryption(byte[] key, byte[] vector, string salt, bool fast = false)
        {
            if (key.Length != 32)
            {
                throw new ArgumentException(nameof(key), "AESEncryption key must be 32 bytes.");
            }

            if (vector.Length != 16)
            {
                throw new ArgumentException(nameof(vector), "AESEncryption vector must be 16 bytes.");
            }

            if (salt.Length < 8)
            {
                throw new ArgumentException(nameof(salt), "AESEncryption salt must be at least 8 characters.");
            }

            _encoder = new UTF8Encoding();

            _algorithm = new RijndaelManaged
            {
                Mode      = CipherMode.CBC,
                Padding   = PaddingMode.PKCS7,
                KeySize   = 256,
                BlockSize = 128
            };

            var derivedValue = new Rfc2898DeriveBytes(key, _encoder.GetBytes(salt), fast ? 9 : 779);

            _algorithm.Key      = derivedValue.GetBytes(32);
            _algorithm.IV       = vector;
            _encryptorTransform = _algorithm.CreateEncryptor();
            _decryptorTransform = _algorithm.CreateDecryptor();

            derivedValue.Reset();
        }
コード例 #5
0
        public static void Main(string[] passwordargs)
        {
            passwordargs = new[] { "Flemming" };
            //If no file name is specified, write usage text.
            if (passwordargs.Length == 0)
            {
                Console.WriteLine(usageText);
            }
            else
            {
                string pwd1 = passwordargs[0];
                // Create a byte array to hold the random value.
                byte[] salt1 = new byte[8];
                using (RNGCryptoServiceProvider rngCsp = new
                                                         RNGCryptoServiceProvider())
                {
                    // Fill the array with a random value.
                    rngCsp.GetBytes(salt1);
                }

                //data1 can be a string or contents of a file.
                string data1 = "Some test data";
                //The default iteration count is 1000 so the two methods use the same iteration count.
                int myIterations = 1000;
                try
                {
                    Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, salt1, myIterations);
                    Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(pwd1, salt1);
                    // Encrypt the data.
                    Aes encAlg = Aes.Create();
                    encAlg.Key = k1.GetBytes(16);
                    MemoryStream encryptionStream = new MemoryStream();
                    CryptoStream encrypt          = new CryptoStream(encryptionStream,
                                                                     encAlg.CreateEncryptor(), CryptoStreamMode.Write);
                    byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(
                        data1);

                    encrypt.Write(utfD1, 0, utfD1.Length);
                    encrypt.FlushFinalBlock();
                    encrypt.Close();
                    byte[] edata1 = encryptionStream.ToArray();
                    k1.Reset();

                    // Try to decrypt, thus showing it can be round-tripped.
                    Aes decAlg = Aes.Create();
                    decAlg.Key = k2.GetBytes(16);
                    decAlg.IV  = encAlg.IV;
                    MemoryStream decryptionStreamBacking = new MemoryStream();
                    CryptoStream decrypt = new CryptoStream(
                        decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
                    decrypt.Write(edata1, 0, edata1.Length);
                    decrypt.Flush();
                    decrypt.Close();
                    k2.Reset();
                    string data2 = new UTF8Encoding(false).GetString(
                        decryptionStreamBacking.ToArray());

                    if (!data1.Equals(data2))
                    {
                        Console.WriteLine("Error: The two values are not equal.");
                    }
                    else
                    {
                        Console.WriteLine("The two values are equal.");
                        Console.WriteLine("k1 iterations: {0}", k1.IterationCount);
                        Console.WriteLine("k2 iterations: {0}", k2.IterationCount);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e);
                }
            }
        }
コード例 #6
0
    // RandomNumber
    // PublicKey
    // PublicKey2Str
    // Variables
    // BuildAESKeys
    // EncryptWithAES
    // DecryptWithAES
    // NOTE: Rijndael is NOT supported in WP8. If you want to use the Rijndael on
    // other platforms, simply add a compiler directive of "UseRijndael", or
    // comment out the if / endif lines

    #endregion Other

    #if (UseRijndael)

    // BuildRijndaelKeys
    // EncryptWithRijndael
    // DecryptWithRijndael

    /// <summary>
    /// builds keys for the crypto
    /// </summary>
    /// <param name="RCrypto"></param>
    /// <param name="key">the key to build with</param>
    /// <param name="keyStr">the key string to build with</param>
    private static void BuildRijndaelKeys(RijndaelManaged RCrypto, string keyStr, byte[] key)
    {
        // set block and key size
        RCrypto.BlockSize = RCrypto.LegalBlockSizes[0].MaxSize;
        RCrypto.KeySize = RCrypto.LegalKeySizes[0].MaxSize;

        /*
            What the key derivation function (Rfc2898DeriveBytes) does is repeatedly hash the user password along with a salt. This has multiple benefits:

                1) you can use arbitrarily sized passwords – AES only supports specific key sizes.

                2) the addition of the salt means that you can use the same passphrase to generate multiple different.
                    This is important for key separation; reusing keys in different contexts is one of the most common ways cryptographic systems are broken.

            The beauty of this is that every time you encrypt plain text P1 with the derived key, you will get a different cipher text out the other side.
            But those different cipher texts can all be decrypted with the same key.
        */
        Rfc2898DeriveBytes KeyDerivationFunction = new Rfc2898DeriveBytes(keyStr, key);

        // derive our key, and IV (Rijndael)
        byte[] keyBytes = KeyDerivationFunction.GetBytes(RCrypto.KeySize / 8);
        KeyDerivationFunction.Reset();
        byte[] ivBytes = KeyDerivationFunction.GetBytes(RCrypto.BlockSize / 8);

        // populate keys in crypto
        RCrypto.Key = keyBytes;
        RCrypto.IV = ivBytes;
        RCrypto.Mode = CipherMode.CBC;
        RCrypto.Padding = PaddingMode.PKCS7;
    }
コード例 #7
0
        /// <inheritdoc />
        public override void ForwardProcessDataStream(System.IO.Stream inStream, System.IO.Stream outStream, Dictionary <string, string> options, out long writtenBytes)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            else if (!options.ContainsKey(PasswordOption))
            {
                throw new ArgumentException("Options must contain encryption key", "options");
            }

            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }

#if NETFX_CORE
            inStream.Seek(0, 0);
            outStream.Seek(0, 0);

            IBuffer pwBuffer   = CryptographicBuffer.ConvertStringToBinary(options[PasswordOption], BinaryStringEncoding.Utf8);
            IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(SALT);

            // Derive key material for password size 32 bytes for AES256 algorithm
            KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            // using salt and 1000 iterations
            KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);

            // create a key based on original key and derivation parmaters
            CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
            IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

            // derive buffer to be used for encryption salt from derived password key
            IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

            // display the buffers - because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
            string keyMaterialString  = CryptographicBuffer.EncodeToBase64String(keyMaterial);
            string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);

            SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            // create symmetric key from derived password key
            CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

            using (MemoryStream ms = new MemoryStream())
            {
                inStream.CopyTo(ms);
                // encrypt data buffer using symmetric key and derived salt material
                IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(ms), saltMaterial);
                resultBuffer.AsStream().CopyTo(outStream);
                writtenBytes = outStream.Position;
            }
#else
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(options[PasswordOption], SALT);
            var key = pdb.GetBytes(32);
            pdb.Reset();
            var iv = pdb.GetBytes(16);

            using (var transform = encrypter.CreateEncryptor(key, iv))
            {
                using (MemoryStream internalStream = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(internalStream, transform, CryptoStreamMode.Write))
                    {
                        StreamTools.Write(inStream, csEncrypt);
                        inStream.Flush();
                        csEncrypt.FlushFinalBlock();

                        internalStream.Seek(0, 0);
                        StreamTools.Write(internalStream, outStream);
                        writtenBytes = outStream.Position;
                    }
                }
            }
#endif
        }
コード例 #8
0
        public ActionResult Edit(Password password)
        {
            if (password.PasswordId == -1)
            {
                password.CreatedByUserId      = User.UserID;
                password.CreatedOnDate        = DateTime.UtcNow;
                password.LastModifiedByUserId = User.UserID;
                password.LastModifiedOnDate   = DateTime.UtcNow;
                string pwd1 = ModuleContext.Configuration.ModuleSettings["JTM2_PasswordManager_MasterPassword"].ToString();
                // Create a byte array to hold the random value.
                byte[] salt1 = new byte[SALT_LEN];
                using (RNGCryptoServiceProvider rngCsp = new
                                                         RNGCryptoServiceProvider())
                {
                    // Fill the array with a random value.
                    rngCsp.GetBytes(salt1);
                }

                //data1 can be a string or contents of a file.
                string data1 = password.PasswordPlainText;
                //The default iteration count is 1000 so the two methods use the same iteration count.
                try
                {
                    Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, salt1,
                                                                   NUM_PBKDF2_ITERS);
                    // Encrypt the data.
                    Aes encAlg = Aes.Create();
                    password.PasswordIV = encAlg.IV;

                    encAlg.Key = k1.GetBytes(KEY_LEN);
                    MemoryStream encryptionStream = new MemoryStream();
                    CryptoStream encrypt          = new CryptoStream(encryptionStream,
                                                                     encAlg.CreateEncryptor(), CryptoStreamMode.Write);
                    byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(
                        data1);

                    encrypt.Write(utfD1, 0, utfD1.Length);
                    encrypt.FlushFinalBlock();
                    encrypt.Close();
                    byte[] edata1 = encryptionStream.ToArray();
                    password.PasswordText = edata1;
                    k1.Reset();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: ", e);
                }

                password.PasswordSalt = salt1;

                password.PasswordPlainText = "";

                PasswordManager.Instance.CreatePassword(password);
            }
            else
            {
                var existingPassword = PasswordManager.Instance.GetPassword(password.PasswordId, password.ModuleId);
                existingPassword.LastModifiedByUserId = User.UserID;
                existingPassword.LastModifiedOnDate   = DateTime.UtcNow;
                existingPassword.PasswordSite         = password.PasswordSite;
                existingPassword.PasswordText         = password.PasswordText;
                existingPassword.PasswordUrl          = password.PasswordUrl;
                existingPassword.PasswordNotes        = password.PasswordNotes;
                existingPassword.PasswordPlainText    = "";
                existingPassword.PasswordIV           = password.PasswordIV;
                existingPassword.PasswordSalt         = password.PasswordSalt;

                existingPassword.AssignedUserId = password.AssignedUserId;

                PasswordManager.Instance.UpdatePassword(existingPassword);
            }

            return(RedirectToDefaultRoute());
        }
コード例 #9
0
        public void MsdnExample()
        {
            const string pwd1         = "b@nana!123";
            const int    myIterations = 1000;

            // data1 can be a string or contents of a file.
            const string data1 = "Some test data";

            // Create a byte array to hold the random value.
            byte[] randomSalt = new byte[8];
            using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with a random value.
                rngCsp.GetBytes(randomSalt);
            }

            ////	try
            ////	{
            // The default iteration count is 1000 so the two methods use the same iteration count.
            Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, randomSalt, myIterations);
            Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(pwd1, randomSalt);

            // Encrypt the data.
            SymmetricAlgorithm encAlg = TripleDES.Create();

            encAlg.Key = k1.GetBytes(16);

            MemoryStream encryptionStream = new MemoryStream();
            CryptoStream encrypt          = new CryptoStream(
                encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write);

            byte[] utfD1 = new UTF8Encoding(false).GetBytes(data1);

            encrypt.Write(utfD1, 0, utfD1.Length);
            encrypt.FlushFinalBlock();
            encrypt.Close();
            byte[] edata1 = encryptionStream.ToArray();

            // Erase memory for optimum secrecy?
            k1.Reset();

            // Try to decrypt, thus showing it can be round-tripped.
            SymmetricAlgorithm decAlg = TripleDES.Create();

            decAlg.Key = k2.GetBytes(16);

            // Relay the one-time INITIALIZATION VECTOR
            // generated by the original encryption.
            // Could this have been initialized via the Rfc k1/k2?
            decAlg.IV = encAlg.IV;

            MemoryStream decryptionStreamBacking = new MemoryStream();
            CryptoStream decrypt = new CryptoStream(
                decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);

            decrypt.Write(edata1, 0, edata1.Length);
            decrypt.Flush();
            decrypt.Close();

            // Erase memory for optimum secrecy?
            k2.Reset();

            string data2 = new UTF8Encoding(false).GetString(decryptionStreamBacking.ToArray());

            if (!data1.Equals(data2))
            {
                Console.WriteLine("Error: The two values are not equal.");
            }
            else
            {
                Console.WriteLine("The two values are equal.");
                Console.WriteLine("k1 iterations: {0}", k1.IterationCount);
                Console.WriteLine("k2 iterations: {0}", k2.IterationCount);
            }
            ////	}
            ////	catch (Exception e)
            ////	{
            ////		Console.WriteLine("Error: {0}", e);
            ////	}

            Assert.AreEqual(data2, data1);
            Assert.IsTrue(data1.Equals(data2));
        }
コード例 #10
0
 public void Reset()
 {
     bytes.Reset();
     initCoords();
 }
コード例 #11
0
 private static void WriteArray(Rfc2898DeriveBytes source, int count)
 {
     source.Reset();
     Console.WriteLine(string.Join(" ", source.GetBytes(count).Select(b => b.ToString())));
 }
コード例 #12
0
        public async Task Run()
        {
            const string pwd1 = "mypassword";

            // Create a byte array to hold the random value.
            var salt1 = new byte[8];

            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with a random value.
                rngCsp.GetBytes(salt1);
            }

            //data1 can be a string or contents of a file.
            const string data1 = "Some test data";

            //The default iteration count is 1000 so the two methods use the same iteration count.
            const int myIterations = 1000;

            try
            {
                var k1 = new Rfc2898DeriveBytes(pwd1, salt1, myIterations);
                var k2 = new Rfc2898DeriveBytes(pwd1, salt1);

                // Encrypt the data.
                var encAlg = TripleDES.Create();
                encAlg.Key = k1.GetBytes(16);
                var encryptionStream = new MemoryStream();
                var encrypt          = new CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write);
                var utfD1            = new UTF8Encoding(false).GetBytes(data1);

                encrypt.Write(utfD1, 0, utfD1.Length);
                encrypt.FlushFinalBlock();
                encrypt.Close();
                var edata1 = encryptionStream.ToArray();
                k1.Reset();

                // Try to decrypt, thus showing it can be round-tripped.
                var decAlg = TripleDES.Create();
                decAlg.Key = k2.GetBytes(16);
                decAlg.IV  = encAlg.IV;
                var decryptionStreamBacking = new MemoryStream();

                var decrypt = new CryptoStream(decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);

                decrypt.Write(edata1, 0, edata1.Length);
                decrypt.Flush();
                decrypt.Close();
                k2.Reset();

                var data2 = new UTF8Encoding(false).GetString(decryptionStreamBacking.ToArray());

                if (!data1.Equals(data2))
                {
                    Console.WriteLine("Error: The two values are not equal.");
                }
                else
                {
                    Console.WriteLine("The two values are equal.");
                    Console.WriteLine("k1 iterations: {0}", k1.IterationCount);
                    Console.WriteLine("k2 iterations: {0}", k2.IterationCount);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }