public void Load(TokenCacheNotificationArgs args)
 {
     var binaryData = _distributedCache.Get(_cacheKey);
     try
     {
         args.TokenCache.DeserializeMsalV3(_protector?.Unprotect(binaryData) ?? binaryData);
     }
     catch (Exception ex)
     {
         args.TokenCache.DeserializeMsalV2(_protector?.Unprotect(binaryData) ?? binaryData);
         _logger?.Error(ex);
     }
 }
        public static SignInMessage Unprotect(string data, IDataProtector protector)
        {
            var json = protector.Unprotect(data, "signinmessage");
            var message = JsonConvert.DeserializeObject<SignInMessage>(json);

            if (DateTime.UtcNow > message.ValidTo)
            {
                throw new Exception("SignInMessage expired.");
            }

            return message;
        }
        public static SignInMessage Unprotect(string data, IDataProtector protector)
        {
            var settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore
            };

            var json = protector.Unprotect(data, "signinmessage");
            var message = JsonConvert.DeserializeObject<SignInMessage>(json);

            if (DateTime.UtcNow > message.ValidTo)
            {
                throw new Exception("SignInMessage expired.");
            }

            return message;
        }
Exemple #4
0
        public DashboardViewModel ToDashboardViewModel(byte[] byteArray)
        {
            if (byteArray == null)
            {
                throw new ArgumentNullException(nameof(byteArray));
            }

            IDataProtector dataProtector = _dataProtectionProvider.CreateProtector("DashboardProtection");

            try
            {
                using (MemoryStream memoryStream = new MemoryStream(dataProtector.Unprotect(byteArray)))
                {
                    using (MemoryStream targetStream = new MemoryStream())
                    {
                        using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                        {
                            gZipStream.CopyTo(targetStream);
                            gZipStream.Flush();

                            targetStream.Seek(0, SeekOrigin.Begin);

                            BinaryFormatter binaryFormatter = new BinaryFormatter();
                            return((DashboardViewModel)binaryFormatter.Deserialize(targetStream));
                        }
                    }
                }
            }
            catch (CryptographicException)
            {
                return(null);
            }
            catch (InvalidDataException)
            {
                return(null);
            }
            catch (SerializationException)
            {
                return(null);
            }
        }
Exemple #5
0
        public async Task <IActionResult> Index([FromQuery] string removed)
        {
            var cookie = _shortlistCookieService.Get(Constants.ShortlistCookieName);

            if (cookie == default)
            {
                return(View(new ShortlistViewModel()));
            }

            var result =
                await _mediator.Send(
                    new GetShortlistForUserQuery { ShortlistUserId = cookie.ShortlistUserId });

            var removedProviderName = string.Empty;

            if (!string.IsNullOrEmpty(removed))
            {
                try
                {
                    var base64EncodedBytes = WebEncoders.Base64UrlDecode(removed);
                    removedProviderName = System.Text.Encoding.UTF8.GetString(_protector.Unprotect(base64EncodedBytes));
                }
                catch (FormatException e)
                {
                    _logger.LogInformation(e, "Unable to decode provider name from request");
                }
                catch (CryptographicException e)
                {
                    _logger.LogInformation(e, "Unable to decode provider name from request");
                }
            }

            var viewModel = new ShortlistViewModel
            {
                Shortlist   = result.Shortlist.Select(item => (ShortlistItemViewModel)item).ToList(),
                Removed     = removedProviderName,
                HelpBaseUrl = _config.EmployerDemandFeatureToggle ? _config.EmployerDemandUrl : ""
            };

            return(View(viewModel));
        }
        public ViewResult Ogrenciler(string id)
        {
            //throw new Exception("Hata: Öğrenci gösteriminde hata oluştu.");

            int ogrenciId = Convert.ToInt32(protector.Unprotect(id));

            Ogrenci ogrenci = _ogrenciRepository.GetOgrenci(ogrenciId);

            if (ogrenci == null)
            {
                Response.StatusCode = 404;
                return(View("OgrenciBulunamadi", ogrenciId));
            }
            HomeOgrencilerViewModel homeOgrencilerViewModel = new HomeOgrencilerViewModel()
            {
                Ogrenci   = ogrenci,
                PageTitle = "Ogrenciler"
            };

            return(View(homeOgrencilerViewModel));
        }
        // Convert Protected Data into WebHook while getting from Database
        protected virtual WebHook ConvertToWebHook(Registration registration)
        {
            if (registration == null)
            {
                return(null);
            }

            try
            {
                var content = _protector != null?_protector.Unprotect(registration.ProtectedData) : registration.ProtectedData;

                var webHook = JsonConvert.DeserializeObject <WebHook>(content, _serializerSettings);
                return(webHook);
            }
            catch (Exception ex)
            {
                var message = string.Format(CultureInfo.CurrentCulture, Constants.Constants.BadWebHook, typeof(WebHook).Name, ex.Message);
                _logger.Error(message, ex);
            }
            return(null);
        }
        /// <summary>
        /// Decrypts the message
        /// </summary>
        public string Decrypt(string inputText)
        {
            inputText.CheckArgumentNull(nameof(inputText));

            try
            {
                var inputBytes = Convert.FromBase64String(inputText);
                var bytes      = _dataProtector.Unprotect(inputBytes);
                return(Encoding.UTF8.GetString(bytes));
            }
            catch (FormatException ex)
            {
                _logger.LogError(ex.Message, "Invalid base 64 string. Fall through.");
            }
            catch (CryptographicException ex)
            {
                _logger.LogError(ex.Message, "Invalid protected payload. Fall through.");
            }

            return(null);
        }
Exemple #9
0
        /// <summary>
        /// Converts the provided <paramref name="registration"/> to a <see cref="WebHook"/> instance
        /// which is returned from this <see cref="IWebHookStore"/> implementation.
        /// </summary>
        /// <param name="registration">The instance to convert.</param>
        /// <returns>An initialized <see cref="WebHook"/> instance.</returns>
        protected virtual WebHook ConvertToWebHook(TRegistration registration)
        {
            if (registration == null)
            {
                return(null);
            }

            try
            {
                string content = _protector != null?_protector.Unprotect(registration.ProtectedData) : registration.ProtectedData;

                WebHook webHook = JsonConvert.DeserializeObject <WebHook>(content, _serializerSettings);
                return(webHook);
            }
            catch (Exception ex)
            {
                string msg = string.Format(CultureInfo.CurrentCulture, StorageResources.SqlStore_BadWebHook, typeof(WebHook).Name, ex.Message);
                _logger.Error(msg, ex);
            }
            return(null);
        }
        public ViewResult Details(string id)
        {
            string   decryptedId = dataProtector.Unprotect(id);
            Employee employee    = _employeeRepository.GetEmployee(Convert.ToInt32(decryptedId));

            if (employee == null)
            {
                //Error view is used to display an error here
                ViewBag.Title   = "Error";
                ViewBag.Message = "Emplyee Not found";
                return(View("Error"));
            }
            var vm = new HomeDetailsViewModel()
            {
                Employee  = employee,
                PageTitle = "Employee Details"
            };

            ViewBag.Title = $"Employee {decryptedId}";
            return(View(vm));
        }
Exemple #11
0
        public ViewResult Details(string id)
        {
            int      employeeId = Convert.ToInt32(protector.Unprotect(id));
            Employee employee   = _employeeRepository.GetEmployee(employeeId);

            if (employee == null)
            {
                Response.StatusCode = 404;
                return(View("EmployeeNotFound", employeeId));
            }

            HomeDetailsViewModel homeDetailsViewModel = new HomeDetailsViewModel
            {
                PageTitle = "Employee-Details",
                Employee  = employee
            };



            return(View(homeDetailsViewModel));
        }
        /// <summary>
        /// 使用X509Certificate2证书解密字符串
        /// </summary>
        /// <param name="decryptStr">待解密字符串</param>
        /// <param name="services"></param>
        /// <returns></returns>
        public static string X509Certificate2Decrypt(
            string decryptStr,
            InputParameter options)
        {
            ServiceCollection service = new ServiceCollection();

            service.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(
                                         options.SecretKeyPath))
            .SetApplicationName(
                options.ApplicationName)
            .ProtectKeysWithCertificate(
                new X509Certificate2(options.CertFilePath, options.CertPassWord));

            IDataProtectionProvider protector = service
                                                .BuildServiceProvider().GetService <IDataProtectionProvider>();

            IDataProtector dataProtector = protector.CreateProtector(options.Purpose);

            return(dataProtector.Unprotect(decryptStr));
        }
        public void ConfigureServices(IServiceCollection services)
        {
            if (Environment.IsDevelopment())
            {
                services.Configure <TestOption>(Configuration.GetSection("TestOption"));
            }
            else
            {
                // 注入数据保护需要的Option
                services.Configure <ProtectionOption>(Configuration.GetSection("ProtectionOption"));

                // 注入数据保护服务(依赖指定证书)
                IDataProtector dataProtector = services.AddDataProtectionWithX509();
                // 解密字符串
                string connStr = dataProtector.Unprotect(Configuration.GetSection("Database:DbConnection").Value);
                Console.WriteLine($"Sit:ConnStr:{connStr}");
                // 解密Option;Option上带有EncryptedAttribute标记的属性将会被解密
                services.ProtectedConfigure <TestOption>(Configuration.GetSection("TestOption"));
            }
            services.AddControllers();
        }
        public Task <Message <TModel> > ReadAsync(string value)
        {
            Message <TModel> result = null;

            if (!String.IsNullOrWhiteSpace(value))
            {
                try
                {
                    var bytes = Base64Url.Decode(value);
                    bytes = _protector.Unprotect(bytes);
                    var json = Encoding.UTF8.GetString(bytes);
                    result = ObjectSerializer.FromString <Message <TModel> >(json);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Exception reading protected message");
                }
            }

            return(Task.FromResult(result));
        }
        public ViewResult Details(string Id)
        {
            //throw new Exception("Error in details view ");
            logger.LogTrace("trace");
            logger.LogDebug("debugg");
            logger.LogInformation("information");
            logger.LogWarning("warning");
            logger.LogError("Error");
            logger.LogCritical("critical");


            int employeeId = Convert.ToInt32(protector.Unprotect(Id));


            Employee employee = _employeeRepository.GetEmployee(employeeId);

            if (employee == null)
            {
                Response.StatusCode = 404;
                return(View("EmployeeNotFound", employeeId));
            }
            HomeDetailsViewModel homeDetailsViewModel = new HomeDetailsViewModel()
            {
                Employee  = employee,
                PageTitle = "Employee Details page "
            };



            // return Json(new { id = 1 ,name="balqees" });

            //   Employee model = _employeeRepository.GetEmployee(3);
            ////   ViewBag.Employee = model;
            //  ViewBag.EmployeeTitle = "Employee Details ";


            //ViewData["Employee"] = model;
            //ViewData["EmployeeTitle"] = "Employee Details ";
            return(View(homeDetailsViewModel));
        }
Exemple #16
0
        public IActionResult Index(LoginViewModel viewModel)
        {
            if (!ModelState.IsValid)//O Model é LoginViewModel. Por causa dos atributos o Java replicou lá.
            {
                return(View(viewModel));
            }


            var contato = _db.Contatos.Where(c => c.Email == viewModel.Email &&
                                             _protectorProvider.Unprotect(c.Senha) == viewModel.Senha).SingleOrDefault();

            if (contato == null)
            {
                //validação do modelo
                ModelState.AddModelError("", "Usuário ou Senha incorreto");

                return(View(viewModel));//Para o campo e-mail aparecer digitado
            }
            //Claims é um objeto. Tudo isso para cookie
            var claims = new List <Claim> //uma lista
            {                             //ctrl c v
                new Claim(ClaimTypes.Name, contato.Nome),
                new Claim(ClaimTypes.Email, contato.Email),

                //new Claim(ClaimTypes.Role, "Admin"),//Perfil apenas para teste depoiis volart
                new Claim(ClaimTypes.Role, "Vendedor"),                     //Role - Perfil
                new Claim("Contato", "Criar")
            };                                                              //Depois que está logado essas informações aparecem

            var identidade = new ClaimsIdentity(claims, _tipoAutenticacao); //As permissões são as claims
            var principal  = new ClaimsPrincipal(identidade);               //qUAL DEles é o principal. Tudo o que fizemos é para chegar na 3ª linha

            //Http context o que necessário estar disponível para eu fazer a autenticação

            HttpContext.Authentication.SignInAsync(_tipoAutenticacao, principal);

            return(RedirectToAction("Index", "Home"));
            //Action e o Controller
        }
        private Key Unprotect(Key key)
        {
            var resultKey = new Key(key.Name, null);

            var protector = _dataProtector as IPersistedDataProtector;

            if (protector != null)
            {
                bool   wasRevoked, requiresMigration;
                byte[] data   = WebEncoders.Base64UrlDecode(key.Value);
                byte[] result = protector.DangerousUnprotect(data, false, out requiresMigration, out wasRevoked);

                resultKey.Value   = Encoding.UTF8.GetString(result);
                resultKey.IsStale = requiresMigration;
            }
            else
            {
                resultKey.Value = _dataProtector.Unprotect(key.Value);
            }

            return(resultKey);
        }
