文章出處
文章列表
在調用api應用的過程,我們需要用hmac加密技術,它是一種基于hash的加密算法,通過一個雙方共同約定的密鑰,在發送message前,對密鑰進行了sha散列計算,在生成消息又對此密鑰進行了二次加密,通過周期性的更換密鑰,安全性可以得到保障。
在wp8.1 sdk中很多傳統系統類庫被整編進以windows打頭的命名空間中,很多剛接觸wp8.1朋友可能覺得疑惑。
代碼所需命名空間。
1 using System; 2 using System.Net.Http; 3 using System.Threading.Tasks; 4 using Windows.Security.Cryptography; 5 using Windows.Security.Cryptography.Core; 6 using Windows.Storage.Streams;
加密方法。
1 public string CreateHMAC(string publicKey, string privateKey) 2 { 3 string strAlgName = MacAlgorithmNames.HmacSha1; 4 MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(strAlgName); 5 6 IBuffer data = CryptographicBuffer.ConvertStringToBinary(publicKey, BinaryStringEncoding.Utf8); 7 IBuffer buffKeyMaterial = CryptographicBuffer.ConvertStringToBinary(privateKey, BinaryStringEncoding.Utf8); 8 CryptographicKey hmacKey = objMacProv.CreateKey(buffKeyMaterial); 9 10 var buffHMAC = CryptographicEngine.Sign(hmacKey, data); 11 12 return CryptographicBuffer.EncodeToBase64String(buffHMAC); 13 }
調用方式,根據天氣網api得知,加密的message為除去key之外的url,再根據私鑰簽名加密,得到最終的key。
1 public MainPageViewModel()
2 {
3 GetAsync();
4 }
5
6 public async void GetAsync()
7 {
8 string areaId = "101010100";
9 string type = "observe";
10 string date = System.DateTime.Now.ToString("yyyyMMddHHmm");
11 string appId = "---天氣網提供的appid---";
12 string privateKey = "---天氣網提供的key---";
13 string publicKey = string.Format("http://open.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}",
14 areaId, type, date, appId);
15
16 string key = CreateHMAC(publicKey, privateKey);
17 string url = string.Format(@"http://open.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}&key={4}",
18 areaId, type, date, appId.Substring(0, 6), key);
19
20 var httpClient = new HttpClient();
21 var content = await httpClient.GetStringAsync(url);
22 await Task.Run(() =>
23 {
24 string c = content;
25 });
26 }
返回的結果就是一串json了。
文章列表
全站熱搜