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 アルゴリズムの使用に置き換えられました。
- パスワードの派生は、以前はまったくソルト化されていませんでしたが、現在は適切にソルト化されています (別のばかげたバグがつぶされました)。