コード例 #1
0
        // 當不傳Key進來用預設的Key值
        public string DecryptDerivedKey(string SrcString)
        {
            try
            {
                Byte[] edata1 = Convert.FromBase64String(SrcString);

                PasswordDeriveBytes pdb = new PasswordDeriveBytes(DefaultPassword, DefaultSalt);

                byte[] iv  = new byte[] { 0xA0, 0x16, 0xBC, 0xF2, 0x08, 0x3C, 0x55, 0x68 };
                byte[] key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, iv);


                TripleDES decAlg = TripleDES.Create();
                decAlg.Key = key;
                decAlg.IV  = new byte[] { 0x06, 0xA2, 0xCC, 0x53, 0x2B, 0x33, 0x28, 0x2F };



                MemoryStream decryptionStreamBacking = new MemoryStream();
                CryptoStream decrypt = new CryptoStream(decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);
                decrypt.Write(edata1, 0, edata1.Length);
                decrypt.Flush();
                decrypt.Close();
                pdb.Reset();
                string data2 = new UTF8Encoding(false).GetString(decryptionStreamBacking.ToArray());

                return(data2);
            }
            catch (Exception EX)
            {
                throw EX;
            }
        }
コード例 #2
0
    public static void Main() {
        string PlainText = "Titan";
        byte[] PlainBytes = new byte[5];
        PlainBytes = Encoding.ASCII.GetBytes(PlainText.ToCharArray());
        PrintByteArray(PlainBytes);
        byte[] CipherBytes = new byte[8];
        PasswordDeriveBytes pdb = new PasswordDeriveBytes("Titan", null);
        byte[] IV = new byte[8];
        byte[] Key = pdb.CryptDeriveKey("RC2", "SHA1", 40, IV);
        PrintByteArray(Key);
        PrintByteArray(IV);

        // Now use the data to encrypt something
        RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
        Console.WriteLine(rc2.Padding);
        Console.WriteLine(rc2.Mode);
        ICryptoTransform sse = rc2.CreateEncryptor(Key, IV);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs1 = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs1.Write(PlainBytes, 0, PlainBytes.Length);
        cs1.FlushFinalBlock();
        CipherBytes = ms.ToArray();
        cs1.Close();
        Console.WriteLine(Encoding.ASCII.GetString(CipherBytes));
        PrintByteArray(CipherBytes);

        ICryptoTransform ssd = rc2.CreateDecryptor(Key, IV);
        CryptoStream cs2 = new CryptoStream(new MemoryStream(CipherBytes), ssd, CryptoStreamMode.Read);
        byte[] InitialText = new byte[5];
        cs2.Read(InitialText, 0, 5);
        Console.WriteLine(Encoding.ASCII.GetString(InitialText));
    	PrintByteArray(InitialText);
    }
コード例 #3
0
        // 當不傳Key進來用預設的Key值
        public string EncryptDerivedKey(string SrcString)
        {
            try
            {
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(DefaultPassword, DefaultSalt);

                byte[] iv  = new byte[] { 0xA0, 0x16, 0xBC, 0xF2, 0x08, 0x3C, 0x55, 0x68 };
                byte[] key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, iv);

                // Encrypt the data.
                TripleDES encAlg = TripleDES.Create();
                encAlg.Key = key;
                encAlg.IV  = new byte[] { 0x06, 0xA2, 0xCC, 0x53, 0x2B, 0x33, 0x28, 0x2F };


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


                byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes(SrcString);

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

                // 以Base-64編碼傳回
                return(Convert.ToBase64String(edata1));
            }
            catch (Exception EX)
            {
                throw EX;
            }
        }
コード例 #4
0
        void generateIV()
        {
            PasswordDeriveBytes cdk = new PasswordDeriveBytes(tbIV.Text, null);

            byte[] iv  = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] key = cdk.CryptDeriveKey("RC2", "SHA1", 128, iv);
            tbIV.Text = Convert.ToBase64String(key);
        }
コード例 #5
0
        private static string EncryptPassword(byte[] password, byte[] salt)
        {
            PasswordDeriveBytes            passwordGenerator = new PasswordDeriveBytes(password, salt);
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            var hashedPassword = passwordGenerator.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);

            return(Convert.ToBase64String(hashedPassword.Concat(salt).ToArray()));
        }
