3

パスワードを使用して文字列を暗号化および復号化したいのですが。私はC#とWinRT(MetroStyle)を使用しています。誰かに暗号化/復号化のクラスがありますか?

4

1 に答える 1

11

通常の .Net System.Security.Cryptography 名前空間は Metro には存在しません。代わりに、 Windows.Security.Cryptography.Core名前空間のCryptographicEngineクラスを使用し ます。

パスワードが検証/認証されるだけの場合は、暗号化しないでください。代わりに、次を使用します。

using Windows.Security.Cryptography.Core;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;

...
// Use Password Based Key Derivation Function 2 (PBKDF2 or RFC2898)
KeyDerivationAlgorithmProvider pbkdf2 = 
    KeyDerivationAlgorithmProvider.OpenAlgorithm(
        KeyDerivationAlgorithmNames.Pbkdf2Sha256);

// Do not store passwords in strings if you can avoid them. The
// password may be retained in memory until it is garbage collected.
// Crashing the application and looking at the memory dump may 
// reveal it.
IBuffer passwordBuffer = 
     CryptographicBuffer.ConvertStringToBinary("password", 
         BinaryStringEncoding.Utf8);
CryptographicKey key = pbkdf2.CreateKey(passwordBuffer);

// Use random salt and 10,000 iterations. Store the salt along with 
// the derviedBytes (see below).
IBuffer salt = CryptographicBuffer.GenerateRandom(32);
KeyDerivationParameters parameters = 
    KeyDerivationParameters.BuildForPbkdf2(salt, 10000);

// Store the returned 32 bytes along with the salt for later verification
byte[] derviedBytes = 
    CryptographicEngine.DeriveKeyMaterial(key, parameters, 32).ToArray();

パスワードが提供されたら、同じソルトを使用して同じプロセスを実行し、derivedBytes を比較します。暗号化キーと同じようにシークレットを保存します。

別のサービスへの接続など、パスワードが使用される場合:

// Use AES, CBC mode with PKCS#7 padding (good default choice)
SymmetricKeyAlgorithmProvider aesCbcPkcs7 = 
    SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

// Create an AES 128-bit (16 byte) key
CryptographicKey key = 
    aesCbcPkcs7.CreateSymmetricKey(CryptographicBuffer.GenerateRandom(16));

// Creata a 16 byte initialization vector
IBuffer iv = CryptographicBuffer.GenerateRandom(aesCbcPkcs7.BlockLength);

// Encrypt the data
byte[] plainText = Encoding.UTF8.GetBytes("Hello, world!"); // Data to encrypt
byte[] cipherText = CryptographicEngine.Encrypt(
    key, plainText.AsBuffer(), iv).ToArray();

// Decrypt the data
string newPlainText = new string(
    Encoding.UTF8.GetChars(CryptographicEngine.Decrypt(
        key, cipherText.AsBuffer(), iv).ToArray()));

// newPlainText contains "Hello, world!"

他の暗号化と同様に、キーを適切に保護し、ベスト プラクティスに従ってください。リンクされたドキュメントにも例が示されています。

于 2012-09-09T11:08:28.527 に答える