forked from ac87/GoogleAssistantWindows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.cs
88 lines (78 loc) · 2.8 KB
/
Utils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using Google.Apis.Util.Store;
namespace GoogleAssistantWindows
{
public class Utils
{
public static string GetDataStoreFolder()
{
return new FileDataStore(Const.Folder).FolderPath + "\\";
}
public static bool HasTokenFile() => GetTokenFile() != null;
public static string GetTokenFile()
{
// Can't find a nicer way in the OAuth2 Lib to see if we've ever authorised, so look for the datastore file
return Directory.EnumerateFiles(GetDataStoreFolder()).FirstOrDefault(file => file.Contains($"-{Const.User}"));
}
public static void GetImage(string url, string imageFile)
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(new Uri(url), imageFile);
}
}
// ref http://stackoverflow.com/a/3978040
public static int GetRandomUnusedPort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
/// <summary>
/// Returns URI-safe data with a given input length.
/// </summary>
/// <param name="length">Input length (nb. output will be longer)</param>
/// <returns></returns>
public static string RandomDataBase64Url(uint length)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] bytes = new byte[length];
rng.GetBytes(bytes);
return Base64UrlEncodeNoPadding(bytes);
}
/// <summary>
/// Returns the SHA256 hash of the input string.
/// </summary>
/// <param name="inputStirng"></param>
/// <returns></returns>
public static byte[] Sha256(string inputStirng)
{
byte[] bytes = Encoding.ASCII.GetBytes(inputStirng);
SHA256Managed sha256 = new SHA256Managed();
return sha256.ComputeHash(bytes);
}
/// <summary>
/// Base64url no-padding encodes the given input buffer.
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static string Base64UrlEncodeNoPadding(byte[] buffer)
{
string base64 = Convert.ToBase64String(buffer);
// Converts base64 to base64url.
base64 = base64.Replace("+", "-");
base64 = base64.Replace("/", "_");
// Strips padding.
base64 = base64.Replace("=", "");
return base64;
}
}
}