-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtemcrypt.min.js
2 lines (2 loc) · 12.7 KB
/
temcrypt.min.js
1
2
/*! temcrypt v1.0.0 (LAST UPDATE: August 15, 2023) | Copyright (c) 2023 by Jose Pino, @jofpin | https://github.com/jofpin/temcrypt */
const temcrypt=(()=>{const e={core:{credits:{AUTHOR:"Jose Pino",VERSION:"1.0.0"},date:{START:new Date("August 15, 2023 00:00:00"),CURRENT:new Date,LAST_UPDATE:new Date("August 15, 2023")},time:{DIGIT_UPGRADE_YEARS:1.8,HOUR_BOOST_PER_MONTH:6},PREFIX_STRING:"T3M",SUFFIX_EXTENSION:".trypt",MINIMUM_BYTE_SIZE:859,IMPORTANT_ERRORS:{DECRYPTION_EXCEEDED:{code:420,message:"Decryption time limit exceeded"},DECRYPTION_FAILED:{code:444,message:"Decryption failed"},NO_DATA:{code:777,message:"No data provided"},NO_TEM:{code:859,message:"The provided string is not a valid temcrypt encrypted string"}}},nodeOrBrowser:function(){const e="undefined"==typeof window;let t,r;if(e){try{t=require("crypto-js")}catch(e){!function(e){try{require("child_process").execSync("npm -v")}catch(e){throw console.error("npm is not installed. You must install it before running this script."),e}try{console.log("\n"),console.log("TEMCRYPT: SELF INSTALLATION OF DEPENDENCIES"),console.log("----------------"),console.log(`> Installing TEM dependencies: ${e}...`),console.log("--"),require("child_process").execSync(`npm install ${e}`),console.log(`> ${e} installed.`),console.log("----------------"),console.log("| Now you can successfully use TEM!"),console.log("----------------")}catch(t){throw console.error(`Failed to install ${e}. Please install it manually by running: npm install ${e}`),t}}("crypto-js"),t=require("crypto-js")}try{r=require("fs")}catch(e){r=null}}else{if(window.CryptoJS)t=window.CryptoJS;else{const e=new XMLHttpRequest;if(e.open("GET","https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js",!1),e.send(null),200!==e.status)throw new Error("Could not load CryptoJS");{const r=document.createElement("script");r.text=e.responseText,document.head.appendChild(r),t=window.CryptoJS}}r=null}return{mode:e?"NODE":"BROWSER",CryptoJS:t,fs:r}},credits:function(){console.log(`\ntemcrypt v${this.core.credits.VERSION} is being used!\n---\n> Author: ${this.core.credits.AUTHOR}\n> Release Date: ${this.core.date.START.toLocaleDateString()}\n> Last Update: ${this.core.date.LAST_UPDATE.toLocaleDateString()}\n--------------------------\n- Base Time: ${this.baseTime().toString()}\n--------------------------\n- Execution Mode: ${this.nodeOrBrowser().mode}\n---\n`)},baseTime:function(){let e=new Date,t=e-this.core.date.START,r=Math.floor(t/36e5%24),s=Math.floor(t/6e4%60),i=Math.floor(t/1e3%60),n=e.getMonth()-this.core.date.START.getMonth()+12*(e.getFullYear()-this.core.date.START.getFullYear());return r+=Math.floor(n/this.core.time.HOUR_BOOST_PER_MONTH),{hours:("0"+r).slice(-2),minutes:("0"+s).slice(-2),seconds:("0"+i).slice(-2),toString:function(){return this.hours+":"+this.minutes+":"+this.seconds}}},helper:function(e){const s=function(e){return t.SHA256(e).toString()};return{sha256:s,enc256:function(r){return t.AES.encrypt(e,r).toString()},dec256:function(r){return t.AES.decrypt(e,r).toString(t.enc.Utf8)},splitKey:function(e){return{one:s(e.substring(0,e.length/2)),two:s(e.substring(e.length/2))}},readerFile:function(e){return r.readFileSync(e).toString("base64")},writerFile:function(e,t){const s=Buffer.from(t,"base64");r.writeFileSync(e,s)},outputFilename:function(e,t){let s=e.replace(t,"");const i=s.includes(".")?s.slice(s.lastIndexOf(".")):"",n=s.slice(0,-1!==s.lastIndexOf(".")?s.lastIndexOf("."):s.length),o=/\((\d+)\)$/;let a=1,c=n;if(o.test(n)){const e=n.match(o);a=parseInt(e[1]),c=n.replace(o,"")}for(s=`${c} (${a})${i}`;r.existsSync(s);)a++,s=`${c} (${a})${i}`;return s},calculateBytes:function(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024)),r=e/Math.pow(1024,t);return`${r%1==0?r.toFixed(0):r.toFixed(2)} ${["Bytes","KB","MB","GB"][t]}`}}},shuffle:function(e){if(!Array.isArray(e)&&"string"!=typeof e)throw new Error("The value must be a array or an string");return Array.isArray(e)?e.sort((()=>Math.random()-.5)).join(""):e.split("").sort((()=>Math.random()-.5)).join("")},shadowToken:function(){const e=this.helper().sha256(t.lib.WordArray.random(256));return this.shuffle(e)},createKey:function(e,t,r){let s=[e,t+this.baseTime().hours+this.baseTime().minutes,r],i=new Set,n=s.filter((e=>!i.has(e)&&(i.add(e),!0)));return this.shuffle(n)},hexGenerator:function(e){const t="0123456789abcdef";let r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(16*Math.random()));return r},byteLength:function(e){return"BROWSER"===this.nodeOrBrowser().mode?new Blob([e]).size:Buffer.byteLength(e,"utf-8")},increaseDigit:function(){let e=1+Math.floor((this.core.date.CURRENT.getFullYear()-this.core.date.START.getFullYear())/this.core.time.DIGIT_UPGRADE_YEARS);return{value:Math.pow(10,e),saltIncrease:Math.floor(Math.random()*Math.pow(10,e)).toString()}},multiLayer:function(e,r){const s=this.helper(JSON.stringify(e)).enc256(this.helper().splitKey(r).one),i=this.helper(s).enc256(this.helper().splitKey(r).two),n=t.enc.Utf8.parse(i).toString(t.enc.Hex).split("").reverse().join(""),o=n.substring(0,this.baseTime().seconds);return n.substring(n.length-this.baseTime().seconds)+n.substring(this.baseTime().seconds,n.length-this.baseTime().seconds)+o},_encryptableString:function(e,t,r){if(!e&&!t)throw new Error("Both string and key are required");if(!e)throw new Error("string cannot be empty");t=t||this.shadowToken();const s=this.shadowToken(),i=this.helper(e).enc256(s+this.baseTime().minutes),n=this.byteLength(e),o=this.helper().calculateBytes(n);let a="";if(r){if("number"!=typeof r)throw new Error("extraBytes must be a number");a=this.hexGenerator(r)}const c={tem:{string:i,token:s,extraBytes:a,creationDate:this.core.date.CURRENT.toLocaleDateString(),lastDecryptionDate:""}},l=this.createKey(this.shuffle(this.core.PREFIX_STRING),t,this.increaseDigit().saltIncrease),h=this.multiLayer(c,l),d=this.core.PREFIX_STRING+h,u=this.helper().sha256(d),y=this.byteLength(d),f=this.helper().calculateBytes(y),g=(y-n)/n*100;return{hash:u,mainKey:t,timeKey:this.baseTime().hours+":"+this.baseTime().minutes,dataString:d,dataSizes:{exposed:o,encrypted:f,percentageIncrease:g.toFixed(2)+"%"},extraBytes:a}},_decryptableString:function(e,r){if(!e||!r)throw new Error("Both encrypted data and key are required");let s=this.increaseDigit().value;for(let i=0;i<=60;i++)for(let n=0;n<s;n++)for(let s=0;s<=60;s++)for(let s=0;s<=6;s++){let s=this.createKey(this.shuffle(this.core.PREFIX_STRING),r,n.toString()),o=e.substring(this.core.PREFIX_STRING.length),a=o.substring(0,i),c=(o.substring(o.length-i)+o.substring(i,o.length-i)+a).split("").reverse().join("");if((new Date-this.core.date.CURRENT)/1e3>60||"00"===this.baseTime().seconds)return{status:!1,error_code:this.core.IMPORTANT_ERRORS.DECRYPTION_EXCEEDED.code,message:this.core.IMPORTANT_ERRORS.DECRYPTION_EXCEEDED.message};try{let e=this.helper(t.enc.Hex.parse(c).toString(t.enc.Utf8)).dec256(this.helper().splitKey(s).two),i=this.helper(e).dec256(this.helper().splitKey(s).one),n=JSON.parse(i),o=n.tem.string,a=n.tem.token+this.baseTime().minutes,l=this.helper(o).dec256(a);n.tem.lastDecryptionDate=this.core.date.CURRENT.toDateString();const h=this.createKey(this.shuffle(this.core.PREFIX_STRING),r,this.increaseDigit().saltIncrease),d=this.multiLayer(n,h),u=this.core.PREFIX_STRING+d;return{status:!0,hash:this.helper().sha256(u),dataString:l,updatedEncryptedData:u,creationDate:n.tem.creationDate,lastDecryptionDate:n.tem.lastDecryptionDate}}catch(e){continue}}return{status:!1,error_code:this.core.IMPORTANT_ERRORS.DECRYPTION_FAILED.code,message:this.core.IMPORTANT_ERRORS.DECRYPTION_FAILED.message}},_encryptableFiles:function(e,t,r){if("BROWSER"===this.nodeOrBrowser().mode)return void console.warn("WARNING: This property is only supported in NODE.js and not in the Browser");if("string"==typeof e&&(e=[e]),!Array.isArray(e))throw new Error("Must be an array or a string");if("string"==typeof t&&(t=Array(e.length).fill(t)),!Array.isArray(t))throw new Error("Must be an array or a string");if(e.length!==t.length)throw new Error("File(s) and mainKey(s) must have the same length");const s=e.map(((e,s)=>{const i=this.helper().readerFile(e),n=this._encryptableString(i,t[s],r),o=e+this.core.SUFFIX_EXTENSION;return this.nodeOrBrowser().fs.writeFileSync(o,n.dataString),{fileName:o,mainKey:t[s],timeKey:n.timeKey}}));return{encryptedData:s,totalFiles:s.length}},_decryptableFiles:function(e,t){if("BROWSER"===this.nodeOrBrowser().mode)return void console.warn("WARNING: This property is only supported in NODE.js and not in the Browser");if("string"==typeof e&&(e=[e]),!Array.isArray(e))throw new Error("Must be an array or a string");if("string"==typeof t&&(t=Array(e.length).fill(t)),!Array.isArray(t))throw new Error("Must be an array or a string");const r=[],s=[];for(let i=0;i<e.length;i++){const n=e[i],o=t[i],a=this.nodeOrBrowser().fs.readFileSync(n,"utf-8");if(a.startsWith(this.core.PREFIX_STRING)||this.byteLength(a)<this.core.MINIMUM_BYTE_SIZE)try{const e=this._decryptableString(a,o),t=this.helper().outputFilename(n,this.core.SUFFIX_EXTENSION);this.helper().writerFile(t,e.dataString),this.nodeOrBrowser().fs.writeFileSync(n,e.updatedEncryptedData,"utf-8");const s=Buffer.from(e.dataString,"base64").toString("utf-8");r.push({fileName:t,creationDate:e.creationDate,lastDecryptionDate:e.lastDecryptionDate,dataString:s})}catch{s.push({fileName:n,message:"Error during decryption, the mainKey or timeKey may be incorrect"});continue}else s.push({fileName:n,message:`Invalid temcrypt file: ${n}`})}return{status:r.length>0,message:r.length>0?"Successfully decrypted the valid temcrypt files.":"No valid temcrypt files found.",decryptedData:r,totalFiles:r.length,invalidFiles:s}},encrypt:function(e){if(!e)throw new Error("Provides the parameters");if(!e.dataString&&!e.dataFiles)return{status:!1,error_code:this.core.IMPORTANT_ERRORS.NO_DATA.code,message:this.core.IMPORTANT_ERRORS.NO_DATA.message};const t=e.extraBytes||0;if(e.dataString)return this._encryptableString(e.dataString,e.mainKey,t);if(e.dataFiles)return this._encryptableFiles(e.dataFiles,e.mainKey,t);throw new Error("Unexpected error: dataString or dataFiles must be provided")},decrypt:function(e){if(!e)throw new Error("Provides the parameters");if(!e.dataString&&!e.dataFiles)return{status:!1,error_code:this.core.IMPORTANT_ERRORS.NO_DATA.code,message:this.core.IMPORTANT_ERRORS.NO_DATA.message};if(e.dataString){return e.dataString.startsWith(this.core.PREFIX_STRING)||this.byteLength(e.dataString)<this.core.MINIMUM_BYTE_SIZE?this._decryptableString(e.dataString,e.mainKey):{status:!1,error_code:this.core.IMPORTANT_ERRORS.NO_TEM.code,message:this.core.IMPORTANT_ERRORS.NO_TEM.message}}if(e.dataFiles)return this._decryptableFiles(e.dataFiles,e.mainKey);throw new Error("Unexpected error: dataString or dataFiles must be provided")},utils:function(e){if(!e)throw new Error("Provide the parameters");if(e.changeKey){const{dataFiles:t,dataString:r,mainKey:s,newKey:i}=e.changeKey;if(t){const e=this.nodeOrBrowser().fs.readFileSync(t,"utf-8"),r=this._decryptableString(e,s);if(r.status){const e=this._encryptableString(r.dataString,i);return this.nodeOrBrowser().fs.writeFileSync(t,e.dataString,"utf-8"),{status:!0,message:"mainKey updated successfully for the file."}}return{status:!1,message:"Error updating mainKey for the file."}}if(r){const e=this._decryptableString(r,s);if(e.status){return{status:!0,message:"mainKey updated successfully for the string.",newEncryptedString:this._encryptableString(e.dataString,i).dataString}}return{status:!1,message:"Error updating mainKey for the string."}}throw new Error("dataFiles or dataString must be provided")}if(e.check){const{dataFiles:t,dataString:r}=e.check;if(t){const e=this.nodeOrBrowser().fs.readFileSync(t,"utf-8"),r=e.startsWith(this.core.PREFIX_STRING)&&this.byteLength(e)>=this.core.MINIMUM_BYTE_SIZE,s=r?this.nodeOrBrowser().fs.statSync(t).size:0;return{status:r,message:r?"Is a valid temcrypt file.":"Invalid temcrypt file.",fileSize:this.helper().calculateBytes(s)}}if(r){const e=r.startsWith(this.core.PREFIX_STRING)&&this.byteLength(r)>=this.core.MINIMUM_BYTE_SIZE,t=e?r.length:0;return{status:e,message:e?"Is a valid temcrypt string.":"Invalid temcrypt string.",stringSize:this.helper().calculateBytes(t)}}throw new Error("dataFiles or dataString must be provided")}if(e.verify){const{hash:t,dataFiles:r,dataString:s}=e.verify;if(r){const e=this.nodeOrBrowser().fs.readFileSync(r,"utf-8"),s=this.helper().sha256(e)===t;return{status:s,message:s?"Valid Hash for the file (temcrypt)":"Invalid Hash for the file (temcrypt)"}}if(s){const e=this.helper().sha256(s)===t;return{status:e,message:e?"Valid Hash for the encrypted string (temcrypt)":"Invalid Hash for the encrypted string (temcrypt)"}}throw new Error("dataFiles or dataString must be provided")}}},{CryptoJS:t,fs:r}=e.nodeOrBrowser();return e.credits(),"undefined"!=typeof module&&void 0!==module.exports?module.exports=e:window.temcrypt=e,e})();