0

I'm trying to send email and password to API. The password needs to be encrypted with sha256. So far I tried 2 packages - flutter_string_encryption and crypto but can't get it to work. With the first package, I can't find the sha256 method and with the second package, I'm getting an error when decoding List<Int> into a String. What is the proper way to do this?

Sprowk
  • 355
  • 1
  • 6
  • 15

1 Answers1

1

The crypto documentation is straight forward. You can perform sha256 hashing as follows. If it doesn't solve what you are looking for, please add a minimum code that can reproduce the problem you are facing.

// import the packages
import 'package:crypto/crypto.dart';
import 'dart:convert'; // for the utf8.encode method

// then hash the string
var bytes = utf8.encode("foobar"); // data being hashed
var digest = sha256.convert(bytes);
print("Digest as hex string: $digest");
  • With this package I'm getting _Unhandled Exception: FormatException: Bad UTF-8 encoding 0x8f (at offset 2)_ `var bytes = utf8.encode("foobar"); var digest = sha256.convert(bytes); print("Digest as hex string: $digest"); url += utf8.decode(digest.bytes);` – Sprowk Jan 11 '20 at 20:37
  • As far as I know, utf8.decode works only if digest.bytes are all utf8 characters. If you still want to do that, you can use allowMalformed: true. utf8.decode(digest.bytes, allowMalformed: true); However I would go with: String.fromCharCodes(digest.bytes); – Paras Nath Chaudhary Jan 12 '20 at 02:18
  • Printing the digest works and the result looks like this: Digest as hex string: 03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4. However, doing `url += String.fromCharCodes(digest.bytes);` adds these characters to the string: ¬gBóá\vá¥âUðg6#ȳ´Eùx×ÈFô. What am I doing wrong? url is var containing string and I'm just appending another string, right? – Sprowk Jan 12 '20 at 12:52