我的 javascript 技能很少,我不确定在将原始 Uint8Array(32) 发送到 localStorage、解码并转换回 Uint8Array(32) 后如何获取它。下面你会看到我尝试对私钥进行字符串化,然后对其进行 base64 编码,以便将其发送到 localStorage 以供以后使用:
window.genSKey = function()
{
var secretKey = eccrypto.generatePrivate();
console.log(secretKey);
var skey = JSON.stringify(secretKey);
var SKey = window.btoa(skey);
localStorage.setItem("skey", SKey);
console.log(SKey);
alert(`your private key is ${SKey}`);
return;
}
在这里,您会注意到我正在尝试获取私钥,以便我可以通过从 localStorage 获取 base64 编码的字符串并从中创建一个新的 Uint8Array 来生成相应的公钥:
window.base642Array = function(base64) {
var binStr = window.atob(base64);
console.log("binStr"+ binStr);
var l = binStr.length;
var bytes = new Uint8Array(l);
for (var i = 0; i < l; i++) {
bytes[i] = binStr.charCodeAt(i);
}
return bytes.buffer;
}
window.genPKey = function()
{
console.log("getSKey flag: 0");
var SKey = getSKey();
console.log("getSKey flag: 1");
var publicKey;
if(SKey != null || undefined)
{
console.log(SKey);
console.log("getSKey flag: 2");
publicKey = eccrypto.getPublic(SKey);
console.log("getSKey flag: 3");
localStorage.setItem("pkey", window.btoa(JSON.stringify(publicKey)));
return;
}
console.log("getSKey flag: alt");
genSKey();
genPKey();
return;
window.getSKey = function()
{
console.log("getSKey flag: 0");
var SKey = localStorage.getItem("skey");
var skey = base642Array(SKey);
console.log("getSKey flag: 1");
console.log("getSKey flag: 2");
console.log(skey);
return skey;
}
在这里您会看到输入的结果与输出的结果不同:
在
Uint8Array(32) [247, 145, 236, 54, 52, 10, 202, 187, 35, 79, 42, 141, 230, 76, 228, 2, 109, 228, 72, 92, 221, 139, 235, 147, 244, 10, 149, 220, 196, 175, 11, 128]
0: 247
1: 145
2: 236
3: 54
4: 52
5: 10
6: 202
7: 187
8: 35
9: 79
10: 42
11: 141
12: 230
13: 76
14: 228
15: 2
16: 109
17: 228
18: 72
19: 92
20: 221
21: 139
22: 235
23: 147
24: 244
25: 10
26: 149
27: 220
28: 196
29: 175
30: 11
31: 128
offset: (...)
parent: (...)
buffer: (...)
byteLength: (...)
byteOffset: (...)
length: (...)
Symbol(Symbol.toStringTag): (...)
__proto__: Uint8Array
出去
ArrayBuffer(141) {}
[[Int8Array]]: Int8Array(141)
[0 … 99]
[100 … 140]
__proto__: TypedArray
[[Uint8Array]]: Uint8Array(141)
[0 … 99]
[100 … 140]
__proto__: TypedArray
byteLength: (...)
__proto__: ArrayBuffer
byteLength: (...)
constructor: ƒ ArrayBuffer()
slice: ƒ slice()
Symbol(Symbol.toStringTag): "ArrayBuffer"
get byteLength: ƒ byteLength()
__proto__: Object
[[IsDetached]]: false
我认为问题可能是使用 JSON.stringify 将嵌套的 Uint8Array 转换为字符串,但我不确定是否有其他方法可以使此功能正常运行。
为什么对象输入与对象输出不一样?我想学习如何做到这一点,帮助对我来说意味着世界。