コード例 #6
0
        private static byte[] GetSecretKey(string password)
        {
            string secretKey = "dr0!sys";   // need to replace with some string from client side

            byte[] salt             = { 0, 0, 0, 0, 0, 0, 0, 0 };
            PasswordDeriveBytes cdk = new PasswordDeriveBytes(secretKey, salt);

            return(cdk.CryptDeriveKey("RC2", "SHA1", 128, salt));
        }
コード例 #7
0
        /// <summary>
        /// Creates a key from the password
        /// </summary>
        /// <param name="password"></param>
        public void SetKeyFromPassword(string password)
        {
            // TODO salt and iv should not be hard coded
            byte[] iv               = { 10, 31, 244, 101, 53, 13, 7, 3 };
            var    salt             = password.ToUpper() + password.ToLower() + (password.Length * 31);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password,
                                                              Encoding.Default.GetBytes(salt));

            Key = pdb.CryptDeriveKey("TripleDES", "SHA256", 192, iv);
        }
コード例 #8
0
ファイル: UnitTest1.cs プロジェクト: mmeents/DataMattei
        public string toDESCipher(string sText)
        {
            string sResult = "";
            DESCryptoServiceProvider aCSP = new DESCryptoServiceProvider();

            aCSP.Key = PDB.CryptDeriveKey("DES", "SHA1", 64, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
            aCSP.IV  = MMExt.defIV;
            MemoryStream ms        = new MemoryStream();
            CryptoStream encStream = new CryptoStream(ms, aCSP.CreateEncryptor(), CryptoStreamMode.Write);
            StreamWriter sw        = new StreamWriter(encStream);

            sw.WriteLine(sText.toBase64EncodedStr());
            sw.Close();
            encStream.Close();
            byte[] buffer = ms.ToArray();
            ms.Close();
            sResult = buffer.toHexStr();
            return(sResult);
        }
コード例 #9
0
        /// <summary>
        /// Creates a transform based on CryptoStreamMode.
        /// </summary>
        /// <param name="Mode"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        private static ICryptoTransform CreateTripleDESTransform(CryptoStreamMode Mode, string Password)
        {
            byte[] key     = null;
            byte[] pdbsalt = null;
            byte[] iv      = null;

            try
            {
                // Salt byte array.
                pdbsalt = GetPdbSalt();

                // Create PasswordDeriveBytes object that will generate
                // a Key for TripleDES algorithm.
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, pdbsalt);

                iv = new byte[8] {
                    1, 0, 0, 1, 1, 0, 0, 1
                };
                // Create a private key for TripleDES algorithm.
                // The iv parameter is not currently used.
                // * http://blogs.msdn.com/shawnfa/archive/2004/04/14/113514.aspx
                key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, iv);

                switch (Mode)
                {
                case CryptoStreamMode.Read:
                    return(TripleDES.Create().CreateDecryptor(key, iv));

                case CryptoStreamMode.Write:
                    return(TripleDES.Create().CreateEncryptor(key, iv));

                default:
                    return(null);
                }
            }
            catch (CryptographicException)
            {
                return(null);
            }
            finally
            {
                if (key != null)
                {
                    Array.Clear(key, 0, key.Length);
                }
                if (pdbsalt != null)
                {
                    Array.Clear(pdbsalt, 0, pdbsalt.Length);
                }
                if (iv != null)
                {
                    Array.Clear(iv, 0, iv.Length);
                }
            }
        }
コード例 #10
0
        public static byte[] DerivePasswordFromPlainText(string passphrase, string salted)
        {
            TripleDESCryptoServiceProvider csp = new TripleDESCryptoServiceProvider();

            byte[] buffer         = Encoding.UTF8.GetBytes(passphrase);
            byte[] salt           = Encoding.UTF8.GetBytes(salted);
            PasswordDeriveBytes p = new PasswordDeriveBytes(buffer, salt);

            byte[] k = p.CryptDeriveKey("TripleDES", "SHA1", 192, csp.IV);
            return(k);
        }
コード例 #11
0
        public byte[] DeriveKey(string password)
        {
            var passwordDeriveBytes = new PasswordDeriveBytes(password, PasswordSalt);
            var initialVector       = new byte[InitialVector.Length];

            InitialVector.CopyTo(initialVector, 0);
            return(passwordDeriveBytes.CryptDeriveKey(SymmetricAlgorithm.GetType().BaseType.Name,
                                                      PasswordHashAlgorithm.GetType().BaseType.Name,
                                                      SymmetricAlgorithm.LegalKeySizes.First().MaxSize,
                                                      initialVector));
        }
