/// <summary> /// Returns all the keys in storage. /// </summary> /// <returns></returns> public async Task <IEnumerable <SerializedKey> > LoadKeysAsync() { var list = new List <SerializedKey>(); var files = _directory.GetFiles(KeyFilePrefix + "*" + KeyFileExtension); foreach (var file in files) { var id = file.Name.Substring(4); try { using (var reader = new StreamReader(file.OpenRead())) { var json = await reader.ReadToEndAsync(); var item = KeySerializer.Deserialize <SerializedKey>(json, EncodeJson); list.Add(item); } } catch (Exception ex) { _logger.LogError(ex, "Error reading file: " + file.Name); } } return(list); }
/// <summary> /// Persists new key in storage. /// </summary> /// <param name="key"></param> /// <returns></returns> public Task StoreKeyAsync(SerializedKey key) { var json = KeySerializer.Serialize(key, EncodeJson); var path = Path.Combine(_directory.FullName, KeyFilePrefix + key.Id + KeyFileExtension); File.WriteAllText(path, json, Encoding.UTF8); return(Task.CompletedTask); }
/// <summary> /// Unprotects RsaKeyContainer. /// </summary> /// <param name="key"></param> /// <returns></returns> public RsaKeyContainer Unprotect(SerializedKey key) { var data = key.DataProtected ? _dataProtectionProvider.Unprotect(key.Data) : key.Data; var item = KeySerializer.Deserialize <RsaKeyContainer>(data); if (item.KeyType == KeyType.X509) { item = KeySerializer.Deserialize <X509KeyContainer>(data); } return(item); }
/// <summary> /// Protects RsaKeyContainer. /// </summary> /// <param name="key"></param> /// <returns></returns> public SerializedKey Protect(RsaKeyContainer key) { var data = KeySerializer.Serialize(key); if (_options.DataProtectKeys) { data = _dataProtectionProvider.Protect(data); } return(new SerializedKey { Created = DateTime.UtcNow, Id = key.Id, KeyType = key.KeyType, Data = data, DataProtected = _options.DataProtectKeys, }); }
/// <inheritdoc/> public SerializedKey Protect(KeyContainer key) { var data = KeySerializer.Serialize(key); if (_options.DataProtectKeys) { data = _dataProtectionProvider.Protect(data); } return(new SerializedKey { Version = 1, Created = DateTime.UtcNow, Id = key.Id, Algorithm = key.Algorithm, IsX509Certificate = key.HasX509Certificate, Data = data, DataProtected = _options.DataProtectKeys, }); }
/// <inheritdoc/> public KeyContainer Unprotect(SerializedKey key) { var data = key.DataProtected ? _dataProtectionProvider.Unprotect(key.Data) : key.Data; if (key.IsX509Certificate) { return(KeySerializer.Deserialize <X509KeyContainer>(data)); } if (key.Algorithm.StartsWith("R") || key.Algorithm.StartsWith("P")) { return(KeySerializer.Deserialize <RsaKeyContainer>(data)); } if (key.Algorithm.StartsWith("E")) { return(KeySerializer.Deserialize <EcKeyContainer>(data)); } throw new Exception($"Invalid Algorithm: {key.Algorithm} for kid: {key.Id}"); }