1

次の方法を使用して、データをデータベースに保存する前に暗号化しています。データは取得時に XML に変換され、データ アクセス層に渡されて、既知のビジネス エンティティ オブジェクトに逆シリアル化されます。

問題は、エンコードが原因でデータに 16 進文字が含まれているため、xml が無効な xml ドキュメントになり、逆シリアル化できないことです。

この問題を解決するにはどうすればよいですか?

public static string EncryptStringAES(string plainText, string sharedSecret)
{
    if (string.IsNullOrEmpty(plainText))
        throw new ArgumentNullException("plainText");
    if (string.IsNullOrEmpty(sharedSecret))
        throw new ArgumentNullException("sharedSecret");

    string outStr = null;                       // Encrypted string to return
    RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

    try
    {
        // generate the key from the shared secret and the salt
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

        // Create a RijndaelManaged object
        aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

        // Create a decryptor to perform the stream transform.
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        // Create the streams used for encryption.
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            // prepend the IV
            msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
            msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    //Write all data to the stream.
                    swEncrypt.Write(plainText);
                }
            }
            outStr = Convert.ToBase64String(msEncrypt.ToArray());
        }
    }
    finally
    {
        // Clear the RijndaelManaged object.
        if (aesAlg != null)
            aesAlg.Clear();
    }

    // Return the encrypted bytes from the memory stream.
    return outStr;
}
4

1 に答える 1

-1

私は通常、HttpUtility.HtmlEncodeを使用して XML の値をエスケープします。

于 2013-04-08T02:11:59.717 に答える