Search code examples
flutterencryptionsharedpreferences

How to store an Encrypted type in flutter sharedprefrence


Am designing an app in flutter and I have successfully encrypted a string using encrypt. now i want to store this encrypted data in sharedpreference so i can retrieve it later and decrypt it before using. I have tried setString() it does not work as it seem 'Encrypted' is a type itself so won't work with strings. Is there any work around.

this is my code

Encrypted runEncrypt( String caption) {
    final key = Key.fromUtf8('u^Hrf64hFrM08HuytDeMK7654DgJlP');
    final iv = IV.fromLength(16);

    final encryptPro = Encrypter(AES(key));

    final encrypted = encryptPro.encrypt(caption, iv: iv);

    return encrypted;
  }

/////
Encrypted keyz=runEncrypt('this is the key');
pref.setString("key",keyz);

Solution

  • You could use the base64 property of your encrypted object it returns a String. In the source code of the package it says that it returns the Encrypted as a Base64 String representation.

    pref.setString("key", keyz.base64);
    

    use the same encoding while decrypting

    Encrypter.decrypt64(valueFromSharedPref)