Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled Exception: PlatformException(Exception encountered, read, javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT #161

Closed
JAICHANGPARK opened this issue Sep 23, 2020 · 77 comments · Fixed by #165 or #328

Comments

@JAICHANGPARK
Copy link

How to fix this problem?

E/flutter (29195): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: PlatformException(Exception encountered, read, javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
E/flutter (29195): 	at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
E/flutter (29195): 	at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:570)
E/flutter (29195): 	at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:351)
E/flutter (29195): 	at javax.crypto.Cipher.doFinal(Cipher.java:1741)
E/flutter (29195): 	at com.it_nomads.fluttersecurestorage.ciphers.StorageCipher18Implementation.decrypt(StorageCipher18Implementation.java:91)
E/flutter (29195): 	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin.decodeRawValue(FlutterSecureStoragePlugin.java:163)
E/flutter (29195): 	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin.read(FlutterSecureStoragePlugin.java:144)
E/flutter (29195): 	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin.access$300(FlutterSecureStoragePlugin.java:29)
E/flutter (29195): 	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin$MethodRunner.run(FlutterSecureStoragePlugin.java:197)
E/flutter (29195): 	at java.lang.Thread.run(Thread.java:764)
E/flutter (29195): , null)
@bettdouglas
Copy link

I'm also experiencing the same problem

message_codecs.dart in StandardMethodCodec.decodeEnvelope at line 572 platform_channel.dart in MethodChannel._invokeMethod at line 161 Called from: <asynchronous suspension> flutter_secure_storage.dart in FlutterSecureStorage.read at line 30

PlatformException(Exception encountered, read, javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:596)
at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:363)
at javax.crypto.Cipher.doFinal(Cipher.java:2055)
at c.c.a.a.b.b(:8)
at c.c.a.a.b(:9)
at c.c.a.a.d(:2)
at c.c.a.a.onMethodCall(:11)
at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(:2)
at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(:5)
at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(:2)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(Unknown Source:19)
at android.os.Looper.loop(Unknown Source:64)
at android.app.ActivityThread.main(Unknown Source:107)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(Unknown Source:11)
at com.android.internal.os.ZygoteInit.main(Unknown Source:274)
)

@bettdouglas
Copy link

I used this workaround by adding
<application ... android:allowBackup="false" android:fullBackupContent="false">

to AndroidManifest.xml

@sheychan31
Copy link

I used this workaround by adding
<application ... android:allowBackup="false" android:fullBackupContent="false">

to AndroidManifest.xml

@bettdouglas this doesnt seem to work anymore.

@sheychan31
Copy link

I encounter this too when running the app for the 2nd time.

@dara1chan
Copy link

I got the same problem.

@HemilTheRebel
Copy link

I have the same problem. But the bug only triggers some of the time. I always reproduce it
This is my stacktrace:

PlatformException(Exception encountered, read, javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
I/flutter (30164): 	at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
I/flutter (30164): 	at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:602)
I/flutter (30164): 	at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:365)
I/flutter (30164): 	at javax.crypto.Cipher.doFinal(Cipher.java:2055)
I/flutter (30164): 	at com.it_nomads.fluttersecurestorage.ciphers.StorageCipher18Implementation.decrypt(StorageCipher18Implementation.java:91)
I/flutter (30164): 	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin.decodeRawValue(FlutterSecureStoragePlugin.java:163)
I/flutter (30164): 	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin.read(FlutterSecureStoragePlugin.java:144)
I/flutter (30164): 	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin.access$300(FlutterSecureStoragePlugin.java:29)
I/flutter (30164): 	at com.it_nomads.fl

@HemilTheRebel
Copy link

I downgraded to 3.3.3 and the issue disappeared.
Change pubspec.yaml to flutter_secure_storage: 3.3.3

@rodrigo-martins-ifood
Copy link

rodrigo-martins-ifood commented Sep 28, 2020

I'm having the same problem on 3.3.3

Repost: Version 3.3.4 with

<application ... android:allowBackup="false" android:fullBackupContent="false">

Seem to solve the problem for me.

@iNima
Copy link

iNima commented Sep 29, 2020

I added <application ... android:allowBackup="false" android:fullBackupContent="false"> with 3.3.4 but the same error is still there.
I had to change back to 3.3.2 and the problem solved.

@Andrew-Bekhiet
Copy link

I got the same problem with 3.3.3 and 3.3.4, but when downgraded to 3.3.2 it works fine for me

@sydneyagcaoili
Copy link

