0

I am using the below code to hash a data and it's working fine. Took the code from crypto website

const crypto = require('crypto');

const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
                   .update('I love cupcakes')
                   .digest('hex');
console.log(hash);
// Prints:
//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e

My problem is how to reverse this? How can I un-hash a data to a normal text again?

Syn3sthete
  • 4,151
  • 3
  • 23
  • 41
  • 3
    You don't. That's what a hash is meant for. You're probably looking for *encryption*. – Rob Jul 25 '17 at 08:08
  • Possible duplicate of [Fundamental difference between Hashing and Encryption algorithms](https://stackoverflow.com/questions/4948322/fundamental-difference-between-hashing-and-encryption-algorithms) – Artjom B. Jul 25 '17 at 17:06

1 Answers1

3

A hash cannot be reversed... You need a Cipher for that. Here's my little, very simplistic, secret class.

import crypto from 'crypto'
let Secret = new (function (){
    "use strict";

    let world_enc = "utf8"
    let secret_enc = "hex";
    let key = "some_secret_key";

    this.hide = function(payload){
        let cipher = crypto.createCipher('aes128', key);
        let hash = cipher.update(payload, world_enc, secret_enc);
        hash += cipher.final(secret_enc);
        return hash;
    };
    this.reveal = function(hash){
        let sha1 = crypto.createDecipher('aes128', key);
        let payload = sha1.update(hash, secret_enc, world_enc);
        payload += sha1.final(world_enc);
        return payload;
    }
});

export {Secret};
Salketer
  • 14,263
  • 2
  • 30
  • 58