编码XML属性中的十六进制字符

本文关键字:十六进制 字符 XML 属性 编码 | 更新日期: 2023-09-27 18:08:02

在将数据存储到数据库之前,我使用以下方法对数据进行加密。数据将在检索时转换为XML,并传递给数据访问层,以反序列化为已知的业务实体对象。

问题是由于编码,数据中有一些十六进制字符,这使得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;
}

编码XML属性中的十六进制字符

我通常使用HttpUtility。