Created
February 14, 2010 11:35
-
-
Save hibri/303962 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Security.Cryptography; | |
using System.Text; | |
using System.Xml; | |
using System.Xml.Serialization; | |
namespace ClassLibrary1 | |
{ | |
public class SignedXmlSerializer<T> : XmlSerializer where T : Signable | |
{ | |
private readonly HashAlgorithm _hashAlgorithm; | |
public SignedXmlSerializer(HashAlgorithm hashAlgorithm) : base(typeof (T)) { | |
_hashAlgorithm = hashAlgorithm; | |
} | |
public void Serialize(T o, XmlTextWriter writer) { | |
o.Nonce = GenerateNonce(); | |
StringBuilder stringBuilder = GetXMLToSign(o); | |
string hmac = GetSignature(stringBuilder); | |
o.HMAC = hmac; | |
Serialize(writer, o); | |
} | |
private string GetSignature(StringBuilder stringBuilder) { | |
return ComputeHash(_hashAlgorithm, stringBuilder.ToString()); | |
} | |
private StringBuilder GetXMLToSign<T>(T o) { | |
StringBuilder stringBuilder = new StringBuilder(); | |
StringWriter stringWriter = new StringWriter(stringBuilder); | |
Serialize(new XmlTextWriter(stringWriter), o); | |
return stringBuilder; | |
} | |
private static string GenerateNonce() { | |
byte[] data = Encoding.ASCII.GetBytes(new Random().Next(123400, 9999999).ToString()); | |
return Convert.ToBase64String(data); | |
} | |
private static string ComputeHash(HashAlgorithm hashAlgorithm, string data) { | |
if (hashAlgorithm == null) { | |
throw new ArgumentNullException("hashAlgorithm"); | |
} | |
if (string.IsNullOrEmpty(data)) { | |
throw new ArgumentNullException("data"); | |
} | |
byte[] dataBuffer = Encoding.ASCII.GetBytes(data); | |
byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer); | |
return Convert.ToBase64String(hashBytes); | |
} | |
} | |
public abstract class Signable | |
{ | |
[XmlElement("nonce")] | |
public string Nonce { get; set; } | |
[XmlElement("hmac")] | |
public string HMAC { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment