首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rijndael加密问题

Rijndael加密问题
EN

Stack Overflow用户
提问于 2012-07-05 03:16:17
回答 3查看 1.7K关注 0票数 0

我不知道我做错了什么,但我已经试着让这个东西工作了大约4个小时,但我就是不能让它工作…当我尝试解密时,这只会给我一个错误:“请支持正确的密码”。不过,加密似乎运行得很好。

有什么建议吗?:<

代码语言:javascript
复制
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Security;
using AesApp.Rijndael;
using System.Linq;

    internal class FileEncryption
        {
            private static string password = pw;

            internal static void Encrypt(string inputfile, string outputfile)
            {
                byte[] encryptedPassword;

                // Create a new instance of the RijndaelManaged
                // class.  This generates a new key and initialization
                // vector (IV).
                using (var algorithm = new RijndaelManaged())
                {
                    algorithm.KeySize = 256;
                    algorithm.BlockSize = 128;

                    // Encrypt the string to an array of bytes.
                    encryptedPassword = Cryptology.EncryptStringToBytes(
                        password, algorithm.Key, algorithm.IV);
                }

                string chars = encryptedPassword.Aggregate(string.Empty, (current, b) => current + b.ToString());
                Cryptology.EncryptFile(@inputfile, @outputfile, chars);
            }

            internal static void Decrypt(string @inputfile, string @outputfile)
            {
                byte[] encryptedPassword;

                // Create a new instance of the RijndaelManaged
                // class.  This generates a new key and initialization
                // vector (IV).
                using (var algorithm = new RijndaelManaged())
                {
                    algorithm.KeySize = 256;
                    algorithm.BlockSize = 128;

                    // Encrypt the string to an array of bytes.
                    encryptedPassword = Cryptology.EncryptStringToBytes(
                        password, algorithm.Key, algorithm.IV);
                }

                string chars = encryptedPassword.Aggregate(string.Empty, (current, b) => current + b.ToString());
                Cryptology.DecryptFile(@inputfile, @outputfile, chars);
            }
        }

Reindael.cs

代码语言:javascript
复制
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

    namespace AesApp.Rijndael
    {
        internal sealed class Cryptology
        {
            private const string Salt = "d5fg4df5sg4ds5fg45sdfg4";
            private const int SizeOfBuffer = 1024 * 8;

            internal 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("key");
                }

                byte[] encrypted;
                // Create an RijndaelManaged object
                // with the specified key and IV.
                using (var rijAlg = new RijndaelManaged())
                {
                    rijAlg.Key = key;
                    rijAlg.IV = iv;

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

                    // Create the streams used for encryption.
                    using (var msEncrypt = new MemoryStream())
                    {
                        using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        {
                            using (var 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;

            }

            internal 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("key");

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

                // Create an RijndaelManaged object
                // with the specified key and IV.
                using (var rijAlg = new RijndaelManaged())
                {
                    rijAlg.Key = key;
                    rijAlg.IV = iv;

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

                    // Create the streams used for decryption.
                    using (var msDecrypt = new MemoryStream(cipherText))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                plaintext = srDecrypt.ReadToEnd();
                            }
                        }
                    }

                }
                return plaintext;
            }

            internal static void EncryptFile(string inputPath, string outputPath, string password)
            {
                var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
                var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write);

                // Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
                // 1.The block size is set to 128 bits
                // 2.You are not using CFB mode, or if you are the feedback size is also 128 bits

                var algorithm = new RijndaelManaged { KeySize = 256, BlockSize = 128 };
                var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Salt));

                algorithm.Key = key.GetBytes(algorithm.KeySize / 8);
                algorithm.IV = key.GetBytes(algorithm.BlockSize / 8);

                using (var encryptedStream = new CryptoStream(output, algorithm.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    CopyStream(input, encryptedStream);
                }
            }

            internal static void DecryptFile(string inputPath, string outputPath, string password)
            {
                var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
                var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write);

                // Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
                // 1.The block size is set to 128 bits
                // 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
                var algorithm = new RijndaelManaged { KeySize = 256, BlockSize = 128 };
                var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Salt));

                algorithm.Key = key.GetBytes(algorithm.KeySize / 8);
                algorithm.IV = key.GetBytes(algorithm.BlockSize / 8);

                try
                {
                    using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        CopyStream(input, decryptedStream);
                    }
                }
                catch (CryptographicException)
                {
                    throw new InvalidDataException("Please suppy a correct password");
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

            private static void CopyStream(Stream input, Stream output)
            {
                using (output)
                using (input)
                {
                    byte[] buffer = new byte[SizeOfBuffer];
                    int read;
                    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        output.Write(buffer, 0, read);
                    }
                }
            }
        }
    }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-05 04:18:08

不完全确定,但我想我记得有一段时间,连续两次调用加密得到了两种不同的结果。因此,您连续两次调用EncryptStringToBytes可能会给出两个不同的密码:一个用于加密,另一个用于解密……这导致了失败。

我不确定这些加密是不是有必要...如果您有一个硬编码的密码,那么任何人都可以生成其他不依赖于其他内容的字符串。您应该直接使用此密码,而不是第一次加密它:

代码语言:javascript
复制
 internal static void Encrypt(string inputfile, string outputfile)
 {
     Cryptology.EncryptFile(inputfile, outputfile, password);
 }

 internal static void Decrypt(string inputfile, string outputfile)
 {
     Cryptology.DecryptFile(inputfile, outputfile, password);
 }
票数 0
EN

Stack Overflow用户

发布于 2012-07-05 04:22:43

你的加密函数看起来和你的function.

  • Also,完全一样,为什么你要把所有的字节都转换成字符串,然后把它们连接起来?,,
  1. ,你的加密函数看起来和你的解密函数完全一样。此转换不可逆。
票数 0
EN

Stack Overflow用户

发布于 2012-12-19 23:15:17

代码语言:javascript
复制
string chars = encryptedPassword.Aggregate(string.Empty, (current, b) => current + b.ToString());
            Cryptology.EncryptFile(@inputfile, @outputfile, chars);

Aggregate()函数是原因。每次运行应用程序时,它都会创建不同的值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11334399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档