コード例 #12
0
    /// <summary>
    ///		Derive key, null IV
    /// </summary>
    private static void DeriveKeyNullIv()
    {
        string password = "******";

        byte[] salt = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };

        PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt);

        pdb.CryptDeriveKey("RC2", "MD5", 21, null);
        return;
    }
コード例 #13
0
ファイル: Form1.cs プロジェクト: Sofon/ZI22Lab
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     // если форму закрывает пользователь (нормальное завершение работы программы)
     if (e.CloseReason != CloseReason.ApplicationExitCall)
     {
         pwd = Encoding.Unicode.GetBytes(passFrase.Edit1.Text);
         buf = new byte[pwd.Length + randBytes.Length];
         // создание объекта для генерации случайной примеси
         RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
         // создание буфера для случайной примеси
         randBytes    = new byte[8];
         randBytes[1] = 1;
         randBytes[5] = 1;
         // получение примеси для секретного ключа
         //rand.GetBytes(randBytes);
         // создание объекта для вывода ключа из парольной фразы
         pdb = new PasswordDeriveBytes(pwd, randBytes);
         // копирование в буфер примеси
         randBytes.CopyTo(buf, pwd.Length);
         // генерация начального вектора для блочного шифрования
         rc2CSP.GenerateIV();
         // вывод ключа шифрования из парольной фразы и примеси
         rc2CSP.Key = pdb.CryptDeriveKey("RC2", "SHA", rc2CSP.KeySize, rc2CSP.IV);
         // создание объекта шифрования
         ICryptoTransform encryptor = rc2CSP.CreateEncryptor(rc2CSP.Key, rc2CSP.IV);
         // создание нового файла
         Acc.AccFile = new FileStream(Account.SECFILE, FileMode.Create);
         // запись в начало зашифрованного файла случайной примеси
         Acc.AccFile.Write(randBytes, 0, 8);
         // сохранение в файле начального вектора
         Acc.AccFile.Write(rc2CSP.IV, 0, rc2CSP.BlockSize / 8);
         // создание объекта для потока шифрования
         CrStream = new CryptoStream(Acc.AccFile, encryptor, CryptoStreamMode.Write);
         // смещение к началу потока в памяти
         Acc.AccMem.Seek(0, SeekOrigin.Begin);
         // выделение памяти для буфера ввода-вывода
         bytes = new byte[Acc.AccMem.Length];
         // задание количества непрочитанных байт
         numBytesToRead = (int)Acc.AccMem.Length;
         // получение данных из потока в памяти
         int n = Acc.AccMem.Read(bytes, 0, numBytesToRead);
         // сохранение фактического количества прочитанных байт
         numBytesToRead = n;
         // запись в зашифрованный файл
         CrStream.Write(bytes, 0, numBytesToRead);
         // очистка памяти с конфиденциальными данными
         rc2CSP.Clear();
         // закрытие потока шифрования
         CrStream.Close();
         // закрытие файла и потока в памяти
         Acc.AccMem.Close();
         Acc.AccFile.Close();
     }
 }
コード例 #14
0
        public void PasswordDerivedBytes_Test()
        {
            byte[] randBytes = new byte[5];
            new Random(10032010).NextBytes(randBytes);


            var tdes  = new TripleDESCryptoServiceProvider();
            var pwddb = new PasswordDeriveBytes("1", new byte[] { 1 });

            tdes.Key = pwddb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);
            //string s = Convert.ToBase64String(tdes.Key);
        }
コード例 #15
0
ファイル: Form1.cs プロジェクト: snitinjames/Aes-Rijn
        private void button2_Click(object sender, EventArgs e)
        {
            byte[] salt             = { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] V                = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            PasswordDeriveBytes cdk = new PasswordDeriveBytes(textBox4.Text, salt);

            //string kex = Convert.ToBase64String(cdk.CryptDeriveKey("RC2", "SHA1", 128, salt));
            byte[] kex    = cdk.CryptDeriveKey("RC2", "SHA1", 128, salt);
            string answer = Decrypt(textBox1.Text, kex, V);

            textBox3.Text = answer;
        }
