Created
          June 10, 2015 14:33 
        
      - 
      
- 
        Save mykiimike/eae214a32f81c144950e to your computer and use it in GitHub Desktop. 
    Nodejs crypto good practice AES-CBC + SHA256 + HMAC
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // var cryptoKey = raw SHA256 Hash | |
| function decypherPayload(payload) { | |
| /* inputs */ | |
| var t = payload.split(","); | |
| var C = t[0], | |
| IV = t[1], | |
| Hm = t[2]; | |
| /* compute hmac */ | |
| var c = crypto.createHmac("sha256", cryptoKey); | |
| c.update(C, "ascii"); | |
| c.update(IV, "ascii"); | |
| c.update(cryptoKey, 'binary'); | |
| var hmac = c.digest("hex"); | |
| /* integrity control */ | |
| if(hmac != Hm) | |
| return({ error: true, message: "Bad HMAC control" }); | |
| try { | |
| var dcp = crypto.createDecipheriv("aes-256-cbc", cryptoKey, new Buffer(IV, "hex")); | |
| var pl = dcp.update(payload, 'hex'); | |
| pl += dcp.final("ascii"); | |
| } catch(e) { | |
| return({ error: true, message: "Decipher: "+e.message }); | |
| } | |
| try { | |
| js = JSON.parse(pl); | |
| } catch(e) { | |
| return({ error: true, message: "JSON error: "+e.message }); | |
| } | |
| return({ error: false, data: js }); | |
| } | |
| function cypherPayload(data) { | |
| var iv = crypto.randomBytes(16); | |
| var c = crypto.createCipheriv("aes-256-cbc", cryptoKey, iv); | |
| data.ip = ip; | |
| var pl = c.update(JSON.stringify(data), 'utf8', "hex"); | |
| pl += c.final("hex"); | |
| iv = iv.toString("hex"); | |
| c = crypto.createHmac("sha256", cryptoKey); | |
| c.update(pl, "ascii"); | |
| c.update(iv, "ascii"); | |
| c.update(cryptoKey, 'binary'); | |
| var hmac = c.digest("hex"); | |
| return(pl+","+iv+","+hmac); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment