RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-452059

GoodBoyAlex's questions

Martin Hope
GoodBoyAlex
Asked: 2023-09-02 04:05:31 +0000 UTC

FormatException:加密文本时输入不是有效的 Base-64 字符串错误

  • 5

有一个关键类:

public class EncryptKey
{
    public EncryptKey (byte[] key) => Key = key;

    public EncryptKey (string key) => FromString(key);

    public byte[] Key { get; set; }

    public void FromString (string s)
    {
        using SymmetricAlgorithm sa = Aes.Create();

        using Rfc2898DeriveBytes hasher = new(s, sa.IV, 5000, HashAlgorithmName.SHA512);

        Key = hasher.GetBytes(32);
    }

    public override string ToString() => Convert.ToBase64String(Key);
}

加密实现如下所示:

public static string Encrypt (string text, IEncryptKey key)
{
    string textToEncode = text.Replace("/", "%SL%").Replace("+", "%PL%");

    using Aes aes = Aes.Create();

    aes.Key = key.Key;

    using MemoryStream ms = new();

    ms.Write(aes.IV);

    using (CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))

        cs.Write(Encoding.UTF8.GetBytes(textToEncode));

    return Convert.ToBase64String(ms.ToArray());
}

public static string Decrypt (string text, IEncryptKey key)
{
    string textToDecode = text.Replace("%SL%", "/").Replace("%PL%", "+");

    using MemoryStream ms = new(Convert.FromBase64String(textToDecode));

    byte[] iv = new byte[16];

    _ = ms.Read(iv);

    using Aes aes = Aes.Create();

    aes.Key = key.Key;

    aes.IV = iv;

    using CryptoStream cs = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);

    using MemoryStream output = new();

    cs.CopyTo(output);

    return Encoding.UTF8.GetString(output.ToArray());
}

我这样称呼:

var encText = Encrypt(Guid.NewGuid().ToString, new("123"));
var decText = Decrypt(encText, new("123"));

结果,出现错误:

FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters
c#
  • 1 个回答
  • 47 Views
Martin Hope
GoodBoyAlex
Asked: 2022-06-27 02:32:20 +0000 UTC

Windows Server 2022:可管理性错误

  • 0

Windows Server 2022 Datacenter 在服务器管理器中激活了持久性管理错误:

В сети: сбои при получении данных

更详细地说:

Системе не удаётся получить доступ к одному или нескольким журналам событий из-за недостаточных прав доступа, повреждения файла или по другим причинам. Дополнительные сведения см. в канале Operational журнала ошибок ServerManager-ManagmentProvider на целевом сервере.

谁遇到过,告诉我该怎么做或至少在哪里可以找到这本杂志?

sfc /scannow 没有出现错误。

windows-server
  • 0 个回答
  • 0 Views
Martin Hope
GoodBoyAlex
Asked: 2022-06-13 03:06:04 +0000 UTC

Hangfire 任务未运行

  • 0

ASP.Net 6.0 上有一个站点。在 Configure startyp.cs 中创建了一个初始化类

public static class SiteInit
{
    private static void AddTasks (IServiceProvider serviceProvider, [NotNull] IConfiguration configuration)
        {
            //Получаю DependencyIjector
            serviceProvider = serviceProvider.CreateScope().ServiceProvider;
            //Провожу инъекцию аккаунта
            AccountManager account = serviceProvider.GetRequiredService<AccountManager>();

            byte.TryParse(configuration["accountsettings:newbieexceededhours"], out byte hourstodelete);

        /* To-Do после теста отключить на Dayly */
        RecurringJob.AddOrUpdate(() => NewbieDeleterTask.Execute(account, hourstodelete), Cron.Hourly);
    }
    public static void InitSite (IServiceProvider service,[NotNull] IConfiguration configuration)
    {
        AddTasks(service, configuration);
    }
}

它的任务是初始化类中给出的任务:

/// <summary>
/// Задача удаления новичков после n часов
/// </summary>
public static class NewbieDeleterTask
{
    private static async Task ExecuteAsync ([NotNull] AccountManager account, byte hours = 36)
    {
        //Получение текущей даты
        DateTime dateTime = DateTime.UtcNow;

        //Получение списока пользователей с неподтверждённым email
        IEnumerable<MyUser> notConfirmedUsers = account.GetAllUsers().Where(usr => !usr.EmailConfirmed);

        //Список "просроченных" пользователей
        // ReSharper disable once CollectionNeverQueried.Local
        List<MyUser> overdueUsers = new();

        //Получаем список просрочек
        foreach (MyUser user in notConfirmedUsers)
        {
            if (await account.IsUserInRoleAsync(user, "newbie") && user.DateOfRegister.AddHours(hours).CompareTo(dateTime) <= 0)
                overdueUsers.Add(user);
        }

        //Удаляем пользователей
        foreach (MyUser user in overdueUsers)
            await account.DeleteUserAsync(user);
    }

