将加密数据写入xml

时间:2016-05-25 11:51:43

标签: c# xml encryption

在我的应用程序中,我有以下代码将某些数据加密为字符串:

org.mule.module.launcher.DeploymentInitException: SAXParseException: cvc-complex
-type.2.4.a: Invalid content was found starting with element 'batch:execute'. On
e of '{"http://www.mulesoft.org/schema/mule/core":abstract-message-processor, "h
ttp://www.mulesoft.org/schema/mule/core":abstract-outbound-endpoint, "http://www
.mulesoft.org/schema/mule/core":abstract-mixed-content-message-processor, "http:
//www.mulesoft.org/schema/mule/core":response}' is expected.
        at org.mule.module.launcher.application.DefaultMuleApplication.init(Defa
ultMuleApplication.java:197) ~[mule-module-launcher-3.7.0.jar:3.7.0]
        at org.mule.module.launcher.artifact.ArtifactWrapper$2.execute(ArtifactW
rapper.java:62) ~[mule-module-launcher-3.7.0.jar:3.7.0]
        at org.mule.module.launcher.artifact.ArtifactWrapper.executeWithinArtifa
ctClassLoader(ArtifactWrapper.java:129) ~[mule-module-launcher-3.7.0.jar:3.7.0]
        at org.mule.module.launcher.artifact.ArtifactWrapper.init(ArtifactWrappe
r.java:57) ~[mule-module-launcher-3.7.0.jar:3.7.0]
        at org.mule.module.launcher.DefaultArtifactDeployer.deploy(DefaultArtifa
ctDeployer.java:25) ~[mule-module-launcher-3.7.0.jar:3.7.0]
        at org.mule.module.launcher.DefaultArchiveDeployer.guardedDeploy(Default
ArchiveDeployer.java:310) ~[mule-module-launcher-3.7.0.jar:3.7.0]

这就像我想要的那样。现在我想将该数据写入xml文件,如:

private string EncryptPermission(User user)
{
    Encoding encoding = Encoding.ASCII;
    Cryptography cryptography = CreateCryptography(user);
    byte[] val = encoding.GetBytes(user.Permission.ToString());
    byte[] encrypted = cryptography.Encrypt(val);
    string result = encoding.GetString(encrypted);
    return result;
}

目前我致电internal void WriteUser(User user) { XElement userElement = new XElement("user", new XAttribute("id", user.UserId.ToString("N")), new XElement("name", user.Username), new XElement("password", user.Password), new XElement("permission", EncryptPermission(user))); XDocument document = GetDocument(); if (document.Root != null) { document.Root.Add(userElement); SaveDocument(document); } } 我得SaveDocument赞:

  

发生了'System.ArgumentException'类型的第一次机会异常   在System.Xml.dll

中      

附加信息:'',十六进制值0x06,是   无效的char。

(翻译自德语)

我该如何解决这个问题?我已经尝试使用ExceptionConverter.ToBase64String(..),但我得到一个例外,即数据太长了。

2 个答案:

答案 0 :(得分:1)

加密产生字节,而不是所有字节都是有效字符,正如XML所预期的那样。你的0x06就是这样的一个。一种可能的解决方案是在写入XML之前将字节转换为Base64。 Base64仅使用有效字符,代价是增加一些大小:它使用四个字符来写三个字节。

查看C#Base64转换方法的Convert类。

答案 1 :(得分:0)

它很可能是字符串中的一个字符,已经破坏了xml。

在节点内的CDATA []标签中添加加密字符串,你应该没问题

What does <![CDATA[]]> in XML mean?

相关问题