Exemple #18
0
        public IActionResult AES(AESInfo aes)
        {
            string message = string.Empty;

            if (ModelState.IsValid)
            {
                string userInfo = aes.UserId + aes.Password;
                aes.EncUserInfo = _protector.Protect(userInfo);          //암호화 정보
                aes.DecUserInfo = _protector.Unprotect(aes.EncUserInfo); //복호화 정보

                ViewData["Message"] = "암복호화가 성공적으로 이루어졌습니다.";

                return(View(aes));
            }
            else
            {
                message = "암복호화를 위한 정보를 올바르게 입력하세요.";
            }

            ModelState.AddModelError(string.Empty, message);
            return(View(aes));
        }
Exemple #19
0
        public T Unprotect <T>(string input, bool sessionBase = true)
        {
            try
            {
                string _jsonData = null;

                if (sessionBase)
                {
                    _jsonData = protectorSessionBase.Unprotect(input);
                }
                else
                {
                    _jsonData = protector.Unprotect(input);
                }

                return(JsonConvert.DeserializeObject <T>(_jsonData));
            }
            catch (Exception)
            {
                return(default(T));
            }
        }
Exemple #20
0
        /// <summary>
        /// Reads the pass phrase hash.
        /// </summary>
        /// <returns>The pass phrase hash.</returns>
        internal byte[] ReadPassPhraseHash()
        {
            var registryValue = _registryStore.Read(KeyName);

            if (registryValue == null)
            {
                return(new byte[] { });
            }

            var registryValueBytes = Convert.FromBase64String(registryValue);

            var entropy = new byte[16];

            var cipherValue = new byte[registryValueBytes.Length - 16];

            Array.Copy(registryValueBytes, 0, entropy, 0, 16);
            Array.Copy(registryValueBytes, 16, cipherValue, 0, cipherValue.Length);

            var passPhraseHash = _dataProtector.Unprotect(cipherValue, entropy);

            return(passPhraseHash);
        }
Exemple #21
0
        /// <summary>
        /// Reads the cache data from the backend database.
        /// </summary>
        private void ReadCacheForSignedInUser()
        {
            if (_inMemoryCache == null) // first time access
            {
                _inMemoryCache = GetLatestUserRecordQuery().FirstOrDefault();
            }
            else
            {
                // retrieve last written record from the DB
                var lastwriteInDb = GetLatestUserRecordQuery().Select(n => n.LastWrite).FirstOrDefault();

                // if the persisted copy is newer than the in-memory copy
                if (lastwriteInDb > _inMemoryCache.LastWrite)
                {
                    // read from from storage, update in-memory copy
                    _inMemoryCache = GetLatestUserRecordQuery().FirstOrDefault();
                }
            }

            // Send data to the TokenCache instance
            _userTokenCache.DeserializeMsalV3((_inMemoryCache == null) ? null : _dataProtector.Unprotect(_inMemoryCache.CacheBits));
        }
        public async Task <FundsTransferResponse> ValidateTransactionByRef(string transactionRef)
        {
            FundsTransferResponse response = new FundsTransferResponse();

            var oralConnect = new OracleConnection(_protector.Unprotect(_appSettings.FlexConnection));

            using (oralConnect)
            {
                string query = $@"SELECT * FROM {_appSettings.FlexSchema}.ACTB_DAILY_LOG WHERE AUTH_STAT = ‘A’ AND TRN_REF_NO = :transactionRef";

                var r = await oralConnect.QueryAsync <string>(query, new { transactionRef });

                response.message = r.FirstOrDefault();

                if (!string.IsNullOrWhiteSpace(response.message))
                {
                    response.status = "true";
                }
            }

            return(response);
        }
        public string Protect(string input)
        {
            // get the path to %LOCALAPPDATA%\myapp-keys
            string destFolder = Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "blockcore-keys");

            // instantiate the data protection system at this folder
            IDataProtectionProvider dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(destFolder));

            IDataProtector protector = dataProtectionProvider.CreateProtector("Blockcore");

            // protect the payload
            string protectedPayload = protector.Protect(input);

            Console.WriteLine($"Protect returned: {protectedPayload}");

            // unprotect the payload
            string unprotectedPayload = protector.Unprotect(protectedPayload);

            Console.WriteLine($"Unprotect returned: {unprotectedPayload}");

            return(protectedPayload);
        }
Exemple #24
0
        public DashboardSettingsViewModel ToDashboardSettingsViewModel(byte[] byteArray)
        {
            if (byteArray == null)
            {
                throw new ArgumentNullException(nameof(byteArray));
            }

            IDataProtector dataProtector = _dataProtectionProvider.CreateProtector("SettingsProtection");

            try
            {
                return(JsonSerialization.FromByteArray <DashboardSettingsViewModel>(dataProtector.Unprotect(byteArray)));
            }
            catch (CryptographicException)
            {
                return(null);
            }
            catch (SerializationException)
            {
                return(null);
            }
        }
Exemple #25
0
        public string Decrypt(string payload)
        {
            try
            {
                return(_protector.Unprotect(payload));
            }
            catch (CryptographicException e)
            {
                var persistedProtector = _protector as IPersistedDataProtector;
                if (persistedProtector == null)
                {
                    throw new Exception("Can't call DangerousUnprotect.");
                }

                var plain = persistedProtector.DangerousUnprotect(
                    WebEncoders.Base64UrlDecode(payload),
                    true,
                    out var migrate,
                    out var revoked);
                return(Encoding.UTF8.GetString(plain));
            }
        }
        private JwtTokens UnprotectTokens(JwtTokens protectedTokens)
        {
            // Create a Protector and start unprotecting the tokens
            IDataProtector authProtector = this.protectionProvider.CreateProtector(TokenProtector);

            IDataProtector accessTokenProtector = authProtector.CreateProtector(AccessTokenProtector);
            string         accessToken          = accessTokenProtector.Unprotect(protectedTokens.AccessToken);

            IDataProtector idTokenProtector = authProtector.CreateProtector(IdTokenProtector);
            string         idToken          = idTokenProtector.Unprotect(protectedTokens.IdToken);

            IDataProtector refreshTokenProtector = authProtector.CreateProtector(RefreshTokenProtector);
            string         refreshToken          = refreshTokenProtector.Unprotect(protectedTokens.RefreshToken);

            // Return the unprotected tokens for use.
            return(new JwtTokens
            {
                AccessToken = accessToken,
                IdToken = idToken,
                RefreshToken = refreshToken,
            });
        }
Exemple #27
0
        public ViewResult Details(string id)
        {
            // Decrypt the employee id using Unprotect method
            string decryptedId    = protector.Unprotect(id);
            int    decryptedIntId = Convert.ToInt32(decryptedId);

            // throw new Exception("Error in details view");
            Employee employee = _employeeRepository.GetEmployee(decryptedIntId);

            if (employee == null)
            {
                Response.StatusCode = 404;
                return(View("EmployeeNotFound", decryptedIntId));
            }
            HomeDetailsViewModel homeDetailsViewModel = new HomeDetailsViewModel
            {
                Employee  = employee,
                PageTitle = "Employee Details"
            };

            return(View(homeDetailsViewModel));
        }
        public string GetCookieFromRequest(HttpContext context)
        {
            string content           = null;
            var    encrtyptedContent = context.Request.Cookies[CookieNames.LevyEmployerIndicator];

            if (string.IsNullOrWhiteSpace(encrtyptedContent))
            {
                return(null);
            }

            try
            {
                content = _dataProtector.Unprotect(encrtyptedContent);
            }
            catch (CryptographicException ex)
            {
                _logger.LogWarning(ex, "Couldn't decrypt levy cookie. Probably due to recent release changing DataProtection keys");
                DeleteCookie(context.Response);
            }

            return(content);
        }
        public bool Unprotect(string encryptedText, out string?decrypted)
        {
            decrypted = null;

            byte[] decryptedBytes;

            try
            {
                var encryptedBytes = Convert.FromBase64String(encryptedText);
                decryptedBytes = _protector.Unprotect(encryptedBytes);
            }
            catch
            {
                return(false);
            }

            var utf8 = new UTF8Encoding();

            decrypted = utf8.GetString(decryptedBytes);

            return(true);
        }
        public ActionResult <string> GetEncryption()
        {
            string plainText     = "Lorem Ipsum Dolor Sit Amet";
            string encryptedText = protector.Protect(plainText);
            string decryptedText = protector.Unprotect(encryptedText);

            //var protectorTimeLimit = protector.ToTimeLimitedDataProtector();
            //string encryptedTextLimitedByTime = protectorTimeLimit.Protect(plainText, TimeSpan.FromSeconds(5));
            //Thread.Sleep(6000);
            //string decryptedTextLimitedByTime = protectorTimeLimit.Unprotect(encryptedTextLimitedByTime);

            var result = new
            {
                plainText,
                encryptedText,
                decryptedText,
                //encryptedTextLimitedByTime,
                //decryptedTextLimitedByTime
            };

            return(Ok(result));
        }
        public static ICollection <string> GetAccessibleResources(this Controller controller, IDataProtector dataProtector)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            if (dataProtector == null)
            {
                throw new ArgumentNullException(nameof(dataProtector));
            }

            if (!controller.Request.Cookies.ContainsKey(Constants.DefaultCookieName))
            {
                return(new string[0]);
            }

            var cookieValue = controller.Request.Cookies[Constants.DefaultCookieName];
            var unprotected = dataProtector.Unprotect(cookieValue);

            return(JsonConvert.DeserializeObject <ICollection <string> >(unprotected));
        }