Used 3.3.2 then 3.3.1+1 it's still a problem..

@Andrew-Bekhiet
Copy link

Andrew-Bekhiet commented Sep 29, 2020

@sydneyagcaoili Double check if the version also changed in the pubspec.lock file

@sandeeppatel1986
Copy link

sandeeppatel1986 commented Sep 30, 2020

@Andrew-Bekhiet I have same issue also tried with deleting pubspec.lock file. Any further solution.
Flutter 1.20.2
flutter_secure_storage: ^3.3.2

Device Samsung S10+(Android 10)

@iNima
Copy link

iNima commented Sep 30, 2020

@sandeeppatel1986 Just for double-checking, go to your .pub_cache/hosted/pub.dartlang.org/ folder and check the version number of flutter_secure_storage. Make sure that the folder name is flutter_secure_storage-3.3.2

@mogol
Copy link
Owner

mogol commented Sep 30, 2020

If anyone has consistent failures, could you please provide a steps to reproduce from scratch?

If you change manifest, I believe you have to delete and then reinstall the app with new manifest, simple relaunch shouldn't help.

@HemilTheRebel
Copy link

@mogol I haven't tried to reproduce this problem due to my schedule currently. I will try to do it today. I haven't changed the manifest in the file since a long time. I had flutter_secure_storage v3.3.3 and it worked. It was when I upgraded to v3.3.4 that I started seeing this error message. I fixed the error by reverting to v3.3.3. My pubspec.yaml has: flutter_secure_storage: 3.3.3 The fix was removing the caret symbol to select an exact version

@ldemyanenko
Copy link

ldemyanenko commented Oct 5, 2020

I'm having this issue on 3.3.4- 3.3.1 versions with Flutter 1.22. I didn't find any solution. I had to remove this lib from the project

@mrevoir
Copy link

mrevoir commented Oct 5, 2020

Roughly 1% of my users are having this problem -- I'm currently using Flutter 1.20.4 and Dart 2.9.2. I haven't found a direct correlation amongst them. I added code at the same time I went from 3.3.3 to 3.3.4 to allow them to report this particular error so it may have been happening before.

@mogol I'll let you know if I'm able to replicate in a demo project.

For those moving to another library, what did you choose?

@koskimas
Copy link
Contributor

koskimas commented Oct 6, 2020

This is randomly happening for me too. The payload that causes it for me is a largeish json string that I unfortunately cannot share here.

I appreciate this great library, and thank you for all the work you've done for it. But unfortunately, this kind of bug is a no-go for this kind of a library that we must be able to trust. I realize that you are probably developing this library on your spare time, but I hope you find time to fix this soon.

@koskimas
Copy link
Contributor

koskimas commented Oct 6, 2020

Here's a reproduction.

Create a new app using flutter create

Replace the content of main.dart with this:

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Secure storage bug',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Secure storage bug'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final secureStorage1 = FlutterSecureStorage();

  Future<void> write() async {
    for (int i = 0; i < 100; ++i) {
      secureStorage1.write(key: 'TEST1', value: 'a');
      secureStorage1.write(key: 'TEST2', value: 'a');
    }
  }

  Future<void> read() async {
    for (int i = 0; i < 100; ++i) {
      secureStorage1.read(key: 'TEST1');
      secureStorage1.read(key: 'TEST2');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('write'),
              onPressed: write,
            ),
            RaisedButton(
              child: Text('read'),
              onPressed: read,
            ),
          ],
        ),
      ),
    );
  }
}

Click write and then read (may need to do that couple of times) and you'll get the error.

So this seems to happen when I run multiple read/write operations in parallel.

@koskimas
Copy link
Contributor

koskimas commented Oct 6, 2020

A temporary workaround would be to serialize all calls to this library and to only use one FlutterSecureStorage instance per app. Something like this:

class AsyncMutex {
  Completer<void> _completer;

  Future<void> lock() async {
    while (_completer != null) {
      await _completer.future;
    }

    _completer = Completer<void>();
  }

  void unlock() {
    assert(_completer != null);
    final completer = _completer;
    _completer = null;
    completer.complete();
  }
}

class SecureStorage {
  static const _secureStorage = FlutterSecureStorage();
  static final _mutex = AsyncMutex();

  Future<String> read({String key}) async {
    try {
      await _mutex.lock();
      return await _secureStorage.read(key: key);
    } finally {
      _mutex.unlock();
    }
  }

  Future<void> write({String key, String value}) async {
    try {
      await _mutex.lock();
      await _secureStorage.write(key: key, value: value);
    } finally {
      _mutex.unlock();
    }
  }
}

