404

C# で以下を満たす最も近代的な (最良の) 方法は何ですか?

string encryptedString = SomeStaticClass.Encrypt(sourceString);

string decryptedString = SomeStaticClass.Decrypt(encryptedString);

しかし、ソルト、キー、バイト[]などをいじるなど、最小限の手間がかかります。

私が見つけたものにグーグルで混乱していました(同様のSO Qのリストを見ると、これが欺瞞的な質問であることがわかります)。

4

7 に答える 7

878

2015 年 12 月 23 日更新: この回答には多くの賛成票が寄せられているようですので、愚かなバグを修正し、コメントやフィードバックに基づいてコードを一般的に改善するために更新しました。具体的な改善点のリストについては、投稿の最後を参照してください。

他の人が言ったように、暗号化は単純ではないため、「独自の」暗号化アルゴリズムを作成することは避けるのが最善です。

RijndaelManagedただし、組み込みの暗号化クラスなどの周りに「独自の」ラッパー クラスを配置することはできます。

Rijndael は現在のAdvanced Encryption Standardのアルゴリズム名であるため、「ベスト プラクティス」と見なされるアルゴリズムを使用していることは確かです。

このRijndaelManagedクラスでは、通常、バイト配列、ソルト、キー、初期化ベクトルなどを「いじる」必要がありますが、これはまさに「ラッパー」クラス内で抽象化できる詳細の一種です。

次のクラスは、あなたが求めていることを正確に実行するために少し前に書いたものです。文字列ベースのプレーンテキストを文字列ベースのパスワードで暗号化できるようにする単純な単一のメソッド呼び出しで、結果として暗号化された文字列も生成されます。文字列として表されます。もちろん、暗号化された文字列を同じパスワードで解読する同等の方法があります。

毎回まったく同じソルトと IV 値を使用していたこのコードの最初のバージョンとは異なり、この新しいバージョンでは毎回ランダムなソルトと IV 値が生成されます。ソルトと IV は特定の文字列の暗号化と復号化の間で同じでなければならないため、ソルトと IV は暗号化時に暗号文の先頭に追加され、復号化を実行するために再び抽出されます。この結果、まったく同じ平文をまったく同じパスワードで暗号化すると、毎回まったく異なる暗号文が得られます。

これを使用することの「強み」は、RijndaelManagedクラスを使用して暗号化を実行することと、名前空間のRfc2898DeriveBytes関数を使用することです。この関数は、文字列に基づいてSystem.Security.Cryptography標準的で安全なアルゴリズム (具体的にはPBKDF2 ) を使用して暗号化キーを生成します。あなたが提供するベースのパスワード。(これは、古い PBKDF1 アルゴリズムの最初のバージョンでの使用を改善したものであることに注意してください)。

最後に、これはまだ認証されていない暗号化であることに注意することが重要です。暗号化だけではプライバシーのみが提供されます (つまり、メッセージが第三者に知られません)。一方、認証された暗号化は、プライバシーと信頼性の両方を提供することを目的としています (つまり、受信者はメッセージが送信者によって送信されたことを知っています)。

正確な要件を知らなければ、ここのコードがニーズに対して十分に安全であるかどうかを判断するのは困難ですが、実装の相対的な単純さと「品質」との間のバランスをうまくとることができるように作成されています。たとえば、暗号化された文字列の「受信者」が信頼できる「送信者」から直接文字列を受信して​​いる場合、認証は必要ない場合もあります

より複雑で、認証された暗号化を提供するものが必要な場合は、実装についてこの投稿を確認してください。

コードは次のとおりです。

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

namespace EncryptStringSample
{
    public static class StringCipher
    {
        // This constant is used to determine the keysize of the encryption algorithm in bits.
        // We divide this by 8 within the code below to get the equivalent number of bytes.
        private const int Keysize = 256;

        // This constant determines the number of iterations for the password bytes generation function.
        private const int DerivationIterations = 1000;

        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);
            using (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);
                            }
                        }
                    }
                }
            }
        }

        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();

            using (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);
                            }
                        }
                    }
                }
            }
        }

        private static byte[] Generate256BitsOfRandomEntropy()
        {
            var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with cryptographically secure random bytes.
                rngCsp.GetBytes(randomBytes);
            }
            return randomBytes;
        }
    }
}

上記のクラスは、次のようなコードで非常に簡単に使用できます。

using System;

namespace EncryptStringSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a password to use:");
            string password = Console.ReadLine();
            Console.WriteLine("Please enter a string to encrypt:");
            string plaintext = Console.ReadLine();
            Console.WriteLine("");

            Console.WriteLine("Your encrypted string is:");
            string encryptedstring = StringCipher.Encrypt(plaintext, password);
            Console.WriteLine(encryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Your decrypted string is:");
            string decryptedstring = StringCipher.Decrypt(encryptedstring, password);
            Console.WriteLine(decryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
    }
}

