3

ファイルからテキストを読み取り、暗号化して文字列形式で関数に渡そうとしています。後で私もそれを解読したいと思います。

次のことを試しましたが、暗号化は行われませんでした。簡単な暗号化アルゴリズムを提案できる人はいますか?

fileStream = store.OpenFile(strFilePath, FileMode.Open, FileAccess.Read);
strEncryptedFileStream = Encoding.Unicode.GetBytes(fileStream.ToString()).ToString();
4

3 に答える 3

15

AESを使用します。これはヘルパークラスです。「単純な」暗号化、つまり簡単に破られる暗号化を使用しても意味がありません。人々がそれを破ることができるようにしたいか、そうでないかのどちらかです。よく知られており、テスト済みの暗号化標準を選択してください。

必要に応じて以下の例を変更できる場合があります。

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;

namespace Common.Cryptography
{
    /// <summary>
    /// AES is a symmetric 256-bit encryption algorthm.
    /// Read more: http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
    /// </summary>
    public static class AES
    {
        private const string _SALT = "g46dzQ80";
        private const string _INITVECTOR = "OFRna74m*aze01xY";

        private static byte[] _saltBytes;
        private static byte[] _initVectorBytes;

        static AES()
        {
            _saltBytes = Encoding.UTF8.GetBytes(_SALT);
            _initVectorBytes = Encoding.UTF8.GetBytes(_INITVECTOR);
        }


        /// <summary>
        /// Encrypts a string with AES
        /// </summary>
        /// <param name="plainText">Text to be encrypted</param>
        /// <param name="password">Password to encrypt with</param>   
        /// <param name="salt">Salt to encrypt with</param>    
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param>    
        /// <returns>An encrypted string</returns>        
        public static string Encrypt(string plainText, string password, string salt = null, string initialVector = null)
        {
            return Convert.ToBase64String(EncryptToBytes(plainText, password, salt, initialVector));
        }

        /// <summary>
        /// Encrypts a string with AES
        /// </summary>
        /// <param name="plainText">Text to be encrypted</param>
        /// <param name="password">Password to encrypt with</param>   
        /// <param name="salt">Salt to encrypt with</param>    
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param>    
        /// <returns>An encrypted string</returns>        
        public static byte[] EncryptToBytes(string plainText, string password, string salt = null, string initialVector = null)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            return EncryptToBytes(plainTextBytes, password, salt, initialVector);
        }

        /// <summary>
        /// Encrypts a string with AES
        /// </summary>
        /// <param name="plainTextBytes">Bytes to be encrypted</param>
        /// <param name="password">Password to encrypt with</param>   
        /// <param name="salt">Salt to encrypt with</param>    
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param>    
        /// <returns>An encrypted string</returns>        
        public static byte[] EncryptToBytes(byte[] plainTextBytes, string password, string salt = null, string initialVector = null)
        {
            int keySize = 256;

            byte[] initialVectorBytes = string.IsNullOrEmpty(initialVector) ? _initVectorBytes : Encoding.UTF8.GetBytes(initialVector);
            byte[] saltValueBytes = string.IsNullOrEmpty(salt) ? _saltBytes : Encoding.UTF8.GetBytes(salt);
            byte[] keyBytes = new Rfc2898DeriveBytes(password, saltValueBytes).GetBytes(keySize / 8);

            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                symmetricKey.Mode = CipherMode.CBC;

                using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes))
                {
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();

                            return memStream.ToArray();
                        }
                    }
                }
            }
        }

        /// <summary>  
        /// Decrypts an AES-encrypted string. 
        /// </summary>  
        /// <param name="cipherText">Text to be decrypted</param> 
        /// <param name="password">Password to decrypt with</param> 
        /// <param name="salt">Salt to decrypt with</param> 
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param> 
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string cipherText, string password, string salt = null, string initialVector = null)
        {
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText.Replace(' ','+'));
            return Decrypt(cipherTextBytes, password, salt, initialVector).TrimEnd('\0');
        }

        /// <summary>  
        /// Decrypts an AES-encrypted string. 
        /// </summary>  
        /// <param name="cipherText">Text to be decrypted</param> 
        /// <param name="password">Password to decrypt with</param> 
        /// <param name="salt">Salt to decrypt with</param> 
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param> 
        /// <returns>A decrypted string</returns>
        public static string Decrypt(byte[] cipherTextBytes, string password, string salt = null, string initialVector = null)
        {
            int keySize = 256;

            byte[] initialVectorBytes = string.IsNullOrEmpty(initialVector) ? _initVectorBytes : Encoding.UTF8.GetBytes(initialVector);
            byte[] saltValueBytes = string.IsNullOrEmpty(salt) ? _saltBytes : Encoding.UTF8.GetBytes(salt);
            byte[] keyBytes = new Rfc2898DeriveBytes(password, saltValueBytes).GetBytes(keySize / 8);
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                symmetricKey.Mode = CipherMode.CBC;

                using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
                {
                    using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                        {
                            int byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

                            return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
                        }
                    }
                }
            }
        }
    }
}
于 2013-07-09T13:45:44.880 に答える
1

コード内で暗号化を行うものはありません。Unicode に変換しているだけです。

C# での暗号化の良い例を示すこの質問を見ることができます。

于 2013-07-09T13:45:53.660 に答える
0

メソッド Enconding は、テキスト エンコーディング (UTF-8、ANSI など...) に関するもので、暗号化アルゴリズムを使用する必要があります。これを行うにはいくつかの方法があります。簡単な例では、XOR 暗号化を使用します。

これを参照してください:

string XorEncryptDecryptText(string stringText, string stringKey){
// Variable that receives the result of processode encryption.
string stringNewText = &quot;&quot;;
// First we take the difference in size of the two strings.
int diff = (stringText.Length - stringKey.Length);
// If the size difference that we put stringKey with the same size as the XOR stringText that no errors occur.
if (diff &gt; 0){
    // We calculate the rest and the amount of times we repeat the stringKey to equal sizes.
    int cont = (int)diff / stringKey.Length;
    int resto = diff % stringKey.Length;
    string stringKeyAux = stringKey;
    // At this point the stringText concatenate the stringKey to be equal sizes.
    for (int i = 0; i &lt; cont; i++){
        stringKeyAux += stringKey;
    }

    for (int i = 0; (i &lt; resto); i++){
        stringKeyAux += stringKey[i];
    }
    stringKey = stringKeyAux;
}
// At this point piece of code is done the process of XOR.
for (int i = 0; i &lt; stringText.Length; i++){
    int charValue = Convert.ToInt32(stringText[i]);
    int charKey = Convert.ToInt32(stringKey[i]);
    charValue ^= charKey;
    stringNewText += char.ConvertFromUtf32(charValue);
}
return stringNewText;}

string XOREncriptDecriptFile(string FileName, string stringKey){
string stringAux = System.IO.File.ReadAllLines(FileName);
return XorEncryptDecryptText(stringAux, stringKey);}

このコードはhttp://julioborges.p.ht/?p=769に基づいています。

セキュリティを強化するには、smdragerの回答を使用します

于 2013-07-09T14:01:42.747 に答える