sodium-friends / sodium-native

Low level bindings for libsodium
MIT License
300 stars 64 forks source link

Getting ENOMEM, Cannot allocate memory #146

Closed vikaskumr closed 5 months ago

vikaskumr commented 3 years ago

I am trying to run the below code

const secrets = require('secret-sharing')
const s = require('.')

const secret = Secret key'
const label = ''

console.log('Secret to share:', secret.toString('hex'))

console.log(`Packing with label: '${label}'`)
const packedSecret = s.packLabel(secret, label)
console.log(`Packed secret: ${packedSecret.toString('hex')}`)
console.log(`Length of packed secret is ${packedSecret.length} bytes.`)
const signingKeypair = s.keypair()
const encryptionKeypair = s.signingKeypairToEncryptionKeypair(signingKeypair)

const custodians = []
for (let i = 0; i < 5; i++) {
  custodians.push(s.encryptionKeypair())
}

// console.log('custodians', custodians);

console.log('Creating 5 shares, 3 needed to recover')
secrets.share(packedSecret, 5, 3).then((shards) => {
  // console.log('Shards:')
  // console.log(shards.map(s => s.toString('hex')))
  // console.log('Signed shards:')
  const signedShards = s.signShards(shards, signingKeypair)
  // console.log(signedShards.map(s => s.toString('hex')))

  const boxedShards = signedShards.map((shard, i) => {
    console.log(i);
    console.log(shard.length);
    console.log(custodians[i].publicKey.length);
    return s.oneWayBox(shard, custodians[i].publicKey)
  })
  console.log('Boxed shards:')
  console.log(boxedShards.map(s => s.toString('hex')))
  console.log(`Length of boxed shards are ${boxedShards[0].length} bytes.`)
  secrets.combine(shards.slice(2)).then((result) => {
    console.log('Result of recombining 3 shares:', result.toString())
  })
`})`

But while calling this function

oneWayBox (message, publicKey) {
    console.log('in one way box');
    const curvePublicKey = sodium.sodium_malloc(sodium.crypto_box_PUBLICKEYBYTES)
    console.log('curvePublicKey', curvePublicKey.toString('hex'));
    console.log('curvePublicKey', curvePublicKey.length);
    sodium.crypto_sign_ed25519_pk_to_curve25519(curvePublicKey, publicKey)

    // console.log('curvePublicKey', curvePublicKey.toString('hex'));

    console.log('in one way box');
    console.log('\n');

    const ephemeral = this.encryptionKeypair()
    const nonce = this.randomBytes(sodium.crypto_box_NONCEBYTES)
    const cipherText = sodium.sodium_malloc(message.length + sodium.crypto_box_MACBYTES)

    sodium.crypto_box_easy(cipherText, message, nonce, curvePublicKey, ephemeral.secretKey)
    zero(ephemeral.secretKey)
    zero(message)
    return Buffer.concat([nonce, ephemeral.publicKey, cipherText])
  }

specifically on this line

sodium.crypto_sign_ed25519_pk_to_curve25519(curvePublicKey, publicKey)

I am getting an error (node:2390) UnhandledPromiseRejectionWarning: Error: ENOMEM, Cannot allocate memory

mafintosh commented 5 months ago

sounds like your platform doesnt support secure memory