Signing and Verification failures for Dart Ethereum Library - dart

I am coding the logic to sign & verify a string in Dart.
I am importing the following libraries
import 'package:web3dart/web3dart.dart';
import 'package:eth_sig_util/eth_sig_util.dart';
import 'package:collection/collection.dart';
import 'package:web3dart/crypto.dart';
I generate a KeyPair using the following code. I leverage the 'package:web3dart/web3dart.dart'; library for it.
var random_number = Random.secure();
EthPrivateKey keyPair = EthPrivateKey.createRandom(random_number);
I ran the signing and verifying multiple times in a loop.
When I run over 100 times, I get 1-2 verifications which fail. And this error rate is proportional when I run it over 1000 times too. Roughly 1-2% verification failures. This is my signing logic
Future<String> sign (final String message) async
{
List<int> message_list = message.codeUnits;
final Uint8List bytes_message = Uint8List
.fromList(message_list);
String signature = EthSigUtil.signPersonalMessage
(
privateKey: bytesToHex(keyPair.privateKey),
message: bytes_message
);
return signature;
}
And the code to verify is given below :
Future<bool> verify (final String message, final String signature, String public_key) async
{
String recovered_address = '';
List<int> message_list = message.codeUnits;
final Uint8List bytes_message = Uint8List
.fromList(message_list);
try {
recovered_address = EthSigUtil.recoverPersonalSignature
(
signature: signature,
message: bytes_message
);
}
catch (e)
{
return false;
}
var given_address = publicKeyToAddress(hexToBytes(public_key));
bool is_verified = const ListEquality()
.equals(
hexToBytes(recovered_address),
given_address
);
return is_verified;
}
Am I doing something wrong?

Related

X25519 calculated shared key is different in two programs