コード例 #16
0
	public static Boolean TestRepeated()
	{
		Boolean bRes = true;
		int l, key_size;
		Char[] ach;
		String s;
		Byte[] salt, the_key, temp_key, iv = new Byte[8];
		PasswordDeriveBytes pdb;

		for(int i=0; i<NO_PASSES; i++) {
			l = Rnd.Next(MAX_PASS_LEN)+1;
			ach = new Char[l];
			for(int k=0; k<l; k++) ach[k] = (Char)(Rnd.Next(26)+65);
			s = new String(ach);
			salt = new Byte[Rnd.Next(MAX_SALT_LEN)];
			Rnd.NextBytes(salt);
			key_size = Rnd.Next(128);
			Rnd.NextBytes(iv);

			pdb = new PasswordDeriveBytes(s, salt);
			the_key = pdb.CryptDeriveKey("RC2", "SHA1", /*key_size*/ 128, iv);

			Console.WriteLine("--------------------------------------");
			PrintByteArray(the_key);

			for (int j=0; j<MAX_COMP;j++) {
				temp_key = pdb.CryptDeriveKey("RC2", "SHA1", /*key_size*/ 128, iv);
				Console.WriteLine("--------------------------------------");
				PrintByteArray(temp_key);
				if (!Compare(the_key, temp_key)) {
					bRes = false;
					Console.WriteLine("Two passes of CryptDeriveKey yielded different results");
					break;
				}
			}
			if (bRes == false) break;
		}

		return bRes;
	}
コード例 #17
0
        private ICryptoTransform CreateTranformer(bool forEncryption)
        {
            byte[] key     = null;
            byte[] pdbsalt = null;
            byte[] iv      = null;

            try
            {
                // Salt byte array.
                pdbsalt = GenerateSalt();

                // Create PasswordDeriveBytes object that will generate
                // a Key for TripleDES algorithm.
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(_key, pdbsalt);

                iv = new byte[8] {
                    0, 0, 0, 0, 0, 0, 0, 0
                };
                // Create a private key for TripleDES algorithm.
                // The iv parameter is not currently used.
                // * http://blogs.msdn.com/shawnfa/archive/2004/04/14/113514.aspx
                key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, iv);

                if (forEncryption)
                {
                    return(TripleDES.Create().CreateEncryptor(key, iv));
                }
                else
                {
                    return(TripleDES.Create().CreateDecryptor(key, iv));
                }
            }
            catch (CryptographicException)
            {
                return(null);
            }
            finally
            {
                if (key != null)
                {
                    Array.Clear(key, 0, key.Length);
                }
                if (pdbsalt != null)
                {
                    Array.Clear(pdbsalt, 0, pdbsalt.Length);
                }
                if (iv != null)
                {
                    Array.Clear(iv, 0, iv.Length);
                }
            }
        }
コード例 #18
0
ファイル: SymmetricHelper.cs プロジェクト: valadas/DNNStore
        /// <summary>
        /// Generate a key from a password with the specified
        /// algorithms, key size and IV.
        /// </summary>
        /// <param name="password">Password</param>
        /// <param name="algorithm">Symmetric algorithm</param>
        /// <param name="keySize">Symmetric key size</param>
        /// <param name="hash">Hash algorithm</param>
        /// <param name="iv">IV</param>
        /// <returns>Key</returns>
        public static byte[] GenerateKeyFromPassword(string password, SymmAlgorithm algorithm, int keySize, HashAlgorithm hash, byte[] iv)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            string algName  = Enum.GetName(typeof(SymmAlgorithm), algorithm);
            string hashName = Enum.GetName(typeof(HashAlgorithm), hash);
            // Generate a key from params
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, null);

            byte[] key = pdb.CryptDeriveKey(algName, hashName, keySize, iv);
            return(key);
        }
コード例 #19
0
        private void InitializeHeaderCryptoProvider(string password)
        {
            var bpwd = new PasswordDeriveBytes(password, CreateRandomSalt(7));

            var rc2 = new RC2CryptoServiceProvider();
            var key = bpwd.CryptDeriveKey("RC2", "SHA1", 128, new byte[rc2.IV.Length]);

            var hashProvider = SHA256.Create();

            HeaderCryptoProvider.Key = key;

            PasswordKeyHash = hashProvider.ComputeHash(HeaderCryptoProvider.Key);

            HeaderCryptoProvider.Padding = PaddingMode.Zeros;
        }