Exemple #32
0
        public bool TryParseCircuitId(string?text, out CircuitId circuitId)
        {
            if (text is null)
            {
                circuitId = default;
                return(false);
            }

            try
            {
                var protectedBytes   = Base64UrlTextEncoder.Decode(text);
                var unprotectedBytes = _protector.Unprotect(protectedBytes);

                if (unprotectedBytes.Length != SecretLength)
                {
                    // Wrong length
                    circuitId = default;
                    return(false);
                }

                var id = new byte[IdLength];
                Array.Copy(
                    sourceArray: unprotectedBytes,
                    sourceIndex: SecretLength - IdLength,
                    destinationArray: id,
                    destinationIndex: 0,
                    length: IdLength);

                circuitId = new CircuitId(text, Base64UrlTextEncoder.Encode(id));
                return(true);
            }
            catch (Exception)
            {
                // The payload format is not correct (either not base64urlencoded or not data protected)
                circuitId = default;
                return(false);
            }
        }
        private static StoredRequestState ExtractRequestState(IDataProtector dataProtector, OwinContext context)
        {
            var cookieData = context.Response.Headers["Set-Cookie"].Split(';', '=')[1];

            return new StoredRequestState(
                dataProtector.Unprotect(
                    HttpRequestData.GetBinaryData(cookieData)));
        }
        internal static RSAParameters? DecryptKey(IDataProtector protector, byte[] buffer, out string usage) {
            if (protector == null) {
                throw new ArgumentNullException(nameof(protector));
            }

            if (buffer == null) {
                throw new ArgumentNullException(nameof(buffer));
            }

            usage = null;

            // Note: an exception thrown in this block may be caused by a corrupted or inappropriate key
            // (for instance, if the key was created for another application or another environment).
            // Always catch the exception and return null in this case to avoid leaking sensitive data.
            try {
                var bytes = protector.Unprotect(buffer);
                if (bytes == null) {
                    return null;
                }

                using (var stream = new MemoryStream(bytes))
                using (var reader = new BinaryReader(stream)) {
                    if (/* version: */ reader.ReadInt32() != 2) {
                        return null;
                    }

                    // Note: only RSA keys are currently supported. Return null if another format has been used.
                    if (!string.Equals(/* algorithm: */ reader.ReadString(), "RSA", StringComparison.OrdinalIgnoreCase)) {
                        return null;
                    }

                    // Read the usage from the serialized key.
                    usage = reader.ReadString();

                    // Extract the RSA parameters from the serialized key.
                    return new RSAParameters {
                        D = reader.ReadBytes(reader.ReadInt32()),
                        DP = reader.ReadBytes(reader.ReadInt32()),
                        DQ = reader.ReadBytes(reader.ReadInt32()),
                        Exponent = reader.ReadBytes(reader.ReadInt32()),
                        InverseQ = reader.ReadBytes(reader.ReadInt32()),
                        Modulus = reader.ReadBytes(reader.ReadInt32()),
                        P = reader.ReadBytes(reader.ReadInt32()),
                        Q = reader.ReadBytes(reader.ReadInt32())
                    };
                }
            }

            catch {
                return null;
            }
        }