0

I'm wondering if it's possible to use the Bitcoin public and private keys (usually used for signing) for text encryption. This is an example in nodeJs:

import pkg from 'bitcore-lib'

const { PrivateKey, Networks } = pkg
const privateKey = new PrivateKey(Networks['livenet'])
const myObject = {
    privateKey: privateKey,
    P2PKHAddress: privateKey.toAddress(),
    publicKey: privateKey.toPublicKey(),
    wif: privateKey.toWIF()
}

It is possible to use publicKey to encrypt a message and decrypt with privateKey?

const encryptedText = encrypt('Hello', publicKey)
const decryptedText = decrypt(encryptedText, privateKey)

assert decryptedText === 'Hello'

Cartucho
  • 113
  • 5

1 Answers1

0

After some research I found that the ECIES algorithm is what I was looking for. First, I tried the library bitcore-ecies but seems to be deprecated, old and buggy. So I pick ecies-lite. This is the result:

import pkg from 'bitcore-lib'
import * as ecies from 'ecies-lite'

const { PrivateKey, Networks } = pkg

function generateKeys () {
  const network = Networks.livenet
  const privateKey = new PrivateKey(Networks[network])
  return {
    privateKey: privateKey,
    P2PKHAddress: privateKey.toAddress(),
    publicKey: privateKey.toPublicKey(),
    wif: privateKey.toWIF()
  }
}

function main() {
  const result = generateKeys()
  const body = ecies.encrypt(
    result.publicKey.toBuffer(),
    Buffer.from('This message is for demo purpose')
  )
  console.log(body)
  const message = ecies.decrypt(result.privateKey.toBuffer(), body)
  console.log(message.toString())
}

main()

Cartucho
  • 113
  • 5