(単純な VS2013 サンプル ソリューション (いくつかの単体テストを含む) をここからダウンロードできます)。

2015 年 12 月 23 日更新 : コードの具体的な改善点のリストは次のとおりです。

  • 暗号化と復号化でエンコーディングが異なる愚かなバグを修正しました。ソルト値と IV 値が生成されるメカニズムが変更されたため、エンコードは不要になりました。
  • salt/IV の変更により、16 文字の文字列を UTF8 でエンコードすると 32 バイトが生成されることを誤って示していた以前のコード コメントは適用できなくなりました (エンコードが不要になったため)。
  • 廃止された PBKDF1 アルゴリズムの使用は、より最新の PBKDF2 アルゴリズムの使用に置き換えられました。
  • パスワードの派生は、以前はまったくソルト化されていませんでしたが、現在は適切にソルト化されています (別のばかげたバグがつぶされました)。
于 2012-04-16T15:24:55.087 に答える
121
using System.IO;
using System.Text;
using System.Security.Cryptography;

public static class EncryptionHelper
{
    public static string Encrypt(string clearText)
    {
        string EncryptionKey = "abc123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
    public static string Decrypt(string cipherText)
    {
        string EncryptionKey = "abc123";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
}
于 2014-12-15T12:44:56.257 に答える
30

このクラスを試してください:

public class DataEncryptor
{
    TripleDESCryptoServiceProvider symm;

    #region Factory
    public DataEncryptor()
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
    }
    public DataEncryptor(TripleDESCryptoServiceProvider keys)
    {
        this.symm = keys;
    }

    public DataEncryptor(byte[] key, byte[] iv)
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
        this.symm.Key = key;
        this.symm.IV = iv;
    }

    #endregion

    #region Properties
    public TripleDESCryptoServiceProvider Algorithm
    {
        get { return symm; }
        set { symm = value; }
    }
    public byte[] Key
    {
        get { return symm.Key; }
        set { symm.Key = value; }
    }
    public byte[] IV
    {
        get { return symm.IV; }
        set { symm.IV = value; }
    }

    #endregion

    #region Crypto

    public byte[] Encrypt(byte[] data) { return Encrypt(data, data.Length); }
    public byte[] Encrypt(byte[] data, int length)
    {
        try
        {
            // Create a MemoryStream.
            var ms = new MemoryStream();

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

            // Write the byte array to the crypto stream and flush it.
            cs.Write(data, 0, length);
            cs.FlushFinalBlock();

            // Get an array of bytes from the 
            // MemoryStream that holds the 
            // encrypted data.
            byte[] ret = ms.ToArray();

            // Close the streams.
            cs.Close();
            ms.Close();

            // Return the encrypted buffer.
            return ret;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string EncryptString(string text)
    {
        return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text)));
    }

    public byte[] Decrypt(byte[] data) { return Decrypt(data, data.Length); }
    public byte[] Decrypt(byte[] data, int length)
    {
        try
        {
            // Create a new MemoryStream using the passed 
            // array of encrypted data.
            MemoryStream ms = new MemoryStream(data);

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cs = new CryptoStream(ms,
                symm.CreateDecryptor(symm.Key, symm.IV),
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] result = new byte[length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            cs.Read(result, 0, result.Length);
            return result;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string DecryptString(string data)
    {
        return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data))).TrimEnd('\0');
    }

    #endregion

}

次のように使用します。

string message="A very secret message here.";
DataEncryptor keys=new DataEncryptor();
string encr=keys.EncryptString(message);

// later
string actual=keys.DecryptString(encr);
于 2012-04-16T15:22:35.460 に答える
19

パスワードをメモリに保存する必要があり、パスワードを暗号化したい場合は、SecureStringを使用する必要があります。

http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx

より一般的な用途では、Advanced Encryption Standard (以前は Rijndael として知られていた) などの FIPS 承認アルゴリズムを使用します。実装例については、このページを参照してください。

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx

于 2012-04-16T03:11:18.957 に答える
12

ProtectedDataユーザーのログオン資格情報を使用してデータを暗号化するクラスを探している可能性があります。

于 2012-04-16T03:04:29.053 に答える
-2

私が見た中で暗号化を行う最も簡単な方法は、RSA を使用することです

MSDN を確認してください: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx

バイトを使用する必要がありますが、結局のところ、暗号化と復号化を理解するのが難しいことを望んでいます。そうしないと、ハッキングが容易になります.

于 2012-04-16T03:06:06.823 に答える