C#调用JAVA接口WSSE方式用WebClient方式
生活随笔
收集整理的這篇文章主要介紹了
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方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CPU访问计算机各组件周期
- 下一篇: vim、g++、gdb及makefile