I have written two programs which will exchange X25519 public keys and then calculate shared secret. This is just a test, so public keys are exchanged trough text files (in PEM format), program is until you tell it to continue in order to generate keypairs and exchange them.
First one is in Dart:
import 'dart:convert';
import 'dart:io';
import 'package:cryptography/cryptography.dart';
import 'package:pem/pem.dart';
Future<void> main(List<String> arguments) async {
//https://pub.dev/documentation/cryptography/latest/cryptography/X25519-class.html
final algorithm = Cryptography.instance.x25519();
final keyPair = await algorithm.newKeyPair();
var file = File('/home/razj/dartPublic.txt');
file.writeAsStringSync(PemCodec(PemLabel.publicKey)
.encode(await keyPair.extractPublicKeyBytes()));
print('PRESS AFTER C# PROGRAM GENERATES KEYPAIR');
stdin.readLineSync();
String remotePem = File('/home/razj/sharpPublic.txt').readAsStringSync();
SimplePublicKey remotePublicKey = SimplePublicKey(
PemCodec(PemLabel.publicKey).decode(remotePem),
type: KeyPairType.x25519);
final sharedSecretKey = await algorithm.sharedSecretKey(
keyPair: keyPair,
remotePublicKey: remotePublicKey,
);
List<int> sharedKeyBytes = await sharedSecretKey.extractBytes();
print(base64.encode(sharedKeyBytes));
}
extension SimpleKeyPairExtension on SimpleKeyPair {
Future<List<int>> extractPublicKeyBytes() {
return extract().then((value) => value.bytes);
}
}
Second is in .NET CORE:
using System.Security.Cryptography;
using X25519;
internal class Program
{
private static void Main(string[] args)
{
//https://github.com/HirbodBehnam/X25519-CSharp
var keyPair = X25519KeyAgreement.GenerateKeyPair();
File.WriteAllText("/home/razj/sharpPublic.txt", new string(PemEncoding.Write("PUBLIC KEY", keyPair.PublicKey)));
Console.WriteLine("PRESS AFTER DART PROGRAM GENERATES KEYPAIR");
Console.ReadKey(true);
string remotePem = File.ReadAllText("/home/razj/dartPublic.txt").Replace("-----BEGIN PUBLIC KEY-----\n", "").Replace("\n-----END PUBLIC KEY-----\n", "");
byte[] sharedKeyBytes = X25519KeyAgreement.Agreement(keyPair.PrivateKey, Convert.FromBase64String(remotePem));
Console.WriteLine(Convert.ToBase64String(sharedKeyBytes));
}
}
In the end of each program I print base64 encoded byte array which represents the shared key. Unfortunately outputs doesn't match. Any idea how to fix this or what might be wrong? Thanks for answering.
As #Topaco said,
However, you simply apply the raw 32 bytes key instead of the DER
encoded key, so the PEM key is invalid. This has no consequence, since
the reverse direction returns the raw keys that both libraries use in
the end. It is unnecessary though, just apply the (Base64 encoded) raw
keys directly.
Just exchanged keys by encoding raw key bytes to Base64 string:
Dart:
import 'dart:io';
import 'dart:convert';
import 'package:cryptography/cryptography.dart';
Future<void> main(List<String> arguments) async {
//https://pub.dev/documentation/cryptography/latest/cryptography/X25519-class.html
final algorithm = Cryptography.instance.x25519();
final keyPair = await algorithm.newKeyPair();
var file = File('/home/razj/dartPublic.txt');
SimplePublicKey publicKey = await keyPair.extractPublicKey();
//saving key bytes as base64 string
file.writeAsStringSync(base64.encode(publicKey.bytes));
print('PRESS AFTER C# PROGRAM GENERATES KEYPAIR');
stdin.readLineSync();
String remoteKeyBase64 =
File('/home/razj/sharpPublic.txt').readAsStringSync();
SimplePublicKey remotePublicKey =
SimplePublicKey(base64.decode(remoteKeyBase64), type: KeyPairType.x25519);
final sharedSecretKey = await algorithm.sharedSecretKey(
keyPair: keyPair,
remotePublicKey: remotePublicKey,
);
List<int> sharedKeyBytes = await sharedSecretKey.extractBytes();
print(base64.encode(sharedKeyBytes));
}
.NET CORE
using X25519;
internal class Program
{
private static void Main(string[] args)
{
//https://github.com/HirbodBehnam/X25519-CSharp
var keyPair = X25519KeyAgreement.GenerateKeyPair();
//saving key bytes as base64 string
File.WriteAllText("/home/razj/sharpPublic.txt", Convert.ToBase64String(keyPair.PublicKey));
Console.WriteLine("PRESS AFTER DART PROGRAM GENERATES KEYPAIR");
Console.ReadKey(true);
string remoteKeyBase64 = File.ReadAllText("/home/razj/dartPublic.txt");
byte[] sharedKeyBytes = X25519KeyAgreement.Agreement(keyPair.PrivateKey, Convert.FromBase64String(remoteKeyBase64));
Console.WriteLine(Convert.ToBase64String(sharedKeyBytes));
}
}
Dart output:
Hz2Rf2nUFbwmg4wgaXOl3qAi8ha5h61fHcMOXpNQ23o=
.NET-CORE output
Hz2Rf2nUFbwmg4wgaXOl3qAi8ha5h61fHcMOXpNQ23o=

Signing a message with hmac and sha256 in dart

