欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > C# >内容正文

C#

C#调用JAVA接口WSSE方式用WebClient方式

发布时间:2025/5/22 C# 61 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C#调用JAVA接口WSSE方式用WebClient方式 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

C#读取JAVA的WSSE接口的调用代码:

用webclient 方式:

/// <summary>/// 调用java cxf ws_security加密的服务wcf客户端对应的加密类/// </summary>public class WssSecurity{private byte[] _nonce ;private string _nonceStr = GetNoce(29);private readonly string _pass; //密码private DateTime _created;public WssSecurity(string p, DateTime t){_pass = p;_created = t;}/// <summary>/// 获取UTC时间/// </summary>/// <returns></returns>public string GetCreatedAsString(){return XmlConvert.ToString(_created.ToUniversalTime(), "yyyy-MM-ddTHH:mm:ss.fffZ");}/// <summary>/// 获取加密的密码/// </summary>/// <returns></returns>public string GetPasswordDigestAsBase64(){//RandomNumberGenerator rndGenerator = new RNGCryptoServiceProvider();//rndGenerator.GetBytes(_nonce);// get other operands to the right format _nonce = Encoding.UTF8.GetBytes(_nonceStr);var newDate = GetCreatedAsString();byte[] time = Encoding.UTF8.GetBytes(newDate);byte[] pwd = Encoding.UTF8.GetBytes(_pass);var operand = new byte[_nonce.Length + time.Length + pwd.Length];Array.Copy(_nonce,operand,_nonce.Length);Array.Copy(time,0,operand,_nonce.Length,time.Length);Array.Copy(pwd,0,operand,_nonce.Length + time.Length,pwd.Length);// create the hashSHA1 sha1 = SHA1.Create();return Convert.ToBase64String(sha1.ComputeHash(operand));}private static String[] chars = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e","f" };public static String GetNoce(int length) {StringBuilder sb = new StringBuilder();Random r=new Random();for(int i = 0; i < length; i++) {sb.Append(chars[r.Next(15)]);}return sb.ToString();}/// <summary>/// 获取Nonce/// </summary>/// <returns></returns>public string GetNonceAsBase64(){return _nonceStr;}}

操作方法

string postString = "{\"devices\":[\"1541351315\"]}";byte[] postData = Encoding.UTF8.GetBytes(postString);var wss = new WssSecurity("137E000470C1E8E2FA4B1348AC5B9D7A", DateTime.Now);WebClient client = new WebClient();client.Headers.Add("Authorization", "WSSE profile=\"UsernameToken\"");client.Headers.Add("X-WSSE","UsernameToken Username=\"ServiceDevices\", PasswordDigest=\"" + wss.GetPasswordDigestAsBase64() + "\", Nonce=\"" +wss.GetNonceAsBase64() + "\", Created=\"" + wss.GetCreatedAsString() + "\"");client.Headers.Add("Content-Type","application/x-www-form-urlencoded;application/xml");byte[] responseData = client.UploadData("https://xx.com/open/getDeviceInfo","POST",postData);//得到返回字符流

 

总结

以上是生活随笔为你收集整理的C#调用JAVA接口WSSE方式用WebClient方式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。