You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET MAUI中关闭Android端ISecureStorage的存储加密?

解决.NET MAUI Android端ISecureStorage加密导致的性能问题

方案一:改用MAUI Preferences(推荐)

如果你的数据无需加密,完全可以直接使用MAUI内置的Preferences类替代ISecureStorage。它在Android平台上基于原生SharedPreferences实现,默认不做加密操作,性能远高于ISecureStorage,且跨平台API调用逻辑一致。

使用示例:

// 存储数据
Preferences.Set("user_setting", "default_config");

// 获取数据
string settingValue = Preferences.Get("user_setting", "fallback_value");

// 删除数据
Preferences.Remove("user_setting");

方案二:自定义Android端ISecureStorage实现(保留ISecureStorage接口)

如果你想继续使用ISecureStorage的接口,但关闭Android端的加密逻辑,可以通过自定义平台特定实现替换默认的加密存储:

  1. 在项目的Platforms/Android目录下创建自定义实现类NoEncryptSecureStorage.cs:
using Android.Content;
using Microsoft.Maui.Storage;

namespace YourAppNamespace.Platforms.Android;

public class NoEncryptSecureStorage : ISecureStorage
{
    private readonly ISharedPreferences _sharedPrefs;

    public NoEncryptSecureStorage()
    {
        _sharedPrefs = Android.App.Application.Context.GetSharedPreferences("NonEncryptedStorage", FileCreationMode.Private);
    }

    public Task<string?> GetAsync(string key)
    {
        return Task.FromResult(_sharedPrefs.GetString(key, null));
    }

    public Task RemoveAsync(string key)
    {
        using var editor = _sharedPrefs.Edit();
        editor.Remove(key);
        editor.Apply();
        return Task.CompletedTask;
    }

    public Task SetAsync(string key, string value)
    {
        using var editor = _sharedPrefs.Edit();
        editor.PutString(key, value);
        editor.Apply();
        return Task.CompletedTask;
    }

    public void RemoveAll()
    {
        using var editor = _sharedPrefs.Edit();
        editor.Clear();
        editor.Apply();
    }
}
  1. 在MauiProgram.cs中注册这个自定义实现,覆盖默认的ISecureStorage服务:
builder.Services.AddSingleton<ISecureStorage, NoEncryptSecureStorage>();

该实现仅在Android平台生效,会使用不加密的SharedPreferences完成存储操作;iOS等其他平台仍会保留ISecureStorage的默认行为(若需全平台关闭加密,可对其他平台编写类似的无加密实现)。

注意:此方案仅适用于无敏感数据的场景,避免因取消加密带来不必要的安全风险。

内容的提问来源于stack exchange,提问作者Zita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:10:58