字符串使用密码c#Metro Style加密/解密

我想用密码加密和解密字符串。 我使用C#和WinRT(MetroStyle)。 有人加密/解密吗?

Metro中不存在正常的.Net System.Security.Cryptography命名空间。 您可以在Windows.Security.Cryptography.Core命名空间中使用CryptographicEngine类。

如果仅validation/validation密码,请不要对其进行加密。 相反,请使用以下内容:

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

提供密码时,使用相同的salt运行相同的进程并比较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!" 

与任何加密一样,请确保妥善保护您的密钥并遵循最佳做法。 链接的文档还提供了示例。