Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
CryptoService.cs
1using System.Security.Cryptography;
2using System.Text;
6
8{
12 [Singleton]
13 internal sealed class CryptoService : ICryptoService
14 {
15 private readonly string basePath;
16 private readonly string deviceId;
17 private readonly RandomNumberGenerator rnd;
18 private JwtFactory? jwtFactory;
19
23 public string DeviceID => this.deviceId;
24
28 public CryptoService()
29 {
30 this.basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
31 this.rnd = RandomNumberGenerator.Create();
32
33 try
34 {
35 this.deviceId = ServiceRef.PlatformSpecific.GetDeviceId() + "_";
36 }
37 catch (Exception ex)
38 {
39 ServiceRef.LogService.LogException(ex);
40 this.deviceId = "UNKNOWN_";
41 }
42 }
43
49 public async Task<KeyValuePair<byte[], byte[]>> GetCustomKey(string fileName)
50 {
51 byte[] key;
52 byte[] iv;
53 string? s;
54 int i;
55
56 string FileNameHash = this.deviceId + Path.GetRelativePath(this.basePath, fileName);
57
58 try
59 {
60 s = await SecureStorage.GetAsync(FileNameHash);
61 }
62 catch (TypeInitializationException ex)
63 {
64 ServiceRef.LogService.LogException(ex);
65 // No secure storage available.
66
67 key = Hashes.ComputeSHA256Hash(Encoding.UTF8.GetBytes(fileName + ".Key"));
68 iv = Hashes.ComputeSHA256Hash(Encoding.UTF8.GetBytes(fileName + ".IV"));
69 Array.Resize<byte>(ref iv, 16);
70
71 return new KeyValuePair<byte[], byte[]>(key, iv);
72 }
73
74 if (!string.IsNullOrWhiteSpace(s) && (i = s.IndexOf(',')) > 0)
75 {
76 key = Hashes.StringToBinary(s[..i]);
77 iv = Hashes.StringToBinary(s[(i + 1)..]);
78 }
79 else
80 {
81 key = new byte[32];
82 iv = new byte[16];
83
84 lock (this.rnd)
85 {
86 this.rnd.GetBytes(key);
87 this.rnd.GetBytes(iv);
88 }
89
90 s = Hashes.BinaryToString(key) + "," + Hashes.BinaryToString(iv);
91
92 try
93 {
94 await SecureStorage.SetAsync(FileNameHash, s);
95 }
96 catch(Exception ex)
97 {
98 ServiceRef.LogService.LogException(ex);
99 await ServiceRef.UiService.DisplayException(ex);
100 }
101 }
102
103 return new KeyValuePair<byte[], byte[]>(key, iv);
104 }
105
110 public string CreateRandomPassword()
111 {
112 return Hashes.BinaryToString(this.GetBytes(32));
113 }
114
115 private byte[] GetBytes(int nrBytes)
116 {
117 byte[] result = new byte[nrBytes];
118
119 lock (this.rnd)
120 {
121 this.rnd.GetBytes(result);
122 }
123
124 return result;
125 }
126
130 public async Task InitializeJwtFactory()
131 {
132 KeyValuePair<byte[], byte[]> Keys = await this.GetCustomKey("factory.jwt");
133 this.jwtFactory = JwtFactory.CreateHmacSha256(Keys.Key);
134 }
135
142 public string GenerateJwtToken(params KeyValuePair<string, object?>[] Claims)
143 {
144 if (this.jwtFactory is null)
145 throw new Exception("JWT Factory not initialized.");
146
147 return this.jwtFactory.Create(Claims);
148 }
149
155 public JwtToken? ParseAndValidateJwtToken(string Token)
156 {
157 if (this.jwtFactory is null)
158 return null;
159
160 try
161 {
162 JwtToken Parsed = new(Token);
163 if (!this.jwtFactory.IsValid(Parsed))
164 return null;
165
166 return Parsed;
167 }
168 catch (Exception)
169 {
170 return null;
171 }
172 }
173
177 public void Dispose()
178 {
179 this.jwtFactory?.Dispose();
180 this.jwtFactory = null;
181 }
182 }
183}
Base class that references services in the app.
Definition: ServiceRef.cs:31
static ILogService LogService
Log service.
Definition: ServiceRef.cs:91
static IUiService UiService
Service serializing and managing UI-related tasks.
Definition: ServiceRef.cs:55
Contains methods for simple hash calculations.
Definition: Hashes.cs:59
static byte[] StringToBinary(string s)
Parses a hex string.
Definition: Hashes.cs:102
static string BinaryToString(byte[] Data)
Converts an array of bytes to a string with their hexadecimal representations (in lower case).
Definition: Hashes.cs:65
static byte[] ComputeSHA256Hash(byte[] Data)
Computes the SHA-256 hash of a block of binary data.
Definition: Hashes.cs:348
A factory that can create and validate JWT tokens.
Definition: JwtFactory.cs:53
bool IsValid(JwtToken Token)
Checks if a token is valid and signed by the factory.
Definition: JwtFactory.cs:176
static JwtFactory CreateHmacSha256()
Creates a JWT factory that can create and validate JWT tokens using the HMAC-SHA256 algorithm.
Definition: JwtFactory.cs:92
string Create(params KeyValuePair< string, object >[] Claims)
Creates a new JWT token.
Definition: JwtFactory.cs:248
void Dispose()
IDisposable.Dispose
Definition: JwtFactory.cs:160
Contains information about a Java Web Token (JWT). JWT is defined in RFC 7519: https://tools....
Definition: JwtToken.cs:21
Cryptographic service that helps create passwords and other security related tasks.