英文:
Append and hash two Strings as Hex with sha256 in Dart(Flutter)
问题
以下是您提供的JavaScript代码的翻译部分:
import 'dart:convert';
import 'package:crypto/crypto.dart';
void main() {
final secret = '<SomeSecretHexNumbers>';
final id = 123456789;
final idHex = id.toRadixString(16);
if (idHex.length % 2 != 0) {
idHex = '0' + idHex;
}
final hash = sha256.convert(Uint8List.fromList(hex.decode(idHex + secret)));
final expectedHash = hex.encode(hash.bytes);
print('Hash: $expectedHash');
}
请注意,上述Dart代码使用了crypto
库来执行与JavaScript代码相同的功能。不过,您需要确保在Flutter项目中引入crypto
库,以便使用sha256
和相关功能。
英文:
I have this function in JavaScript and I want to have the same functionality in my Flutter App, but I can't find something similar:
const {createHash} = require("crypto")
const secret = "<SomeSecretHexNumbers>"
let id = 123456789
let idHex = id.toString(16)
if (idHex.length % 2 != 0) {
idHex = "0" + idHex
}
let hash = createHash("sha256")
hash.update(Buffer.from(idHex, "hex"))
hash.update(Buffer.from(secret, "hex"))
const expectedHash = hash.digest("hex")
console.log("Hash: " + expectedHash)
I tried to do this in Dart but I couldn't find a way to do it.
答案1
得分: 0
Dart的十六进制编码在package:convert
中(不要与dart:convert
混淆)。由于您已经有示例代码,您应该逐行分析它,了解它的功能,并在Dart中创建相同的代码,然后进行并行测试。
sha256
摘要的文档位于crypto
包的首页,包括有关如何对多个字节数组进行哈希的示例。
例如:
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
void main() {
const secret = 'cafe1234';
final id = 123456789;
final idHex = id.toRadixString(16);
final u1 = hex.decode(idHex.padLeft((idHex.length + 1) ~/ 2 * 2, '0'));
final u2 = hex.decode(secret);
final output = AccumulatorSink<Digest>();
sha256.startChunkedConversion(output)
..add(u1)
..add(u2)
..close();
final expectedHash = hex.encode(output.events.single.bytes);
print(expectedHash);
}
英文:
Dart's hex codex is in package:convert
(not to be confused with dart:convert
). As you have the sample code, you should just work through each line seeing what it does, creating the same in Dart and test side by side.
Documentation for the sha256
digest is in the front page of the crypto
package, with example for hashing more than one byte array.
For example:
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
void main() {
const secret = 'cafe1234';
final id = 123456789;
final idHex = id.toRadixString(16);
final u1 = hex.decode(idHex.padLeft((idHex.length + 1) ~/ 2 * 2, '0'));
final u2 = hex.decode(secret);
final output = AccumulatorSink<Digest>();
sha256.startChunkedConversion(output)
..add(u1)
..add(u2)
..close();
final expectedHash = hex.encode(output.events.single.bytes);
print(expectedHash);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论