How to Fix : Flutter [flutter_secure_storage] Exception encountered, read, javax.crypto.BadPaddingException Issue on Android: A Step-by-Step Guide
In case you are a Flutter developer, the chances are really high that you have relied on flutter_secure_storage for handling sensitive data securely. Recently, I had to face one of the reported issues [#541] is causing some frustration to some developers. Fortunately, there is a simple fix which can help you get over with this. This article will walk you through steps to resolve the issue and have secure storage working again on Android devices.
Understanding the Issue
The BadPaddingException error occurs due to issues with decryption, often triggered after updating or reinstalling the app. This issue is more prevalent on certain Samsung devices, where data backup settings may interfere with the secure storage.
Steps to Fix the Issue
1. Update Your Dependencies
dependencies:
flutter:
sdk: flutter
//Also tested on 8.0.0 (Due to Dependency Lock)
flutter_secure_storage: ^9.2.2
2. Configure Secure Storage with Android Options
final secureStorage = FlutterSecureStorage(
aOptions: AndroidOptions(
encryptedSharedPreferences: true,
),
);
3. Clear Data on Error (Not Recommended if your app is heavily based on Cache)
try {
String? value = await secureStorage.read(key: 'key');
} catch (e) {
if (e is PlatformException && e.code == 'BadPaddingException') {
await secureStorage.deleteAll();
}
}
And thats how you fix the bug✅ . Also this error is still on the official package and that means this workaround doesn't apply to everyone, until the bug is fixed. FurtherMore [Github Open Issue]
Also for IOS sometimes Null Values are returning when reopening the app due to this bug. So to fix that I suggest you to migrate your IOS secure storage to flutter_keychain package.
I hope this article has helped most of you but not for all 😢 due to this specific scenario.Also drop me a few claps 👏 👏 👏 … if it does! Happy Coding! 👨💻
Contact me via LinkedIn if you are struggling with this issue and this fix doesn't work for you.