How to encrypt a text using SHA256 in dart or flutter?
We need to import a external package 'package:crypto/crypto.dart'
and a dart built-in library 'dart:convert'
. Now lets see the code for encrypting a text
import 'package:crypto/crypto.dart';
import 'dart:convert';
void main() {
String actualText = "Testing Message";
var bytes = utf8.encode(actualText); // Convert data to bytes
var shaConvert = sha256.convert(bytes);
String hashValue = shaConvert.toString(); // Get the hash as a string
print(hashValue);
}
Output:
7a328dce20f4195cacdcb1d7ab7a74ad01a134a4b18b3cd818bdbaa3a68cdc55
Explanation:
We are using import 'package:crypto/crypto.dart';
for sha256 and using import 'dart:convert';
for utf8. We need to convert the actual text which need to be encrypted into bytes before using sha256.convert() because the method sha256.convert()
needs list of bytes as input, not string. And at last we need to convert shaConvert
variable value into string because this variable value is not a regular string, it is a Digest object which contains the raw hash bytes.