コード例 #20
0
        /// <summary>
        /// 設定要產生金鑰的密碼
        /// </summary>
        /// <param name="tPassword">密碼</param>
        public void set_Password(string tPassword)
        {
            //this._tPassword = tPassword;
            //this._pwd = Encoding.Unicode.GetBytes(tPassword);
            //this._salt = CreateRandomSalt(7);
            //PasswordDeriveBytes oPDB = new PasswordDeriveBytes(_pwd, _salt);
            //_TripleDES.Key = oPDB.CryptDeriveKey("TripleDES", "SHA1", 192, _TripleDES.IV);

            this._tPassword = tPassword;
            this._pwd       = Encoding.Unicode.GetBytes(tPassword);
            this._salt      = CreateRandomSalt(7);
            PasswordDeriveBytes oPDB = new PasswordDeriveBytes(_pwd, _salt);

            _TripleDES.Key = oPDB.CryptDeriveKey("TripleDES", "SHA1", 192, _TripleDES.IV);
        }
コード例 #21
0
        void keyExpand()
        {
            keySchedule = new byte[4, (Nr + 1) * 4];

            PasswordDeriveBytes cdk = new PasswordDeriveBytes(tbPassword.Text, null);

            byte[] iv  = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] key = cdk.CryptDeriveKey("RC2", "SHA1", 128, iv);

            int length = 4;
            int k      = 0;

            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length; j++)
                {
                    keySchedule[i, j] = key[k++];
                }
            }

            for (int col = 4; col < (Nr + 1) * 4; col++)
            {
                if (col % 4 == 0)
                {
                    keySchedule[0, col] = keySchedule[1, col - 1];
                    keySchedule[1, col] = keySchedule[2, col - 1];
                    keySchedule[2, col] = keySchedule[3, col - 1];
                    keySchedule[3, col] = keySchedule[0, col - 1];

                    keySchedule[0, col] = sBox[keySchedule[0, col]];
                    keySchedule[1, col] = sBox[keySchedule[1, col]];
                    keySchedule[2, col] = sBox[keySchedule[2, col]];
                    keySchedule[3, col] = sBox[keySchedule[3, col]];

                    keySchedule[0, col] = (byte)(keySchedule[0, col] ^ keySchedule[0, col - 4] ^ Rcon[col / 4]);
                    keySchedule[1, col] = (byte)(keySchedule[1, col] ^ keySchedule[1, col - 4] ^ 0);
                    keySchedule[2, col] = (byte)(keySchedule[2, col] ^ keySchedule[2, col - 4] ^ 0);
                    keySchedule[3, col] = (byte)(keySchedule[3, col] ^ keySchedule[3, col - 4] ^ 0);
                }
                else
                {
                    keySchedule[0, col] = (byte)(keySchedule[0, col - 1] ^ keySchedule[0, col - 4]);
                    keySchedule[1, col] = (byte)(keySchedule[1, col - 1] ^ keySchedule[1, col - 4]);
                    keySchedule[2, col] = (byte)(keySchedule[2, col - 1] ^ keySchedule[2, col - 4]);
                    keySchedule[3, col] = (byte)(keySchedule[3, col - 1] ^ keySchedule[3, col - 4]);
                }
            }
        }
コード例 #22
0
ファイル: sample.cs プロジェクト: zhamppx97/dotnet-api-docs
    public static void Main(String[] args)
    {
        // Get a password from the user.
        Console.WriteLine("Enter a password to produce a key:");

        byte[] pwd = Encoding.Unicode.GetBytes(Console.ReadLine());

        byte[] salt = CreateRandomSalt(7);

        // Create a TripleDESCryptoServiceProvider object.
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

        try
        {
            Console.WriteLine("Creating a key with PasswordDeriveBytes...");

            // Create a PasswordDeriveBytes object and then create
            // a TripleDES key from the password and salt.
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);

            // <Snippet2>

            // Create the key and set it to the Key property
            // of the TripleDESCryptoServiceProvider object.
            // This example uses the SHA1 algorithm.
            // Due to collision problems with SHA1, Microsoft recommends SHA256 or better.
            tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);

            //</Snippet2>

            Console.WriteLine("Operation complete.");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // Clear the buffers
            ClearBytes(pwd);
            ClearBytes(salt);

            // Clear the key.
            tdes.Clear();
        }

        Console.ReadLine();
    }
コード例 #23
0
        public EncryptionTransform(String password)
        {
            PasswordDeriveBytes passwordBytes =
                new PasswordDeriveBytes(password + paranoidSaltString, salt);

            // Create a TripleDESCryptoServiceProvider object.
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Mode = CipherMode.ECB;

            // Create the key and add it to the Key property.
            tdes.Key = passwordBytes.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);

            decrypter = tdes.CreateDecryptor();
            encrypter = tdes.CreateEncryptor();
        }
コード例 #24
0
        internal string Decrypt(string encryptedString)
        {
            PasswordDeriveBytes keyGenerator = new PasswordDeriveBytes(_keyGeneratorPassword, null);

            byte[] cryptoKey = keyGenerator.CryptDeriveKey("RC2", "SHA1", 128, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });

            using (RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider())
            {
                using (ICryptoTransform decryptor = rc2.CreateDecryptor(cryptoKey, StringToByteArray(_initializationVector)))
                {
                    byte[] encryptedBytes = Convert.FromBase64String(encryptedString);
                    byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
                    return(ByteArrayToString(decryptedBytes));
                }
            }
        }
コード例 #25
0
        public static byte[] generateKeyAESKey(byte[] password, byte[] iv, int iterationCount, int keyLength)
        {
            if (password == null)
            {
                throw new Exception("Password is empty");
            }

            if (password.Length == 0)
            {
                throw new Exception("Password has zero length");
            }

            if (iv == null)
            {
                throw new Exception("IV is empty");
            }

            if (iv.Length == 0)
            {
                throw new Exception("IV has zero length");
            }

            if (iterationCount < 1000)
            {
                throw new Exception("Iteration Count should be minimum than 1000");
            }

            if ((keyLength != 128) && (keyLength != 192) && (keyLength != 256))
            {
                throw new Exception("Key Length is invalid. It can be only 128 or 192 or 256.");
            }
            try
            {
                PasswordDeriveBytes a = new  PasswordDeriveBytes(password, iv);
                return(a.CryptDeriveKey("SHA1", "AES", keyLength, iv));
                //KeySpec keySpec = new PBEKeySpec(password, iv, iterationCount, keyLength);
                //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
                //byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
                //SecretKey skey = new SecretKeySpec(keyBytes, "AES");
                //return skey.getEncoded();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #26
0
        private static byte[] TestKnownValue_CryptDeriveKey(HashAlgorithmName hashName, string password, string alg, int keySize, byte[] salt, byte[] expected)
        {
            byte[] output;
            byte[] iv = new byte[8];

            using (var deriveBytes = new PasswordDeriveBytes(password, salt))
            {
                output = deriveBytes.CryptDeriveKey(alg, hashName.Name, keySize, iv);
            }

            Assert.Equal(expected, output);

            // For these tests, the returned IV is always zero
            Assert.Equal(new byte[8], iv);

            return(output);
        }
コード例 #27
0
ファイル: MainForm.cs プロジェクト: mongeon/FreeMeterRevival
		private string Decrypt(string encryptedBase64, string password)
		{
			TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
			des.IV = new byte[8];
			PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[0]);
			des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
			byte[] encryptedBytes = Convert.FromBase64String(encryptedBase64);
			MemoryStream ms = new MemoryStream(encryptedBase64.Length);
			CryptoStream decStream = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
			decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
			decStream.FlushFinalBlock();
			byte[] plainBytes = new byte[ms.Length];
			ms.Position = 0;
			ms.Read(plainBytes, 0, (int)ms.Length);
			decStream.Close();
			ms.Close();
			return Encoding.UTF8.GetString(plainBytes);
		}
コード例 #28
0
	// Get the encryption key to use to protect memory for a scope.
	private static byte[] GetScopeKey(MemoryProtectionScope scope, byte[] salt)
			{
				String key;
				PasswordDeriveBytes derive;
				if(scope == MemoryProtectionScope.SameLogon)
				{
					key = Environment.UserName;
				}
				else
				{
					key = Environment.UserName + "/" + Environment.MachineName;
				}
				if(salt == null)
				{
					salt = new byte [16];
				}
				derive = new PasswordDeriveBytes(key, salt);
				return derive.CryptDeriveKey("Rijndael", "SHA1", 16, null);
			}
コード例 #29
0
ファイル: Package.cs プロジェクト: trickbooter/ssis-build
        protected override void EncryptElement(XmlElement element, string password)
        {
            var rgbSalt = new byte[7];

            new RNGCryptoServiceProvider().GetBytes(rgbSalt);
            var cryptoServiceProvider = new TripleDESCryptoServiceProvider();
            var passwordDeriveBytes   = new PasswordDeriveBytes(password, rgbSalt);

            cryptoServiceProvider.Key = passwordDeriveBytes.CryptDeriveKey("TripleDES", "SHA1", 192, cryptoServiceProvider.IV);

            var exml = new EncryptedXml();

            var encryptedElement = exml.EncryptData(element, cryptoServiceProvider, false);

            var encryptedData = new EncryptedData
            {
                Type             = EncryptedXml.XmlEncElementUrl,
                EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl),
                CipherData       = { CipherValue = encryptedElement }
            };


            // first we add it as a child, then move forward. I did not want to call an internal method (why do they make all useful methods internal?)
            // It is inconsistent at this level. For connection managers, it encrypts the entire element and just replaces the element's outer xml with encrypted node
            // For package parameters they leave original element with DTS:Name attribute, remove all other attributes such as DTS:DataType and then add encrypted element
            // as an inner xml to original element. This is what I have observed, hopefully it is at least consistentl inconsistent, and there is no third way.
            EncryptedXml.ReplaceElement(element, encryptedData, true);
            var replacementElement = element.FirstChild as XmlElement;
            var parentNode         = element.ParentNode;

            if (replacementElement != null && parentNode != null)
            {
                replacementElement.SetAttribute("Salt", Convert.ToBase64String(rgbSalt));
                replacementElement.SetAttribute("IV", Convert.ToBase64String(cryptoServiceProvider.IV));

                // if parent node is marked as sensitive, then it needs to be replaced. Otherwise leave the encrypted node where it is.
                if (XmlHelpers.GetAttributeNode(parentNode, "Sensitive")?.Value == null)
                {
                    parentNode.RemoveChild(element);
                    parentNode.AppendChild(replacementElement);
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Public constructor.
        /// </summary>
        public Encryptor()
        {
            // FIXME: AAA - need support for key and salt changing. What's best interface?
            byte[] salt = Esapi.SecurityConfiguration().MasterSalt;
            string pass = Esapi.SecurityConfiguration().MasterPassword;

            // setup algorithms
            encryptAlgorithm   = Esapi.SecurityConfiguration().EncryptionAlgorithm;
            signatureAlgorithm = Esapi.SecurityConfiguration().DigitalSignatureAlgorithm;
            randomAlgorithm    = Esapi.SecurityConfiguration().RandomAlgorithm;
            hashAlgorithm      = Esapi.SecurityConfiguration().HashAlgorithm;

            try
            {
                // Set up encryption and decryption
                SymmetricAlgorithm symmetricAlgorithm = SymmetricAlgorithm.Create(encryptAlgorithm);
                symmetricAlgorithm.GenerateIV();
                iv = symmetricAlgorithm.IV;
                symmetricAlgorithm.Padding = PaddingMode.PKCS7;

                PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(pass, salt);
                // FIXME: We are using SHA1 hardcoded here, because for some reason CryptDeriveKey doesn't
                // like other hash algorithms. Also, it appears to not like Rijndael as a encryption algorithm.
                secretKey = passwordDeriveBytes.CryptDeriveKey(encryptAlgorithm, "SHA1", symmetricAlgorithm.KeySize, iv);
                encoding  = Esapi.SecurityConfiguration().CharacterEncoding;

                // 13 is the code for DSA
                asymmetricKeyPair = new CspParameters(13);

                // The asymmetric key will be stored in the key container using the name ESAPI.
                asymmetricKeyPair.KeyContainerName = "ESAPI";
                // Set up signing keypair using the master password and salt
                // FIXME: Enhance - make DSA configurable

                RandomNumberGenerator randomNumberGenerator = RNGCryptoServiceProvider.Create(randomAlgorithm);
            }
            catch (Exception e)
            {
                // can't throw this exception in initializer, but this will log it
                new EncryptionException("Encryption failure", "Error creating Encryptor", e);
            }
        }
コード例 #31
0
        public static byte[] TRIPLEDESEncrypt(string Data, string Password, byte[] Key, byte[] IV)
        {
            try
            {
                var pdb = new PasswordDeriveBytes(Password, Key);
                Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, IV);
                //Key = pdb.GetBytes(Key.Length);

                // Create a MemoryStream.
                var mStream = new MemoryStream();

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

                // Convert the passed string to a byte array.
                var toEncrypt = new UnicodeEncoding().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.
                var 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);
            }
        }
コード例 #32
0
ファイル: Form1.cs プロジェクト: korner11/upbz2
        public byte[] generateKey(string key)
        {
            byte[] pwd = Encoding.ASCII.GetBytes(key);

            byte[] salt = CreateRandomSalt(7);

            // Create a TripleDESCryptoServiceProvider object.
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            try
            {
                Console.WriteLine("Creating a key with PasswordDeriveBytes...");

                // Create a PasswordDeriveBytes object and then create
                // a TripleDES key from the password and salt.
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);


                // Create the key and set it to the Key property
                // of the TripleDESCryptoServiceProvider object.

                tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);


                Console.WriteLine("Operation complete.");
                return(tdes.Key);
            }
            catch (Exception e)
            {
                MessageBox.Show("ERROR " + e.Message);
                return(null);
            }
            finally
            {
                // Clear the buffers
                ClearBytes(pwd);
                ClearBytes(salt);

                // Clear the key.
                tdes.Clear();
            }
        }
