1using System.Security.Cryptography;
15 private readonly
string basePath;
16 private readonly
string deviceId;
17 private readonly RandomNumberGenerator rnd;
23 public string DeviceID => this.deviceId;
28 public CryptoService()
30 this.basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
31 this.rnd = RandomNumberGenerator.
Create();
35 this.deviceId =
ServiceRef.PlatformSpecific.GetDeviceId() +
"_";
40 this.deviceId =
"UNKNOWN_";
49 public async Task<KeyValuePair<byte[], byte[]>> GetCustomKey(
string fileName)
56 string FileNameHash = this.deviceId + Path.GetRelativePath(this.basePath, fileName);
60 s = await SecureStorage.GetAsync(FileNameHash);
62 catch (TypeInitializationException ex)
69 Array.Resize<
byte>(ref iv, 16);
71 return new KeyValuePair<byte[], byte[]>(key, iv);
74 if (!
string.IsNullOrWhiteSpace(s) && (i = s.IndexOf(
',')) > 0)
86 this.rnd.GetBytes(key);
87 this.rnd.GetBytes(iv);
94 await SecureStorage.SetAsync(FileNameHash, s);
103 return new KeyValuePair<byte[], byte[]>(key, iv);
110 public string CreateRandomPassword()
115 private byte[] GetBytes(
int nrBytes)
117 byte[] result =
new byte[nrBytes];
121 this.rnd.GetBytes(result);
130 public async Task InitializeJwtFactory()
132 KeyValuePair<byte[], byte[]> Keys = await this.GetCustomKey(
"factory.jwt");
142 public string GenerateJwtToken(params KeyValuePair<string, object?>[] Claims)
144 if (this.jwtFactory is
null)
145 throw new Exception(
"JWT Factory not initialized.");
147 return this.jwtFactory.
Create(Claims);
155 public JwtToken? ParseAndValidateJwtToken(
string Token)
157 if (this.jwtFactory is
null)
163 if (!this.jwtFactory.
IsValid(Parsed))
177 public void Dispose()
180 this.jwtFactory =
null;
Base class that references services in the app.
static ILogService LogService
Log service.
static IUiService UiService
Service serializing and managing UI-related tasks.
Contains methods for simple hash calculations.
static byte[] StringToBinary(string s)
Parses a hex string.
static string BinaryToString(byte[] Data)
Converts an array of bytes to a string with their hexadecimal representations (in lower case).
static byte[] ComputeSHA256Hash(byte[] Data)
Computes the SHA-256 hash of a block of binary data.
A factory that can create and validate JWT tokens.
bool IsValid(JwtToken Token)
Checks if a token is valid and signed by the factory.
static JwtFactory CreateHmacSha256()
Creates a JWT factory that can create and validate JWT tokens using the HMAC-SHA256 algorithm.
string Create(params KeyValuePair< string, object >[] Claims)
Creates a new JWT token.
void Dispose()
IDisposable.Dispose
Contains information about a Java Web Token (JWT). JWT is defined in RFC 7519: https://tools....
Cryptographic service that helps create passwords and other security related tasks.