Buscar pacotes, repositórios e categorias de apps

Detalhes do pacotev1.0.1

encrypt_shared_preferences

Este pacote adiciona uma camada extra de proteção para informações sensíveis como credenciais de usuário, chaves de API ou outros dados confidenciais armazenados no seu aplicativo.

AndroidiOSWebmacOSWindowsLinux
Downloads em 30 dias
17,8 mil
Curtidas
49
Pontos Pub
130

Instalar pacote

flutter pub add encrypt_shared_preferences

Visão geral do pacote

Orientação gerada a partir de informações públicas. Apenas para referência.

O pacote encrypt_shared_preferences melhora a segurança dos dados armazenados no SharedPreferences ao criptografar informações sensíveis, como credenciais de usuário e chaves da API. Integra-se perfeitamente em aplicativos Flutter em múltiplas plataformas, fornecendo uma camada adicional de proteção contra acesso não autorizado. Ao utilizar criptografia, garante que os dados confidenciais permaneçam seguros, mesmo se o dispositivo for comprometido. O pacote é ideal para aplicações que lidam com dados pessoais do usuário e exige configuração mínima para implementação.

Casos de uso

  • Protegendo tokens de login de usuário
  • Armazenar chaves de API com segurança
  • Proteção de dados pessoais do usuário
  • Criptografando configurações de configuração
  • Prevenção de vazamentos de dados em dispositivos rooteados
  • Melhorando a conformidade de segurança do aplicativo

Principais recursos

  • Criptografia de ponta a ponta
  • Integração fácil com SharedPreferences
  • Suporte multiplataforma
  • Gerenciamento seguro de chaves
  • Código mínimo de boilerplate
  • Suporta todas as principais plataformas do Flutter

Indicado para

  • Aplicativos que lidam com dados de usuário sensíveis
  • Aplicações financeiras ou de saúde
  • Aplicações que exigem privacidade de dados
  • Desenvolvedores priorizando segurança
  • Projetos usando SharedPreferences já existem
  • Equipes que seguem as melhores práticas de segurança

Considerações

  • Requer uma estratégia adequada de armazenamento de chaves
  • Pode afetar levemente o desempenho
  • Necessita de manipulação cuidadosa das chaves de criptografia
  • Não é substituto para segurança do lado do servidor
  • Depende da confiabilidade subjacente do SharedPreferences
  • Complexidade adicional na depuração de dados criptografados

README original

Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.

Shared preferences are a simple key-value storage mechanism that can be used to store small amounts of data. However, since shared preferences are stored in plain text, it is not suitable for storing sensitive information. To address this issue, you can use AES encryption to encrypt the data before saving it to shared preferences.

To use shared preferences with AES encryption support, you can add this package to your project as dependency.

Open pub.dev

Legacy EncryptedSharedPreferences

void main() async {
  final key = "";
  await EncryptedSharedPreferences.initialize(key: key);
  var sharedPref = EncryptedSharedPreferences.getInstance();

  await sharedPref.setString(
      'user_token', 'xxxxxxxxxxxx', notify: true); ////notify = true by default

  sharedPref.getString('user_token'); //xxxxxxxxxxxx

  await sharedPref.setInt('age', 99, notify: true); //notify = true by default

  sharedPref.getInt('age', defaultValue: 1001); //99

  await sharedPref.setDouble('pi', 3.14, notify: true); //notify = true by default

  sharedPref.getDouble('pi'); //3.14

  await sharedPref.setBool('isPremium', true, notify: true); //notify = true by default

  sharedPref.getBool('isPremium'); //true

  await sharedPref.setStringList("stringList", ["apple", "orange", "boom"]);

  sharedPref.getStringList("stringList");

  await sharedPref.remove('user_token', notify: true); //notify = true by default

  await sharedPref.clear(notify: true); //notify = true by default

  await sharedPref.reload();

  final badKeys = {
    "key1"
        "key2"
  };
  await sharedPref.removeWhere((key, value) => badKeys.contains(key));

  sharedPref.observe(key: 'token').listen((event) {
    // event = key
    print(event);
  });

  sharedPref.observeSet(keys: {'key1', 'key2', 'keyN'}).listen((event) {
    // event = key
    print(event);
  });
}

EncryptedSharedPreferencesAsync

void main() async {
  final key = "";
  await EncryptedSharedPreferencesAsync.initialize(key: key);
  var sharedPref = EncryptedSharedPreferencesAsync.getInstance();

  await sharedPref.setString(
      'user_token', 'xxxxxxxxxxxx', notify: true); ////notify = true by default

  await sharedPref.getString('user_token'); //xxxxxxxxxxxx

  await sharedPref.setInt('age', 99, notify: true); //notify = true by default

  await sharedPref.getInt('age', defaultValue: 1001); //99

  await sharedPref.setDouble('pi', 3.14, notify: true); //notify = true by default

  await sharedPref.getDouble('pi'); //3.14

  await sharedPref.setBool('isPremium', true, notify: true); //notify = true by default

  await sharedPref.getBool('isPremium'); //true

  await sharedPref.setStringList("stringList", ["apple", "orange", "boom"]);

  await sharedPref.getStringList("stringList");

  await sharedPref.remove('user_token', notify: true); //notify = true by default

  await sharedPref.clear(notify: true); //notify = true by default

  await sharedPref.reload();

  final badKeys = {
    "key1"
        "key2"
  };
  await sharedPref.removeWhere((key, value) =>
      badKeys.contains(key));

  sharedPref.observe(key: 'token').listen((event) {
    // event = key
    print(event);
  });

  sharedPref.observeSet(keys: {'key1', 'key2', 'keyN'}).listen((event) {
    // event = key
    print(event);
  });
}

[Shared builder] Here is example of how to use SharedBuilder widget

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SharedBuilder(
          listenKeys: const {"key1", "key2"}, //Optional
          builder: (EncryptedSharedPreferences encryptedSharedPreferences, String? updatedKey) {
            return Text("value : ${encryptedSharedPreferences.getString("key1")}");
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            EncryptedSharedPreferences.getInstance()
                .setString('key1', 'dataValue');
            Future.delayed(const Duration(seconds: 3), () {
              EncryptedSharedPreferences.getInstance()
                  .setString('key2', 'dataValue');
            });
          },
        ),
      ),
    );
  }
}

[Shared builder async] Here is example of how to use SharedBuilder widget

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SharedBuilderAsync(
          listenKeys: const {"key1", "key2"}, //Optional
          builder: (EncryptedSharedPreferencesAsync encryptedSharedPreferences,
              String? updatedKey) {
            return Text("value : $updatedKey");
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            EncryptedSharedPreferencesAsync.getInstance()
                .setString('key1', 'dataValue');
            Future.delayed(const Duration(seconds: 3), () {
              EncryptedSharedPreferencesAsync.getInstance()
                  .setString('key2', 'dataValue');
            });
          },
        ),
      ),
    );
  }
}

Also you can add custom external encryptor

class CustomEncryptor extends IEncryptor {
  @override
  String decrypt(String key, String encryptedData) {
    //decryption logic
  }

  @override
  String encrypt(String key, String plainText) {
    //encryption logic
  }
}

void main() {
  final key = "";
  await EncryptedSharedPreferences.initialize(key: key, encryptor: CustomEncryptor());
  var sharedPref = EncryptedSharedPreferences.getInstance();
}

DevTools extension for inspecting values

alt text

Categorias

Dependências

Lista de dependências 3 itens

Repositório-fonte

Projetos que usam este pacote