    public static void Execute([NotNull] AccountManager account, byte hours = 36) =>
        ExecuteAsync(account, hours).GetAwaiter().GetResult();
}

AccountManager 本身是 usermanager 和 rolemanager 类的包装器。

一般来说,Hangfire 是这样发誓的:

warn: Hangfire.AutomaticRetryAttribute[0]
      Failed to process the job '10004': an exception occurred. Retry attempt 1 of 10 will be performed in 00:00:21.
      System.NullReferenceException: Object reference not set to an instance of an object.
         at rnrmm.Platform.AccountManager.GetAllUsers() in E:\WebSites\rnrmm_ru\rnrmm_ru\Platform\AccountManager.cs:line 69
         at rnrmm.Tasks.NewbieDeleterTask.ExecuteAsync(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 25
         at rnrmm.Tasks.NewbieDeleterTask.Execute(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 44
warn: Hangfire.AutomaticRetryAttribute[0]
      Failed to process the job '10004': an exception occurred. Retry attempt 2 of 10 will be performed in 00:00:24.
      System.NullReferenceException: Object reference not set to an instance of an object.
         at rnrmm.Platform.AccountManager.GetAllUsers() in E:\WebSites\rnrmm_ru\rnrmm_ru\Platform\AccountManager.cs:line 69
         at rnrmm.Tasks.NewbieDeleterTask.ExecuteAsync(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 25
         at rnrmm.Tasks.NewbieDeleterTask.Execute(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 44

GetAllUsers函数本身如下所示:

public List<MyUser> GetAllUsers ()
    {
        IQueryable<MyUser> usersQuery = usermanager.Users;
        return usersQuery.ToList();
    }

怎么了?为什么她没有获得用户(网站上有 3 个用户)!

asp.net-core-mvc
  • 1 个回答
  • 10 Views
Martin Hope
GoodBoyAlex
Asked: 2022-06-07 13:51:39 +0000 UTC

ASP.Net 6.0 + Identity 不存储授权

  • -1

亲爱的参与者,我请求您帮助解决这个问题:在ASP.Net 6上有一个连接了Microsoft 身份授权的站点,托管在IIS 10 (WinServer 2022)下。在开发中,用户授权(在设置“记住我”复选框时)从此过着幸福的生活。但是,在服务器上,大约10-20 分钟后,授权丢失,您必须重新登录。

这是 IdentityOptions 设置

/* Настройки UserIdentityContext */
services.AddDbContext<UserIdentityContext>(
     options => options.UseSqlServer(Configuration["ConnectionStrings:users_db"]));

IdentityBuilder ibuilder = services.AddIdentity<RnrmmUser, IdentityRole<Guid>>();
ibuilder.AddEntityFrameworkStores<UserIdentityContext>();
ibuilder.AddErrorDescriber<IdentityRussianErrorDescriber>();
ibuilder.AddDefaultTokenProviders();

services.Configure<SecurityStampValidatorOptions>(static options => 
     options.ValidationInterval = TimeSpan.FromHours(1));

services.AddAuthentication().
Services.ConfigureApplicationCookie(static options => {
     options.SlidingExpiration = true;
     options.ExpireTimeSpan = TimeSpan.FromDays(7);
});

services.Configure<IdentityOptions>(static options => {
     options.Password.RequiredLength = 8;
     options.Password.RequireNonAlphanumeric = true;
     options.Password.RequireLowercase = true;
     options.Password.RequireUppercase = true;
     options.Password.RequireDigit = true;
     options.User.RequireUniqueEmail = true;
     options.SignIn.RequireConfirmedAccount = true;
     options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
     options.Lockout.MaxFailedAccessAttempts = 10;
     options.Lockout.AllowedForNewUsers = true;
});

这是我的 Web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Перенаправление на https" stopProcessing="true">
            <match url="(.*)" />
            <conditions>
              <add input="{HTTPS}" pattern="^OFF$" />
            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Found" />
          </rule>
        </rules>
      </rewrite>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\rnrmm_ru.exe" stdoutLogEnabled="true" stdoutLogFile="w:\logs\rnrmm\errorlog" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

我是如何尝试解决问题的: 我尝试增加 cookie 的寿命,如下所示:

//Для поддержки сессий
services.AddDistributedMemoryCache();
services.AddSession(static options =>
{
     options.Cookie.Name = ".rnrmm.session.data";
     options.Cookie.IsEssential = true;
     options.Cookie.HttpOnly = false;
     options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
     //Время ожидания
     options.IdleTimeout = TimeSpan.FromDays(1);
});
авторизация
  • 1 个回答
  • 10 Views
Martin Hope
GoodBoyAlex
Asked: 2022-04-13 15:24:11 +0000 UTC

.Net 6.0:“AesManaged”已弃用:“派生的加密类型已过时。改为在基本类型上使用 Create 方法。

  • 1

亲爱的社区成员!

帮助改进代码!要加密字符串(需要将机密数据保存到公共数据库),我使用该类:

public static class StringEncriptor
    {
        private static readonly byte[] KEY = Enumerable.Range(0, 32).Select(x => (byte)x).ToArray();

        public static string Encrypt (string text)
        {
            using AesManaged aes = new() { Key = KEY };
            using MemoryStream ms = new();
            ms.Write(aes.IV);
            using (CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))
            {
                cs.Write(Encoding.UTF8.GetBytes(text));
            }
            return Convert.ToBase64String(ms.ToArray());
        }

        public static string Decrypt (string base64)
        {
            using MemoryStream ms = new(Convert.FromBase64String(base64));
            byte[] iv = new byte[16];
            ms.Read(iv);
            using AesManaged aes = new() { Key = KEY, IV = iv };
            using CryptoStream cs = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
            using MemoryStream output = new();
            cs.CopyTo(output);
            return Encoding.UTF8.GetString(output.ToArray());
        }
    }

它通常在 .Net 5.0 中解决并完全执行其功能。随着 .Net 6.0 的发布,我决定切换到它(该项目仍处于早期阶段,因此非常现实)。我遇到了这个警告:

SYSLIB0021  "AesManaged" является устаревшим: 'Derived cryptographic types are obsolete. Use the Create method on the base type instead.'

很明显,您需要使用父级的 Create 方法。请帮我理解...

提前致谢!!!

.net
  • 1 个回答
  • 10 Views
Martin Hope
GoodBoyAlex
Asked: 2022-07-18 00:19:35 +0000 UTC

打开表单时出现错误。

  • 0

是 NET.Framework 4.8。重写为 NET.Core 5。那里没有什么可重写的。2班的东西。

当我尝试显示我更改了空格的表单时,会发生不允许显示表单的错误

索引超出范围。索引必须是一个正数,并且它的大小不能超过集合的大小。参数名称: Microsoft.DotNet.DesignTools.Client.DesignerSession.FindDesignableClass(CodeCompileUnit compileUnit)
中 System.CodeDom.CodeTypeDeclarationCollection.get_Item(Int32 index) 中 System.Collections.CollectionBase.System.Collections.IList.get_Item(Int32 index)中的索引 在 Microsoft.VisualStudio.WinForms.RemoteClient.Loader.RemoteCodeDomDesignerLoader.EnsureDocument(IDesignerSerializationManager 管理器) 在 Microsoft.VisualStudio.WinForms.RemoteClient.Loader.RemoteCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager 管理器)



在 Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
--- 从先前发生异常的位置结束堆栈跟踪 ---
在 Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager )
在 System.ComponentModel.Design.Serialization.BasicDesignerLoader.BeginLoad(IDesignerLoaderHost 主机)

代码本身,例如 MainForm.cs

using SFP.Classes;
using SFP.Methods;
using System.Windows.Forms;
namespace SFP
{
    namespace Forms
    {
        public partial class MainForm : Form
        {
            public MainForm()
            {
                InitializeComponent();
            }
        }
    }
}

MainForm.Designer.cs

namespace SFP
{
    namespace Forms
    {
        partial class MainForm
        {
            /// <summary>
            /// Обязательная переменная конструктора.
            /// </summary>
            private System.ComponentModel.IContainer components = null;

            /// <summary>
            /// Освободить все используемые ресурсы.
            /// </summary>
            /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }

            #region Код, автоматически созданный конструктором форм Windows

            /// <summary>
            /// Требуемый метод для поддержки конструктора — не изменяйте 
            /// содержимое этого метода с помощью редактора кода.
            /// </summary>
            private void InitializeComponent()
            {
                this.components = new System.ComponentModel.Container();
                System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
                this.OpenDialog = new System.Windows.Forms.OpenFileDialog();
                this.FormContainer = new System.Windows.Forms.Panel();
                this.SuspendLayout();
                // 
                // OpenDialog
                // 
                this.OpenDialog.FileName = "OpenDialog";
                this.OpenDialog.ReadOnlyChecked = true;
                this.OpenDialog.RestoreDirectory = true;
                this.OpenDialog.ShowReadOnly = true;
                this.OpenDialog.SupportMultiDottedExtensions = true;
                // 
                // FormContainer
                // 
                resources.ApplyResources(this.FormContainer, "FormContainer");
                this.FormContainer.Name = "FormContainer";
                // 
                // MainForm
                // 
                resources.ApplyResources(this, "$this");
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.Controls.Add(this.FormContainer);
                this.KeyPreview = true;
                this.Name = "MainForm";
                this.ResumeLayout(false);

            }

            #endregion
            private System.Windows.Forms.ImageList MenuImagesSmall;
            private System.Windows.Forms.ImageList MenuImagesLarge;
            public System.Windows.Forms.OpenFileDialog OpenDialog;
            private System.Windows.Forms.Panel FormContainer;
        }
    }
}

程序.cs

using SFP.Forms;
using System;
using System.Windows.Forms;
namespace SFP
{
    static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}

窗口截图:

应用程序启动并像错误之前一样运行。

c#
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5