@koskimas
Copy link
Contributor

koskimas commented Oct 6, 2020

Looking at the android code, it seems that it's all completely thread-unsafe. this method is run in a separate thread for each call, and there's no synchronization whatsoever for any method calls except for the ensureInitStorageCipher method.

Thread safety was destroyed in this commit

@Tommimon
Copy link

Tommimon commented Oct 7, 2020

I'm developing two very similar apps, both using secure storage.

Somehow I encountered this problem in only one of those two apps. I tried all the fixes in this issue but none of those worked for me.
I tried reinstalling secure storage and now both my apps have this issue :(

I really need this package for my project, any alternative?

@mogol
Copy link
Owner

mogol commented Oct 7, 2020

@koskimas thanks for repro case 🎉 , I was looking for it quite a while. Let me try it 👍

@koskimas
Copy link
Contributor

koskimas commented Oct 7, 2020

@mogol No problem! Took me a good while too 😅

I think many of the other issues here in github are caused by the thread safety issues too. The cipher classes are not thread safe, but they are called from different threads for each flutter call. Every time two calls run in parallel, things can easily go wrong.

The correct solution, I think, would be to have only one worker thread in android native code, in which all operations are run. That way the code doesn't lock the android main thread, and the code is thread safe. HandlerThread could be a good solution.

@koskimas
Copy link
Contributor

koskimas commented Oct 8, 2020

@mogol I'd be happy to provide a PR for fixing the thread safety issues. Are you already working on the fix or should I start?

@mogol
Copy link
Owner

mogol commented Oct 8, 2020 via email

@Sorunome
Copy link

Sorunome commented Oct 8, 2020

A temporary workaround would be to serialize all calls to this library and to only use one FlutterSecureStorage instance per app. Something like this:

class AsyncMutex {
  Completer<void> _completer;

  Future<void> lock() async {
    while (_completer != null) {
      await _completer.future;
    }

    _completer = Completer<void>();
  }

  void unlock() {
    assert(_completer != null);
    final completer = _completer;
    _completer = null;
    completer.complete();
  }
}

class SecureStorage {
  static const _secureStorage = FlutterSecureStorage();
  final _mutex = AsyncMutex();

  Future<String> read({String key}) async {
    try {
      await _mutex.lock();
      return await _secureStorage.read(key: key);
    } finally {
      _mutex.unlock();
    }
  }

  Future<void> write({String key, String value}) async {
    try {
      await _mutex.lock();
      await _secureStorage.write(key: key, value: value);
    } finally {
      _mutex.unlock();
    }
  }
}

If you make the mutex global you can also use multiple instances, in case it is non-trivial to adapt your app to have a single instance for now and you need a quick fix. Of course not having global variables is cleaner code.

@postpasspost
Copy link

postpasspost commented Apr 14, 2021

This error happens only in production in the play store. Huawei android 10. Tried this:

If you need fullBackupContent="yes", you can disable backup of prefs used by the plugin.

<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
    <exclude domain="sharedpref" path="FlutterSecureStorage"/>
</full-backup-content>

But I still get the error. Using flutter_secure_storage: ^4.2.0

@komritza
Copy link

komritza commented Jul 6, 2021

I am using version 3.3.5 in the production and since few days ago I started getting sentry reports with following error log:

PlatformException
PlatformException(Exception encountered, read, javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
	at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
	at com.android.org.conscrypt.OpenSSLEvpCipher.doFinalInternal(OpenSSLEvpCipher.java:152)
	at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:374)
	at javax.crypto.Cipher.doFinal(Cipher.java:2055)
	at c.c.a.b.b.b(Unknown Source:32)
	at c.c.a.a.b(Unknown Source:11)
	at c.c.a.a.d(Unknown Source:7)
	at c.c.a.a.a(Unknown Source:0)
	at c.c.a.a$b.run(Unknown Source:134)
	at android.os.Handler.handleCallback(Handler.java:938)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loop(Looper.java:246)
	at android.os.HandlerThread.run(HandlerThread.java:67)
, null)

I tried to reproduce the bug, and I manage to do it. Devices that I have tested it Samsung s9 and Samsung s10e => error, Huawei P20 Pro is working and not crashing.
As mentioned above

  1. Installing production App from the PlayStore
  2. Login ( storing some data with FlutterSecureStorage, e.g. token)
  3. Close the App
  4. Uninstalling the App
  5. Install the production app from the PlayStore again
  6. Login -> Error occurs
    app got frozen on the splash screen and I got an instant sentry report. App stopped completely working...
    Then I have installed the app from VS code and it started working again, but I got this log in my terminal:
D/FlutterSecureStoragePl( 7250): Initializing StorageCipher
I/fluttersecurestorage( 7250): Creating keys!
I/fluttersecurestorage( 7250): Initializing
I/fluttersecurestorage( 7250): Generating key pair
E/KeyStore( 7250): generateKeyInternal failed on request -68
D/CertificatePolicyCache( 7250): Creating new instance of CertificatePolicyCache myUid: 10444 callingUid: 10444
D/CertificatePolicyCache( 7250): readVariables type: null userId: 0
D/FlutterSecureStoragePl( 7250): StorageCipher initialization complete

I don't know if this log is helpful, but this is actually a really huge bug.

@dluanoliveira1
Copy link

dluanoliveira1 commented Jul 22, 2021

Hey guys, the problem might be setting a key as empty String, at least for me that was it. I know the thread is closed, by anyways, it could help someone else.

@loonix
Copy link
Contributor

loonix commented Jul 23, 2021

I think @dluanoliveira1 got it, for example I am using this plugin and at the start of the app I am reading a value that might be stored. But when I first start the app (after 1st install) there are no keys registered yet, so it gives back that BAD DECRYPT error when it tries to read a key that does not exist.

@DineshKachhot
Copy link

I am still facing the same issue in release build, I am using flutter_secure_storage: ^4.2.0

@appu-sm
Copy link

appu-sm commented Sep 7, 2021

I'm still facing the issue in 4.2.1 and none of the above solutions work, its surprising, a package of 99% popularity is still having the issue reopened again and again :-(

@romreed
Copy link

romreed commented Oct 15, 2021

I have same issue with flutter_secure_storage: ^4.2.0 in Android 11 on samsung s20.

@rsmaximiliano
Copy link

Same issue with flutter_secure_storage: ^4.2.0

@matthewrice345
Copy link

Just ran into this issue with a Google Pixel 6 Pro tried with:
flutter_secure_storage: ^5.0.0-beta.5 and
flutter_secure_storage: ^4.2.0

@kjawadDeveloper2
Copy link

I am also facing this error.

@jesusmartinezd
Copy link

Same error here

@okan-oz
Copy link

okan-oz commented Feb 1, 2022

Same issue with flutter_secure_storage: 4.2.0

@fakfa19
Copy link

fakfa19 commented Feb 14, 2022

Still same issue with flutter_secure_storage: 4.2.1

@Nazarii77
Copy link

Still same issue with flutter_secure_storage: 5.0.2 (but happens only on some real devices, never on emulator )

@loonix
Copy link
Contributor

loonix commented Feb 22, 2022

Have you checked if you are reading a value that does not exist?

@AG-IT-Solutions
Copy link

AG-IT-Solutions commented Mar 7, 2022

Having the same Problem with 5.0.2 and i am, too, trying to read a key that doesn't exist yet. Is there a way to check first if the key exists or not? Tried it with try catch first, which worked, then tried by adding

android:allowBackup="false"
android:fullBackupContent="false"

in AndroidManifest.xml, which fixed the issue, too.

@romankis95
Copy link

This line caused the error to me
String value = await _storage?.read(key: "username"); --> version 4.2.0

@FreedomLiberty1776
Copy link

I had the same problem with version ^4.2.1 and ^5.0.2 on Samsung J737A which didn't use to happen for a while until I upgraded all my packages. I realized the problem was caused by reading keys that did not yet exist. I solved it by use a simply try catch, and returned null on error, (I think null is the default return value when a key is not found anyways).

static Future getToken() async {
try {
return await _storage.read(key: 'token');
} catch (e) {
return null;
}
}

@jfahrenkrug
Copy link

If you use version 5.0.2 or newer, make sure you use this option when creating the instance:

FlutterSecureStorage(aOptions: AndroidOptions(
    encryptedSharedPreferences: true,
));

This causes the package to use Android's built-in EncryptedSharedPreferences. The crash only seems to occur when not using this setting, because then the package uses a different way of encrypting and decrypting the prefs. You can see that by reading the source code here:

Also see #328 (comment)

@UbaidillahGit
Copy link

I used this workaround by adding <application ... android:allowBackup="false" android:fullBackupContent="false">

to AndroidManifest.xml

Thanks it works for me

@sajanIocod
Copy link

I am still experiencing this issue. Any ideas on how to resolve it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet