我正在实现银行的 API,他们需要提供安全令牌。在每条soap消息的标题中,都有如下内容:
<soapenv:Header>
<tpw:BinarySecurityToken ValueType="MAC" Id="DesMacToken" EncodingType="Base64" Value="**xvz**"/>
</soapenv:Header>
根据他们的文档,我需要在每条消息的正文上生成一个 8 字节的 MAC 值。MAC由CBC-MAC算法生成,DES作为分组密码。每个消息的soapenv:Body标签的内容被用作MAC计算的数据。
所以我的问题是如何让 WCF 做到这一点?我将以下代码放在一起创建 MAC 值,但不确定如何将其放入每条消息的标题中。
private string GenerateMAC(string SoapXML)
{
ASCIIEncoding encoding = new ASCIIEncoding();
//Convert from Hex to Bin
byte[] Key = StringToByteArray(HexKey);
//Convert String to Bytes
byte[] XML = encoding.GetBytes(SoapXML);
//Perform the Mac goodies
MACTripleDES DesMac = new MACTripleDES(Key);
byte[] Mac = DesMac.ComputeHash(XML);
//Base64 the Mac
string Base64Mac = Convert.ToBase64String(Mac);
return Base64Mac;
}
public static byte[] StringToByteArray(string Hex)
{
if (Hex.Length % 2 != 0)
{
throw new ArgumentException();
}
byte[] HexAsBin = new byte[Hex.Length / 2];
for (int index = 0; index < HexAsBin.Length; index++)
{
string bytevalue = Hex.Substring(index * 2, 2);
HexAsBin[index] = Convert.ToByte(bytevalue, 16);
}
return HexAsBin;
}
任何帮助将不胜感激。
更多信息: 银行提供了一个 WSDL,我将其用作服务参考。发送的响应示例:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="LogonRequest", WrapperNamespace="http://webservice.com", IsWrapped=true)]
public partial class LogonRequest {
[System.ServiceModel.MessageHeaderAttribute(Namespace="http://webservice.com")]
public DataAccess.BankService.BinarySecurityToken BinarySecurityToken;
BinarySecurityToken(位于标头中)如下所示:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.233")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://webservice.com")]
public partial class BinarySecurityToken : object, System.ComponentModel.INotifyPropertyChanged {
private string valueTypeField;
private string idField;
private string encodingTypeField;
private string valueField;
public BinarySecurityToken() {
this.valueTypeField = "MAC";
this.idField = "DesMacToken";
this.encodingTypeField = "Base64";
}