如何将Uint8Array的对象转换为字符串?

时间:2020-06-10 17:22:45

标签: javascript reactjs npm

我与此question有相同的问题。我看到了答案,但我不明白该怎么做。还有其他建议吗?

我的代码是:

var eccrypto = require("eccrypto");
var w,actual;
var publicKey = Buffer.from([4, 86, 82, 58, 244, 11, 140, 41, 132, 245, 184, 162, 163, 98, 49, 119, 168, 235, 252, 50, 6, 91, 147, 191, 190, 61, 65, 63, 101, 164, 132, 213, 188, 106, 26, 203, 171, 215, 240, 151, 7, 193, 10, 151, 103, 107, 1, 135, 117, 225, 5, 41, 55, 57, 18, 205, 98, 178, 82, 135, 170, 111, 188, 98, 57],'hex');

var privateKey= Buffer.from([238, 239, 199, 101, 188, 134, 13, 13, 195, 172, 125, 168, 225, 189, 72, 148, 225, 200, 127, 218, 204, 11, 150, 146, 180, 243, 195, 109, 200, 119, 50, 20],'hex');

eccrypto.encrypt(publicKey, Buffer.from("message")).then(function(encrypted) {
    console.log(encrypted)

    let encoded =JSON.stringify(encrypted)
    w=encoded;
    console.log(encoded)

    actual = JSON.parse((encoded))
    console.log(actual)
});

eccrypto.decrypt(privateKey,actual).then(function(plaintext) {
    console.log("Message to part B:", plaintext.toString()); 
});

当我使用actual变量时,出现以下错误:

Uncaught (in promise) Error: Bad public key

此加密输出:

enter image description here

此为已编码的输出:

enter image description here

这是实际的“我认为有些变化,不是吗?”的输出: enter image description here 谢谢你。

2 个答案:

答案 0 :(得分:1)

解析时,您需要发送一个reviver函数,该函数有条件地解析对象。如果您看到编码后的样子,您将理解为什么需要使用这种方式来编写reviver函数。

enter image description here

答案 1 :(得分:0)

我认为您需要从Buffer.from中删除“十六进制”编码参数。