Explore Encrypt & Decrypt Data in Flutter
Flutter is a portable UI toolkit. In other words, it’s a comprehensive app Software Development toolkit (SDK) that comes complete with widgets and tools. Flutter is a free and open-source tool to develop mobile, desktop, web applications. Flutter is a cross-platform development tool. This means that with the same code, we can create both IOs and Android apps. This is the best way to save time and resources in our entire process. In this, hot reload is gaining traction among mobile developers. Allows us to quickly see the changes implemented in the code with hot reload.
In this article, we will explore the Flutter Encrypt & Decrypt data files using the crypto package. With the help of this package, users can encrypt and decrypt data in a flutter. So let’s get started.
Table Of Contents::
Introduction:
Encryption is the process of converting the data into an encoded(cipher) data form. if any unauthorized person or entity gains access to it, they will not be able to read it. It is necessary to secure the files to every mobile application or Website passing data on the network before sending them to prevent unauthorized access to their data to the recipient. It helps to protect private and sensitive information and can enhance the security of communication between client apps and servers.
Decryption is the process of converting encoded data from back to a normal(plain) data form. In this post, we are showing how to encrypt input data and then decrypt it back to its normal form.
Demo module::
Type Of Encrypt data:
We will see 3 different types of algorithms to encrypt and decrypt data in a flutter.
1- AES Algorithm :
(Advanced Encryption Standard) has become the encryption algorithm of choice for governments, financial institutions, and security-conscious enterprises around the world. The U.S. National Security Agency (NSC) uses it to protect the country’s “top secret” information.
2- Fernet Algorithm:
Fernet is an asymmetric encryption method that makes sure that the message encrypted cannot be manipulated/read without the key. It uses URL-safe encoding for the keys. Fernet also uses 128-bit AES in CBC mode and PKCS7 padding, with HMAC using SHA256 for authentication. The IV is created from os. random(). All of this is the kind of thing that good software needs.
3- Salsa Algorithm:
Salsa20 is a cipher that was submitted to the eSTREAM project, running from 2004 to 2008, which was supposed to promote the development of stream ciphers. It is considered to be a well-designed and efficient algorithm. There aren’t any known and effective attacks on the family of Salsa20 ciphers.
Code Implementation:
Let’s start with code implementation. To implement the following project you need to integrate the crypto
package into your Flutter app.
Step 1: Add the dependencies
Add dependencies to pubspec — yaml file.
- > encrypt: ^5.0.1
Now in your Dart code, you can use the following import this package.
import 'package:crypto/crypto.dart';
step 2: I have created a dart file to define AES, Fernet, and Salsa algorithms.
This file has 2 methods for encrypting and decrypt data using the AES algorithm.
class EncryptData{
//for AES Algorithms
static Encrypted? encrypted;
static var decrypted;
static encryptAES(plainText){
final key = Key.fromUtf8('my 32 length key................');
final iv = IV.fromLength(16);
final encrypter = Encrypter(AES(key));
encrypted = encrypter.encrypt(plainText, iv: iv);
print(encrypted!.base64);
}
static decryptAES(plainText){
final key = Key.fromUtf8('my 32 length key................');
final iv = IV.fromLength(16);
final encrypter = Encrypter(AES(key));
decrypted = encrypter.decrypt(encrypted!, iv: iv);
print(decrypted);
}
}
This file has 2 methods for encrypting and decrypt data using the Salsa algorithm.//for Fernet Algorithms
static Encrypted? fernetEncrypted;
static var fernetDecrypted; static encryptFernet(plainText){
final key = Key.fromUtf8('my32lengthsupersecretnooneknows1');
final iv = IV.fromLength(16);
final b64key = Key.fromUtf8(base64Url.encode(key.bytes));
final fernet = Fernet(b64key);
final encrypter = Encrypter(fernet);
fernetEncrypted = encrypter.encrypt(plainText);
print(fernetEncrypted!.base64); // random cipher text
print(fernet.extractTimestamp(fernetEncrypted!.bytes));
}
static decryptFernet(plainText){
final key = Key.fromUtf8('my32lengthsupersecretnooneknows1');
final iv = IV.fromLength(16);
final b64key = Key.fromUtf8(base64Url.encode(key.bytes));
final fernet = Fernet(b64key);
final encrypter = Encrypter(fernet);
fernetDecrypted = encrypter.decrypt(fernetEncrypted!);
print(fernetDecrypted);
}
Step 3: Now finally call this above method in the home screen dart file.
In this file, I designed a card with 1 Text Field and 2 buttons, and 2 text views to show encrypting and decrypting results. Here are the screenshots and code snippets.
Code File:
import 'package:encrypt_data_demo/encrypt_data.dart';
import 'package:flutter/material.dart';
class HomeView extends StatefulWidget {
@override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
TextEditingController? _controller=TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.orange,
appBar: AppBar(
title: Text("Encrypt and Decrypt Data"),
),
body: SingleChildScrollView(
child: Container(
margin: EdgeInsets.only(top:10,bottom: 10),
child: _buildBody(),
),
),
);
}
Widget _buildBody() {
return Container(
height: 280,
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.only(left: 10,right: 10),
child: Card(
elevation: 2,
child: Container(
padding: EdgeInsets.only(left: 15,right: 15,top:
15,bottom: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
child: TextField(
controller: _controller,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter Text',
),
),
),
SizedBox(height: 30),
Text("EncryptText : ${EncryptData.aesEncrypted!=null?EncryptData.aesEncrypted?.base64:''}",
maxLines: 2,
style:TextStyle(
color: Colors.black,
fontSize: 16
),
overflow: TextOverflow.ellipsis,
),
SizedBox(height: 10,),
Expanded(
child: Text("DecryptText : ${EncryptData.aesDecrypted!=null?EncryptData.aesDecrypted:''}",
maxLines: 2,
overflow: TextOverflow.ellipsis,
style:TextStyle(
color: Colors.black,
fontSize: 16
)
),
),
SizedBox(height: 20,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.blue, // background
onPrimary: Colors.white,
),
onPressed: () {
setState(() {
EncryptData.encryptAES(_controller!.text);
});
},
child: Text('Encryption'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.blue, // background
onPrimary: Colors.white,
),
onPressed: () {
setState(() {
EncryptData.decryptAES(_controller!.text);
});
},
child: Text('Decryption'),
)
],
)
],
),
),
),
);
}
}
Conclusion:
In this article, I have explained the basic overview of the Encrypt data in a flutter, you can modify this code according to your choice. This was a small introduction to Encrypt & Decrypt data On User Interaction from my side, and it’s working using Flutter.
I hope this blog will provide you with sufficient information on Trying up the Explore, Encrypt & Decrypt data in your flutter projects.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
Feel free to connect with us
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.