コード例 #33
0
        // Get the encryption key to use to protect memory for a scope.
        private static byte[] GetScopeKey(MemoryProtectionScope scope, byte[] salt)
        {
            String key;
            PasswordDeriveBytes derive;

            if (scope == MemoryProtectionScope.SameLogon)
            {
                key = Environment.UserName;
            }
            else
            {
                key = Environment.UserName + "/" + Environment.MachineName;
            }
            if (salt == null)
            {
                salt = new byte [16];
            }
            derive = new PasswordDeriveBytes(key, salt);
            return(derive.CryptDeriveKey("Rijndael", "SHA1", 16, null));
        }
コード例 #34
0
 private static string Encrypt(string strText)
 {
     string key = "&%#@?,:*";
     TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
     des.IV = new byte[8];
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, new byte[-1 + 1]);
     des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
     MemoryStream ms = new MemoryStream((strText.Length * 2) - 1);
     CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     byte[] plainBytes = Encoding.UTF8.GetBytes(strText);
     encStream.Write(plainBytes, 0, plainBytes.Length);
     encStream.FlushFinalBlock();
     byte[] encryptedBytes = new byte[(int)ms.Length - 1 + 1];
     ms.Position = 0;
     ms.Read(encryptedBytes, 0, (int)ms.Length);
     encStream.Close();
     return Convert.ToBase64String(encryptedBytes);
 }