I try to generate a sha256 HMAC using a base64-decoded secret key on a message. I would like to use the dart language. In python, I could do it with the following code:
# PYTHON CODE
import hmac, hashlib, base64
...
message = 'blabla'
secret = 'DfeRt[...]=='
secret_b64 = base64.b64decode(secret)
signature = hmac.new(secret_b64, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')
Here is what I tried with dart:
// DART CODE
import 'package:crypto/crypto.dart';
import 'dart:convert';
...
String message = 'blabla';
String secret = 'DfeRt[...]=='
var secret_b64 = BASE64.decode(secret);
var hmac = new Hmac(sha256, secret_b64);
// what now?
But then I don't know how to go on. I found some old example code which looks like the following
var message_byte = UTF8.encode(message);
hmac.add(message_byte);
However, the method "add" does not exist any more in the Hmac class. I also tried this, but I am not sure if this is correct
var message_byte = UTF8.encode(message);
var signature = hmac.convert(message_byte);
var signature_b64 = BASE64.encode(signature.bytes);
Can someone help me out?
If you have the whole 'message' available then just call convert(). If the message is large or in pieces then deal with it in chunks.
Your example is simple, when spelled out step by step.
String base64Key = 'DfeRt...';
String message = 'blabla';
List<int> messageBytes = utf8.encode(message);
List<int> key = base64.decode(base64Key);
Hmac hmac = new Hmac(sha256, key);
Digest digest = hmac.convert(messageBytes);
String base64Mac = base64.encode(digest.bytes);
Please read the Effective Dart guide. Note how constants are now lower case, variables in Dart use camel case, etc
I had to sign a request with hmac for calling an API in my recent project. Here is what I had done. Hope this helps you too.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:crypto/crypto.dart';
String getHmacAuthHeader({
#required final String inputUrl,
#required final dynamic inputJsonContent,
#required final String appId,
#required final String appSecrets,
final String method = "POST",
}) {
final url = _encodeUrl(inputUrl);
final seconds =
(DateTime.now().millisecondsSinceEpoch / 1000).round().toString();
final nonce = "N${DateTime.now().millisecondsSinceEpoch}";
final contentHash = _getMd5HashInBase64FromJson(inputJsonContent);
final signature = "$appId$method$url$seconds$nonce$contentHash";
final signatureHmacHashBase64 = _getHmacHashInBase64FromString(appSecrets, signature);
final token = "$appId:$signatureHmacHashBase64:$nonce:$seconds";
return "hmacauth $token";
}
String _encodeUrl(String url) {
if (!url.startsWith("/")) {
url = "/$url";
}
return Uri.encodeComponent(url).toLowerCase();
}
String _getMd5HashInBase64FromJson(dynamic json) {
final jsonString = jsonEncode(json);
final jsonStringBytes = Utf8Encoder().convert(jsonString);
final hashBytes = md5.convert(jsonStringBytes).bytes;
final hashBase64 = base64Encode(hashBytes);
return hashBase64;
}
String _getHmacHashInBase64FromString(String key, String data){
final keyBytes = Utf8Encoder().convert(key);
final dataBytes = Utf8Encoder().convert(data);
final hmacBytes = Hmac(sha256, keyBytes)
.convert(dataBytes)
.bytes;
final hmacBase64 = base64Encode(hmacBytes);
return hmacBase64;
}
Hey I'm late to Answer this question. But I think anyone can use this Answer.
I use https://pub.dev/packages/crypto package
For that you can use
import 'dart:convert';
import 'package:crypto/crypto.dart';
message = 'blabla'
secret = 'DfeRt[...]=='
void main() {
var key = utf8.encode(secret);
var bytes = utf8.encode(message);
var hmacSha256 = Hmac(sha256, key); // HMAC-SHA256
var digest = hmacSha256.convert(bytes);
print("HMAC digest as bytes: ${digest.bytes}");
print("HMAC digest as hex string: $digest");
}
I think this will save codes and clean.

Generate one file for a list of parsed files using source_gen in dart

I have a list of models that I need to create a mini reflective system.
I analyzed the Serializable package and understood how to create one generated file per file, however, I couldn't find how can I create one file for a bulk of files.
So, how to dynamically generate one file, using source_gen, for a list of files?
Example:
Files
user.dart
category.dart
Generated:
info.dart (containg information from user.dart and category.dart)
Found out how to do it with the help of people in Gitter.
You must have one file, even if empty, to call the generator. In my example, it is lib/batch.dart.
source_gen: ^0.5.8
Here is the working code:
The tool/build.dart
import 'package:build_runner/build_runner.dart';
import 'package:raoni_global/phase.dart';
main() async {
PhaseGroup pg = new PhaseGroup()
..addPhase(batchModelablePhase(const ['lib/batch.dart']));
await build(pg,
deleteFilesByDefault: true);
}
The phase:
batchModelablePhase([Iterable<String> globs =
const ['bin/**.dart', 'web/**.dart', 'lib/**.dart']]) {
return new Phase()
..addAction(
new GeneratorBuilder(const
[const BatchGenerator()], isStandalone: true
),
new InputSet(new PackageGraph.forThisPackage().root.name, globs));
}
The generator:
import 'dart:async';
import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:glob/glob.dart';
import 'package:build_runner/build_runner.dart';
class BatchGenerator extends Generator {
final String path;
const BatchGenerator({this.path: 'lib/models/*.dart'});
#override
Future<String> generate(Element element, BuildStep buildStep) async {
// this makes sure we parse one time only
if (element is! LibraryElement)
return null;
String libraryName = 'raoni_global', filePath = 'lib/src/model.dart';
String className = 'Modelable';
// find the files at the path designed
var l = buildStep.findAssets(new Glob(path));
// get the type of annotation that we will use to search classes
var resolver = await buildStep.resolver;
var assetWithAnnotationClass = new AssetId(libraryName, filePath);
var annotationLibrary = resolver.getLibrary(assetWithAnnotationClass);
var exposed = annotationLibrary.getType(className).type;
// the caller library' name
String libName = new PackageGraph.forThisPackage().root.name;
await Future.forEach(l.toList(), (AssetId aid) async {
LibraryElement lib;
try {
lib = resolver.getLibrary(aid);
} catch (e) {}
if (lib != null && Utils.isNotEmpty(lib.name)) {
// all objects within the file
lib.units.forEach((CompilationUnitElement unit) {
// only the types, not methods
unit.types.forEach((ClassElement el) {
// only the ones annotated
if (el.metadata.any((ElementAnnotation ea) =>
ea.computeConstantValue().type == exposed)) {
// use it
}
});
});
}
});
return '''
$libName
''';
}
}
It seems what you want is what this issue is about How to generate one output from many inputs (aggregate builder)?
[Günter]'s answer helped me somewhat.
Buried in that thread is another thread which links to a good example of an aggregating builder:
1https://github.com/matanlurey/build/blob/147083da9b6a6c70c46eb910a3e046239a2a0a6e/docs/writing_an_aggregate_builder.md
The gist is this:
import 'package:build/build.dart';
import 'package:glob/glob.dart';
class AggregatingBuilder implements Builder {
/// Glob of all input files
static final inputFiles = new Glob('lib/**');
#override
Map<String, List<String>> get buildExtensions {
/// '$lib$' is a synthetic input that is used to
/// force the builder to build only once.
return const {'\$lib$': const ['all_files.txt']};
}
#override
Future<void> build(BuildStep buildStep) async {
/// Do some operation on the files
final files = <String>[];
await for (final input in buildStep.findAssets(inputFiles)) {
files.add(input.path);
}
String fileContent = files.join('\n');
/// Write to the file
final outputFile = AssetId(buildStep.inputId.package,'lib/all_files.txt');
return buildStep.writeAsString(outputFile, fileContent);
}
}

AWS Cognito user authentication Missing required parameter SRP_A

I am trying to use AWS Cognito services for user authentication through ruby SDK.
I could able to sign_up, confirm sign_up process using the methods
resp = client.sign_up({ client_id: "ClientIdType",
secret_hash: "SecretHashType",
username: "UsernameType",
password: "PasswordType",
user_attributes: [{ name:"AttributeNameType",
value: "AttributeValueType",
}],
validation_data: [{
name: "AttributeNameType",
value: "AttributeValueType",
}]
})
and confirm_sign_up using
resp = client.confirm_sign_up({client_id: "ClientIdType",
secret_hash: "SecretHashType",
username: "UsernameType",
confirmation_code: "ConfirmationCodeType"
})
But while trying to sign in the user through initiate_auth I am getting an error Missing required parameter SRP_A
cog_provider.initiate_auth({client_id: "xxxxxxxxx", auth_parameters: { username: "xxx", password: "xxx"}, auth_flow: "USER_SRP_AUTH"})
What does SRP_A indicate where to find it.
I have searched for this problem and It is suggested to use the admin_initiate_auth method for signing in a user which I don't believe a best practice.
Yes, SRP_A is a large integer as defined by the Secure Remote Password Protocol. Are you trying to do SRP or just authenticate with username and password. For username/password authentication you should use the AdminInitiateAuth operation.
In our SDKs, you can see the parameters that need to be computed and passed. Take for example the Javascript SDK:
https://github.com/aws/amazon-cognito-identity-js/blob/master/src/CognitoUser.js#L152
Or in the Android SDK:
https://github.com/aws/aws-sdk-android/blob/master/aws-android-sdk-cognitoidentityprovider/src/main/java/com/amazonaws/mobileconnectors/cognitoidentityprovider/CognitoUser.java#L2123
For AWS Java SDK:
here is the class to manage this:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.math.pro.ak.util.cognito;
import com.amazonaws.AmazonClientException;
import com.amazonaws.util.StringUtils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
*
* #author marcus
*/
public class AuthenticationHelper {
private BigInteger a;
private BigInteger A;
private String poolName;
public AuthenticationHelper(String userPoolName) {
do {
a = new BigInteger(EPHEMERAL_KEY_LENGTH, SECURE_RANDOM).mod(N);
A = GG.modPow(a, N);
} while (A.mod(N).equals(BigInteger.ZERO));
if (userPoolName.contains("_")) {
poolName = userPoolName.split("_", 2)[1];
} else {
poolName = userPoolName;
}
}
public BigInteger geta() {
return a;
}
public BigInteger getA() {
return A;
}
private static final String HEX_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
+ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
+ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
+ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
+ "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
private static final BigInteger N = new BigInteger(HEX_N, 16);
private static final BigInteger GG = BigInteger.valueOf(2);
private static final BigInteger KK;
private static final int EPHEMERAL_KEY_LENGTH = 1024;
private static final int DERIVED_KEY_SIZE = 16;
private static final String DERIVED_KEY_INFO = "Caldera Derived Key";
private static final ThreadLocal<MessageDigest> THREAD_MESSAGE_DIGEST = new ThreadLocal<MessageDigest>() {
#Override
protected MessageDigest initialValue() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (final NoSuchAlgorithmException e) {
throw new AmazonClientException("Exception in authentication", e);
}
}
};
private static final SecureRandom SECURE_RANDOM;
static {
try {
SECURE_RANDOM = SecureRandom.getInstance("SHA1PRNG");
final MessageDigest messageDigest = THREAD_MESSAGE_DIGEST.get();
messageDigest.reset();
messageDigest.update(N.toByteArray());
final byte[] digest = messageDigest.digest(GG.toByteArray());
KK = new BigInteger(1, digest);
} catch (final NoSuchAlgorithmException e) {
throw new AmazonClientException(e.getMessage(), e);
}
}
public byte[] getPasswordAuthenticationKey(String userId,
String userPassword,
BigInteger B,
BigInteger salt) {
// Authenticate the password
// u = H(A, B)
final MessageDigest messageDigest = THREAD_MESSAGE_DIGEST.get();
messageDigest.reset();
messageDigest.update(A.toByteArray());
final BigInteger u = new BigInteger(1, messageDigest.digest(B.toByteArray()));
if (u.equals(BigInteger.ZERO)) {
throw new AmazonClientException("Hash of A and B cannot be zero");
}
// x = H(salt | H(poolName | userId | ":" | password))
messageDigest.reset();
messageDigest.update(poolName.getBytes(StringUtils.UTF8));
messageDigest.update(userId.getBytes(StringUtils.UTF8));
messageDigest.update(":".getBytes(StringUtils.UTF8));
final byte[] userIdHash = messageDigest.digest(userPassword.getBytes(StringUtils.UTF8));
messageDigest.reset();
messageDigest.update(salt.toByteArray());
final BigInteger x = new BigInteger(1, messageDigest.digest(userIdHash));
final BigInteger s = (B.subtract(KK.multiply(GG.modPow(x, N)))
.modPow(a.add(u.multiply(x)), N)).mod(N);
Hkdf hkdf = null;
try {
hkdf = Hkdf.getInstance("HmacSHA256");
} catch (final NoSuchAlgorithmException e) {
throw new AmazonClientException(e.getMessage(), e);
}
hkdf.init(s.toByteArray(), u.toByteArray());
final byte[] key = hkdf.deriveKey(DERIVED_KEY_INFO, DERIVED_KEY_SIZE);
return key;
}
}
And call this the method:
userAuth.put("SRP_A", new AuthenticationHelper(request.getUsername()).getA().toString(16));

How do I read console input / stdin in Dart?

How do I read console input from stdin in Dart?
Is there a scanf in Dart?
The readLineSync() method of stdin allows to capture a String from the console:
import 'dart:convert';
import 'dart:io';
void main() {
print('1 + 1 = ...');
var line = stdin.readLineSync(encoding: utf8);
print(line?.trim() == '2' ? 'Yup!' : 'Nope :(');
}
Old version:
import 'dart:io';
main() {
print('1 + 1 = ...');
var line = stdin.readLineSync(encoding: Encoding.getByName('utf-8'));
print(line.trim() == '2' ? 'Yup!' : 'Nope :(');
}
The following should be the most up to date dart code to read input from stdin.
import 'dart:async';
import 'dart:io';
import 'dart:convert';
void main() {
readLine().listen(processLine);
}
Stream<String> readLine() => stdin
.transform(utf8.decoder)
.transform(const LineSplitter());
void processLine(String line) {
print(line);
}
import 'dart:io';
void main(){
stdout.write("Enter your name : ");
var name = stdin.readLineSync();
stdout.write(name);
}
Output
Enter your name : Jay
Jay
By default readLineSync() takes input as string. But If you want integer input then you have to use parse() or tryparse().
With M3 dart classes like StringInputStream are replaced with Stream, try this:
import 'dart:io';
import 'dart:async';
void main() {
print("Please, enter a line \n");
Stream cmdLine = stdin
.transform(new StringDecoder())
.transform(new LineTransformer());
StreamSubscription cmdSubscription = cmdLine.listen(
(line) => print('Entered line: $line '),
onDone: () => print(' finished'),
onError: (e) => /* Error on input. */);
}
As of Dart 2.12, null-safety is enabled, and stdin.readLineSync() now returns a String? instead of a String.
This apparently has been confusing a lot of people. I highly recommend reading https://dart.dev/null-safety/understanding-null-safety to understand what null-safety means.
For stdin.readLineSync() specifically, you can resolve this by checking for null first, which for local variables will automatically promote a String? to a String. Here are some examples:
// Read a line and try to parse it as an integer.
String? line = stdin.readLineSync();
if (line != null) {
int? num = int.tryParse(line); // No more error about `String?`.
if (num != null) {
// Do something with `num`...
}
}
// Read lines from `stdin` until EOF is reached, storing them in a `List<String>`.
var lines = <String>[];
while (true) {
var line = stdin.readLineSync();
if (line == null) {
break;
}
lines.add(line); // No more error about `String?`.
}
// Read a line. If EOF is reached, treat it as an empty string.
String line = stdin.readLineSync() ?? '';
Note that you should not blindly do stdin.readLineSync()!. readLineSync returns a String? for a reason: it returns null when there is no more input. Using the null assertion operator (!) is asking for a runtime exception.
Note that while calling stdin.readLineSync() your isolate/thread will be blocked, no other Future will be completed.
If you want to read a stdin String line asynchronously, avoiding isolate/thread block, this is the way:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
/// [stdin] as a broadcast [Stream] of lines.
Stream<String> _stdinLineStreamBroadcaster = stdin
.transform(utf8.decoder)
.transform(const LineSplitter()).asBroadcastStream() ;
/// Reads a single line from [stdin] asynchronously.
Future<String> _readStdinLine() async {
var lineCompleter = Completer<String>();
var listener = _stdinLineStreamBroadcaster.listen((line) {
if (!lineCompleter.isCompleted) {
lineCompleter.complete(line);
}
});
return lineCompleter.future.then((line) {
listener.cancel();
return line ;
});
}
All these async API readLine*() based solutions miss the syntactic sugar which gives you the ability to do everything without synchronous blocking, but written like synchronous code. This is even more intuitive coming from other languages where you write code to execute synchronously:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
var lines = stdin.transform(utf8.decoder).transform(const LineSplitter());
await for (final l in lines) {
print(l);
}
print("done");
}
The key takeaway here is to make use of async and await:
async on your method is required, as you're using await to interface with asynchronous API calls
await for is the syntax for doing "synchronous-like" code on a Stream (the corresponding syntax for a Future is just await).
Think of await like "unwrapping" a Stream/Future for you by making the following code execute once something is available to be handled. Now you're no longer blocking your main thread (Isolate) to do the work.
For more information, see the Dart codelab on async/await.
(Sidenote: The correct way to declare any return value for an async function is to wrap it in a Future, hence Future<void> here.)
You can use the following line to read a string from the user:
String str = stdin.readLineSync();
OR the following line to read a number
int n = int.parse(stdin.readLineSync());
Consider the following example:
import 'dart:io'; // we need this to use stdin
void main()
{
// reading the user name
print("Enter your name, please: ");
String name = stdin.readLineSync();
// reading the user age
print("Enter your age, please: ");
int age = int.parse(stdin.readLineSync());
// Printing the data
print("Hello, $name!, Your age is: $age");
/* OR print in this way
* stdout.write("Hello, $name!, Your age is: $age");
* */
}
You could of course just use the dcli package and it's ask function
Import 'package: dcli/dcli.dart':
Var answer = ask('enter your name');
print (name);
Use the named validator argument to restrict input to integers.
To read from the console or terminal in Dart, you need to:
import 'dart:io' library
store the entered value using stdin.readLineSync()!
parse the input into an int using int.parse(input) if necessary
Code:
import 'dart:io';
void main() {
String? string;
var number;
stdout.writeln("Enter a String: ");
string = stdin.readLineSync()!;
stdout.writeln("Enter a number: ");
number = int.parse(stdin.readLineSync()!);
}

Resources