Skip to content

Instantly share code, notes, and snippets.

@techie-dan
Last active February 5, 2025 01:26
Show Gist options
  • Save techie-dan/53bb49d725efb94e247c398cced27b4d to your computer and use it in GitHub Desktop.
Save techie-dan/53bb49d725efb94e247c398cced27b4d to your computer and use it in GitHub Desktop.
Dart Encryption/Decryption
import 'package:flutter/material.dart';
import 'dart:convert'; // Access to encoding/decoding
class SimpleEncryption {
// This method takes two parameters: the text to encrypt
static String encrypt(String text, String secretKey) {
if (text.isEmpty || secretKey.isEmpty) {
throw ArgumentError('Text and secret key cannot be empty'); // Checks if text and secretKey is empty
}
// Convert text and key into numbers from 0-255
List<int> textCharacter = utf8.encode(text);
List<int> keyBytes = utf8.encode(secretKey);
// Create an empty list
List<int> encrypted = [];
// Encrypt each character using the key
for (int i = 0; i < textCharacter.length; i++) {
// Get the current key
int keyByte = keyBytes[i % keyBytes.length];
// Add the key to the text and take modulo 256
// to keep it within range (0-255)
int encryptedByte = (textCharacter[i] + keyByte) % 256;
encrypted.add(encryptedByte);
}
// Convert for safe storage and transmission
return base64Encode(encrypted);
}
/// Decrypts a string that was encrypted using the encrypt method
static String decrypt(String encryptedText, String secretKey) {
if (encryptedText.isEmpty || secretKey.isEmpty) {
throw ArgumentError('Encrypted text and secret key cannot be empty');
}
try {
// Decode the base64 string back to bytes
List<int> encryptedBytes = base64Decode(encryptedText);
List<int> keyBytes = utf8.encode(secretKey);
List<int> decrypted = [];
for (int i = 0; i < encryptedBytes.length; i++) {
int keyByte = keyBytes[i % keyBytes.length];
// Subtract the key byte and handle negative results
int decryptedByte = (encryptedBytes[i] - keyByte) % 256;
if (decryptedByte < 0) {
decryptedByte += 256;
}
decrypted.add(decryptedByte);
}
// Convert back to string
return utf8.decode(decrypted);
} catch (e) {
throw const FormatException('Failed to decrypt: Invalid input or wrong key');
}
}
}
void main() {
runApp(
const MyApp()
);
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String encrypted = "";
String decrypted = "";
@override
void initState() {
super.initState();
_encryptAndDecrypt();
}
void _encryptAndDecrypt() {
try {
String secretKey = "MyHNGTask";
String originalText = "Hello, this is my secret message!";
// Encrypt the text
encrypted = SimpleEncryption.encrypt(originalText, secretKey);
// Decrypt the text
decrypted = SimpleEncryption.decrypt(encrypted, secretKey);
// Update UI
setState(() {});
} catch (e) {
print('Error: ${e.toString()}');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.blue.shade700,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/hng_logo.jpg',
width: 100,
),
const SizedBox(height: 20),
const Text(
'Encrypted Text:',
style: TextStyle(color: Colors.white, fontSize: 18),
),
Text(
encrypted,
style: const TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
const Text(
'Decrypted Text:',
style: TextStyle(color: Colors.white, fontSize: 18),
),
Text(
decrypted,
style: const TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
],
),
),
),
);
}
}
@techie-dan
Copy link
Author

techie-dan commented Feb 5, 2025

🎓 My Second HNG App - Encryption and Decryption

Test & Live Demo

For the app test Click here

To check live demo Click here

Installation

1. Clone the repo

git clone https://gist.github.com/53bb49d725efb94e247c398cced27b4d.git

Rename the file as main.dart

2. Create a new flutter project

Run the following command in the command line / terminal

flutter create projectName

3. Add file to lib folder in the new Flutter project

4.

Use the command below to run the app on an emulator or connected device.

flutter run

Contribution

Contributions to the second HNG app are always welcome! If you have any improvements or features you'd like to add, fork the repository and submit a pull request.

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