コード例 #35
0
        private static byte[] TestKnownValue_CryptDeriveKey(HashAlgorithmName hashName, string password, string alg, int keySize, byte[] salt, byte[] expected)
        {
            byte[] output;
            byte[] iv = new byte[8];

            using (var deriveBytes = new PasswordDeriveBytes(password, salt))
            {
                output = deriveBytes.CryptDeriveKey(alg, hashName.Name, keySize, iv);
            }

            Assert.Equal(expected, output);

            // For these tests, the returned IV is always zero
            Assert.Equal(new byte[8], iv);

            return output;
        }
コード例 #36
0
 public static void CryptDeriveKey_Invalid_IV()
 {
     using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
     {
         Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, null));
         Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, new byte[1]));
     }
 }
コード例 #37
0
 public static void CryptDeriveKey_Invalid_HashAlgorithm()
 {
     using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
     {
         Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "BADALG", 128, s_testSalt));
     }
 }
コード例 #38
0
 public static void CryptDeriveKey_Invalid_KeyLength()
 {
     using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
     {
         Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 127, s_testSalt));
         Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 129, s_testSalt));
     }
 }
コード例 #39
0
	/// <summary>
	///		Derive key, null IV
	/// </summary>
	private static void DeriveKeyNullIv()
	{
		string password = "******";
		byte[] salt = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };

		PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt);
		pdb.CryptDeriveKey("RC2", "MD5", 21, null);
		return;
	}
コード例 #40
0
	public static Boolean TestKnown()
	{
		Boolean bRes = true;
		Byte[] IV = new Byte[8];
		Byte[] PlainText = {0,1,2,3,4,5,6,7};
		Byte[] KnownVector = {0x7A, 0x50, 0x39, 0x82, 0xB5, 0x0E, 0xB0, 0x0D, 0x1F, 0x37, 0x9D, 0xC8, 0x36, 0x09, 0xD3, 0xFF};

		PasswordDeriveBytes pdb = new PasswordDeriveBytes("simplepassword", null);
		Byte[] the_key = pdb.CryptDeriveKey("RC2", "MD5", 40, IV);
		
		RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
        ICryptoTransform sse = rc2.CreateEncryptor(the_key, IV);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] ciphertext = ms.ToArray();
        cs.Close();

		Console.WriteLine("--- Cipher Text : ----");
		PrintByteArray(ciphertext);
		Console.WriteLine("--- Known vector : ----");
		PrintByteArray(KnownVector);
		
		if(!Compare(ciphertext, KnownVector)) {
			Console.WriteLine("Known and calculated values differ!");
			bRes = false;
		}

		return bRes;
	}