微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用公钥和私钥使用libsodiumWrapper库解密?

如何解决如何使用公钥和私钥使用libsodiumWrapper库解密?

我正在尝试使用公共密钥和私有密钥对加密的哈希字符串进行解密。由于我是这个钠库的新手,所以我不太了解。我尝试了所有可能的方法。但是我遇到了错误。 我尝试将其转换为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,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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?