MyMonero provides a useful JavaScript library (mymonero-core-js
) for dealing with this sort of thing.
Here is a code snippet that shows how to encrypt/decrypt a payment id using this bit of code from mymonero-core-js
.
const mm = require('mymonero-core-js').monero_utils
const viewKey = mm.random_keypair()
const txKey = mm.random_keypair()
const paymentId = 'badc0ffeefabcafe'
const INTEGRATED_ID_SIZE = 8
const ENCRYPTED_PAYMENT_ID_TAIL = 0x8d
// If you have the private tx key and public view key
const pidKey = mm.cn_fast_hash(
mm.generate_key_derivation(viewKey.pub, txKey.sec) +
ENCRYPTED_PAYMENT_ID_TAIL.toString(16)
).slice(0, INTEGRATED_ID_SIZE * 2)
// If you have the private view key and public tx key
const pidKey2 = mm.cn_fast_hash(
mm.generate_key_derivation(txKey.pub, viewKey.sec) +
ENCRYPTED_PAYMENT_ID_TAIL.toString(16)
).slice(0, INTEGRATED_ID_SIZE * 2)
// Assert that the pidKeys are equal
console.log((pidKey === pidKey2)
? 'pidKeys are equal (expected)'
: 'pidKeys are not equal (unexpected)')
// Encrypt Payment ID
const encryptedPaymentId = mm.hex_xor(paymentId, pidKey)
console.log('Encrypted: ' + encryptedPaymentId)
// Decrypt Payment ID
const decryptedPaymentId = mm.hex_xor(encryptedPaymentId, pidKey)
console.log('Decrypted: ' + decryptedPaymentId)
// Assert that the original and decrypted payment ids are equal
console.log((decryptedPaymentId === paymentId)
? 'Successful Decryption!'
: 'Unsuccessful Decryption')
Should provide an output similar to:
pidKeys are equal (expected)
Encrypted: cfc3f2120b7db7c0
Decrypted: badc0ffeefabcafe
Successful Decryption!
Hope this helps!