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



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

正常。Net系统。安全Metro中不存在加密命名空间。您可以在Windows中使用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();

当提供密码时,使用相同的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!"

与任何密码学一样,请确保适当地保护您的密钥,并遵循最佳实践。链接的文档还提供了示例。

最新更新