当前位置: 首页>>代码示例>>C#>>正文


C# Cryptography.Rfc2898DeriveBytes类代码示例

本文整理汇总了C#中System.Security.Cryptography.Rfc2898DeriveBytes的典型用法代码示例。如果您正苦于以下问题:C# Rfc2898DeriveBytes类的具体用法?C# Rfc2898DeriveBytes怎么用?C# Rfc2898DeriveBytes使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Rfc2898DeriveBytes类属于System.Security.Cryptography命名空间,在下文中一共展示了Rfc2898DeriveBytes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Decrypt

        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
开发者ID:oozcitak,项目名称:RebarPos,代码行数:35,代码来源:Crypto.cs

示例2: Descriptografar

        public static string Descriptografar(string codigo)
        {
            try
            {
                if (string.IsNullOrEmpty(codigo))
                    return String.Empty;
                string retorno;
                var chave = new Rfc2898DeriveBytes(Segredo, Complemento);

                var algoritimo = new RijndaelManaged();
                algoritimo.Key = chave.GetBytes(algoritimo.KeySize / 8);
                algoritimo.IV = chave.GetBytes(algoritimo.BlockSize / 8);

                var descriptografor = algoritimo.CreateDecryptor(algoritimo.Key, algoritimo.IV);
                var bytes = Convert.FromBase64String(codigo);

                using (var memoryStream = new MemoryStream(bytes))
                using (var cryptoStream = new CryptoStream(memoryStream, descriptografor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                    retorno = streamReader.ReadToEnd();

                algoritimo.Clear();

                return retorno;
            }
            catch (Exception)
            {
                return "DEU PAU";
            }
        }
开发者ID:vmussak,项目名称:Criptografia,代码行数:30,代码来源:Criptografia.cs

示例3: Encrypt

 public static string Encrypt(string plainText, string passPhrase)
 {
     // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
     // so that the same Salt and IV values can be used when decrypting.
     var saltStringBytes = Generate256BitsOfRandomEntropy();
     var ivStringBytes = Generate256BitsOfRandomEntropy();
     var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
     var keyBytes = password.GetBytes(Keysize / 8);
     using (var symmetricKey = new RijndaelManaged())
     {
         symmetricKey.BlockSize = 256;
         symmetricKey.Mode = CipherMode.CBC;
         symmetricKey.Padding = PaddingMode.PKCS7;
         using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
         {
             using (var memoryStream = new MemoryStream())
             {
                 using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                 {
                     cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                     cryptoStream.FlushFinalBlock();
                     // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                     var cipherTextBytes = saltStringBytes;
                     cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                     cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                     memoryStream.Close();
                     cryptoStream.Close();
                     return Convert.ToBase64String(cipherTextBytes);
                 }
             }
         }
     }
 }
开发者ID:oozcitak,项目名称:RebarPos,代码行数:34,代码来源:Crypto.cs

示例4: Criptografar

        public static string Criptografar(string texto)
        {
            if(string.IsNullOrEmpty(texto))
                return String.Empty;

            string outStr;

            RijndaelManaged aesAlg = null;
            try
            {
                var key = new Rfc2898DeriveBytes(Segredo, Complemento);
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(texto);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return outStr;
        }
开发者ID:vmussak,项目名称:Criptografia,代码行数:34,代码来源:Criptografia.cs

示例5: Encrypt

 public static string Encrypt(string clearText)
 {
     byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
     Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt);
     byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Convert.ToBase64String(encryptedData);
 }
开发者ID:jmibarrad,项目名称:MailgunHW,代码行数:7,代码来源:AccountSeeder.cs

示例6: AES_Encrypt

        public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
        {
            byte[] encryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }
开发者ID:amitabhasaha1987,项目名称:teamwork,代码行数:32,代码来源:AES.cs

示例7: Encrypt

        public static string Encrypt(string plainText, string key)
        {
            if(string.IsNullOrEmpty(plainText)) {
                throw new ArgumentNullException("plainText");
            }

            if(string.IsNullOrEmpty(key)) {
                throw new ArgumentNullException("key");
            }

            using(var keyDerivationFunction = new Rfc2898DeriveBytes(key, SALT_SIZE)) {
                byte[] saltBytes = keyDerivationFunction.Salt;
                byte[] keyBytes = keyDerivationFunction.GetBytes(32);
                byte[] ivBytes = keyDerivationFunction.GetBytes(16);

                using(var aesManaged = new AesManaged()) {
                    aesManaged.KeySize = 256;

                    using(var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes)) {
                        MemoryStream memoryStream = null;
                        CryptoStream cryptoStream = null;

                        return WriteMemoryStream(plainText, ref saltBytes, encryptor, ref memoryStream, ref cryptoStream);
                    }
                }
            }
        }
开发者ID:2nfro,项目名称:dotNet,代码行数:27,代码来源:AES.cs

示例8: DecryptFile

        public void DecryptFile(string sourceFilename, string destinationFilename, string password)
        {
            AesManaged aes = new AesManaged();
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
            aes.Key = key.GetBytes(aes.KeySize / 8);
            aes.IV = key.GetBytes(aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;
            ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);

            using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
                {
                    try
                    {
                        using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            source.CopyTo(cryptoStream);
                        }
                    }
                    catch (CryptographicException exception)
                    {
                        if (exception.Message == "Padding is invalid and cannot be removed.")
                            throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
                        else
                            throw;
                    }
                }
            }
        }
开发者ID:tejashwikalptaru,项目名称:csharp-clamAV-antivirus,代码行数:33,代码来源:Quarantine.cs

示例9: EncryptAndUpload

        public static void EncryptAndUpload(string file, string awsPath, string key)
        {
            if (bool.Parse(ConfigurationManager.AppSettings["ManagedEncryption"]))
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, appKey);
                using (var aes = new AesCryptoServiceProvider())
                {
                    aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);
                    aes.IV = deriveBytes.GetBytes(aes.BlockSize / 8);
                    using (var temp = new FileStream(file + "_encrypted", FileMode.Create))
                    {
                        using (var stream = new CryptoStream(new FileStream(file, FileMode.Open), aes.CreateEncryptor(), CryptoStreamMode.Read))
                        {
                            stream.CopyTo(temp);
                        }
                    }

                    UploadFile(file + "_encrypted", awsPath);

                    File.Delete(file + "_encrypted");
                }
            }
            else
                UploadFile(file, awsPath);
        }
开发者ID:stormbreakerbg,项目名称:SecureShare,代码行数:25,代码来源:AWSHelper.cs

示例10: Encrypt

 /// <summary>
 /// Encrypts the specified string.
 /// </summary>
 /// <param name="clearText">The string to be encrypted.</param>
 /// <param name="key">The key.</param>
 /// <returns></returns>
 public static string Encrypt(this string clearText, string key)
 {
     byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
     Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
     byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Convert.ToBase64String(encryptedData);
 }
开发者ID:joelkarr,项目名称:ENGworks,代码行数:13,代码来源:StringExtensions.cs

示例11: HashTextWithSalt

        public static string HashTextWithSalt(string text, string salt)
        {
            Rfc2898DeriveBytes hasher = new Rfc2898DeriveBytes(text, Convert.FromBase64String(salt));
            hasher.IterationCount = HashIterations;

            return Convert.ToBase64String(hasher.GetBytes(HashByteSize));
        }
开发者ID:aladd04,项目名称:PersonalWebsite,代码行数:7,代码来源:CryptoFactory.cs

示例12: CheckEqual

        /// <summary>
        /// 检查
        /// </summary>
        /// <param name="pass"></param>
        /// <param name="hashedPass"></param>
        /// <returns></returns>
        public static bool CheckEqual(string pass, string hashedPass)
        {
            /* Extract the bytes */
            byte[] hashBytes;
            try
            {
                hashBytes = Convert.FromBase64String(hashedPass);
            }
            catch (Exception ex)
            {
                var logger = LoggerManager.Current();
                logger.Error(ex);

                return false;
            }
            /* Get the salt */
            var salt = new byte[16];
            Array.Copy(hashBytes, 0, salt, 0, 16);
            /* Compute the hash on the password the user entered */
            var pbkdf2 = new Rfc2898DeriveBytes(pass, salt, 10000);
            var hash = pbkdf2.GetBytes(20);
            /* Compare the results */
            for (var i = 0; i < 20; i++)
            {
                if (hashBytes[i + 16] != hash[i])
                    return false;
            }

            return true;
        }
开发者ID:ngnono,项目名称:NGnono.Framework,代码行数:36,代码来源:PwdSecurityHelper.cs

示例13: GenerateKeys

 public static byte[][] GenerateKeys(byte[] password, byte[] nonce)
 {
     byte[][] array = new byte[4][];
     byte[][] array2 = array;
     byte[] array3 = new byte[]
     {
         1,
         2,
         3,
         4
     };
     byte[] array4 = new byte[nonce.Length + 1];
     for (int i = 0; i < nonce.Length; i++)
     {
         array4[i] = nonce[i];
     }
     nonce = array4;
     for (int j = 0; j < array2.Length; j++)
     {
         nonce[nonce.Length - 1] = array3[j];
         Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, nonce, 2);
         array2[j] = rfc2898DeriveBytes.GetBytes(20);
     }
     return array2;
 }
开发者ID:elloko75,项目名称:Chat-API-NET,代码行数:25,代码来源:KeyStream.cs

示例14: Encrypt

        public static string Encrypt(string plainText, string key)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, _saltSize))
            {
                var saltBytes = keyDerivationFunction.Salt;
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                using (var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    using (var streamWriter = new StreamWriter(cryptoStream))
                        streamWriter.Write(plainText);

                    var cipherTextBytes = memoryStream.ToArray();
                    Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length);
                    Array.Copy(cipherTextBytes, 0, saltBytes, _saltSize, cipherTextBytes.Length);

                    return Convert.ToBase64String(saltBytes);
                }
            }
        }
开发者ID:vfrz,项目名称:ISNProjects,代码行数:29,代码来源:AES.cs

示例15: ComparePasswords

        public static bool ComparePasswords(string PasswordHash, string Password)
        {
            if (string.IsNullOrEmpty(PasswordHash) || string.IsNullOrEmpty(Password)) return false;
            if (PasswordHash.Length < 40 || Password.Length < 1) return false;

            byte[] salt = new byte[20];
            byte[] key = new byte[20];
            byte[] hash = Convert.FromBase64String(PasswordHash);

            try
            {
                Buffer.BlockCopy(hash, 0, salt, 0, 20);
                Buffer.BlockCopy(hash, 20, key, 0, 20);

                using (var hashBytes = new Rfc2898DeriveBytes(Password, salt, 10000))
                {
                    byte[] newKey = hashBytes.GetBytes(20);

                    if (newKey != null)
                        if (newKey.SequenceEqual(key))
                            return true;
                }
                return false;
            }
            finally
            {
                if (salt != null)
                    Array.Clear(salt, 0, salt.Length);
                if (key != null)
                    Array.Clear(key, 0, key.Length);
                if (hash != null)
                    Array.Clear(hash, 0, hash.Length);
            }
        }
开发者ID:miaozhendaoren,项目名称:DCFIv4,代码行数:34,代码来源:UserLogic.cs


注:本文中的System.Security.Cryptography.Rfc2898DeriveBytes类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。