1

我正在尝试使用公钥和私钥解密加密的哈希字符串。由于我是这个钠库的新手,所以我不太了解。我已经尝试了所有可能的方法。但是我遇到了错误。我尝试将其转换为 Uint8Array 但没有帮助。目前我收到错误“无效的公钥长度”。我的私钥和公钥都是哈希字符串。
如果有人可以为我提供任何示例,那将有所帮助。在此先感谢

const libsodiumWrapper = require('libsodium-wrappers');
const concat = require("concat-typed-array");
const { privatekey, publickey } = require('./SecretKeyReader');
const fs=require('fs');
const { Buffer } = require('buffer');
module.exports.encryptFor = async (message, recipientPublicKey, senderPrivateKey) => {
    await libsodiumWrapper.ready;
    const sodium = libsodiumWrapper;
    const nonce = await generateNonce(sodium);
    const ciphertext = sodium.crypto_box_easy(message, nonce, recipientPublicKey, senderPrivateKey);
    return concat(nonce, ciphertext);
}
module.exports.decryptFrom = async (ciphertextWithNonce, senderPublicKey, recipientPrivateKey) => {
    console.log("Text to decrypt="+ciphertextWithNonce)
    console.log("publickey="+senderPublicKey)
    console.log("recipientPrivateKey"+recipientPrivateKey);
    await libsodiumWrapper.ready;
    const sodium = libsodiumWrapper;
    var ciphertextWithNonce2=sodium.to_base64(ciphertextWithNonce,base64_variants.URLSAFE)
    const [nonce, ciphertext] = await splitNonceFromMessage(sodium, ciphertextWithNonce2);
    console.log("Nonce"+nonce);
    console.log("ciphertext2"+ciphertext);
    var publickey=sodium.to_base64(senderPublicKey,base64_variants.URLSAFE);
    var privatekey=new Buffer(sodium.to_base64(recipientPrivateKey,base64_variants.URLSAFE);
   // const keyPair=sodium.crypto_box_keypair(senderPublicKey.toString(16),recipientPrivateKey.toString(16));
    //console.log(keyPair);
    const decrypted = sodium.crypto_box_open_easy(sodium.to_hex(new Buffer(ciphertext)),new Buffer(nonce),publickey,privatekey);
    console.log("Decrypted"+decrypted);
    return decrypted;
}

async function splitNonceFromMessage(sodium, messageWithNonce) {
    const bytes = sodium.crypto_box_NONCEBYTES;
    const nonce = messageWithNonce.slice(0, bytes);
    const message = messageWithNonce.slice(bytes, messageWithNonce.length);
    console.log("Nonce in split="+nonce);
    console.log("message in split="+message)
    return [nonce, message];
}
async function generateNonce(sodium) {
    return await randomBytes(sodium, sodium.crypto_box_NONCEBYTES);
}
async function randomBytes(sodium, length) {
    return sodium.randombytes_buf(length);
}
4

0 回答 0