How can I Decrypt using libsodiumWrapper library using a public and a private key?

360 views Asked by At

I am trying to decrypt a encrypted hash string using a public and a private key.As I am new to this sodium library I do not know much. I have tried every possible way .But I am getting error. I have tried converting it to Uint8Array but it didnt help .Currently I am getting the error "invalid public key length" .My private key and public key both are hash strings.
If anyone can provide me any example or so that will be helpful.Thanks in advance

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);
}
0

There are 0 answers