OverviewFilesCommitsIssuesDocsReleasesPeers

holepunchto-deps / @holepunchto / keet-core / lib / core / crypto.js

1 lines · javascript ref:
const r=require("sodium-native");function o(o){r.sodium_memzero(o),r.sodium_free(o)}module.exports={encryptEntropy:function(t,e){const s=r.sodium_malloc(r.crypto_secretbox_KEYBYTES),_=r.sodium_malloc(Buffer.byteLength(e,"utf-8"));if(_.write(e,"utf-8"),t.byteLength<32)throw r.sodium_memzero(_),r.sodium_memzero(t),new Error("Phrase is too small");const c=r.crypto_pwhash_SALTBYTES,a=r.crypto_secretbox_NONCEBYTES,y=r.crypto_secretbox_MACBYTES,p=Buffer.alloc(1+c+a+t.length+y);p[0]=1;const n=p.subarray(1,1+c),u=p.subarray(1+c,1+c+a),h=p.subarray(1+c+a);r.randombytes_buf(n),r.randombytes_buf(u);try{r.crypto_pwhash(s,_,n,r.crypto_pwhash_OPSLIMIT_INTERACTIVE,r.crypto_pwhash_MEMLIMIT_INTERACTIVE,r.crypto_pwhash_ALG_ARGON2ID13),r.crypto_secretbox_easy(h,t,u,s)}finally{o(s),o(_),o(t)}return p},decryptEntropy:function(t,e){const s=r.sodium_malloc(r.crypto_secretbox_KEYBYTES),_=r.sodium_malloc(Buffer.byteLength(e),"utf-8");_.write(e,"utf-8");const c=r.crypto_pwhash_SALTBYTES,a=r.crypto_secretbox_NONCEBYTES,y=r.crypto_secretbox_MACBYTES;if(1!==t[0])throw new Error("Version mismatch");const p=t.subarray(1,1+c),n=t.subarray(1+c,1+c+a),u=t.subarray(1+c+a),h=Buffer.alloc(u.length-y);try{if(r.crypto_pwhash(s,_,p,r.crypto_pwhash_OPSLIMIT_INTERACTIVE,r.crypto_pwhash_MEMLIMIT_INTERACTIVE,r.crypto_pwhash_ALG_ARGON2ID13),!r.crypto_secretbox_open_easy(h,u,n,s))throw new Error("Decryption failed – bad password or corrupted data")}finally{o(s),o(_)}return h},free:o};