joplin-notes/joplin notion extension/Web Development/Extras/Encryption.md
2026-11-04 00:33:23 +05:30

17 KiB

  • RC4

    • NodeJs

       const rc4 = require("arc4");
       const fs=require('fs')
      
       const data=fs.readFileSync('stacer.jpeg')
      
       const uData=new Uint8Array(data)
      
       const key = "123456789123456789";
      
          // const data = e.target.result;
          const fSize = data.byteLength;
      
          const cipher = rc4("arc4", key);
      
          // const enc = cipher.encodeBuffer(uData);
          const enc = cipher.encodeArray(uData);
          console.log("🚀 ~ file: script.js:76 ~ fr.addEventListener ~ enc:", enc);
          // const dec = cipher.decodeBuffer(enc);
          const dec = cipher.decodeArray(enc);
          console.log("🚀 ~ file: script.js:78 ~ fr.addEventListener ~ dec:", dec);
      
          const decBuffer=Buffer.from(dec)
          fs.writeFileSync('stacerdec.jpeg',decBuffer)
      
    • Javascript(Client side)

      // Function to read a file and return its content as a promise
      function readFile(fileInput) {
        return new Promise((resolve, reject) => {
          const file = fileInput.files[0];
          if (!file) {
            reject("No file selected");
            return;
          }
          const reader = new FileReader();
          reader.onload = (event) => {
            resolve(event.target.result);
          };
          reader.readAsArrayBuffer(file);
        });
      }
      
      // Function to save encrypted data to a file
      function saveEncryptedFile(encryptedData) {
        const blob = new Blob([encryptedData]);
        const a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = "encrypted_file.enc";
        a.click();
      }
      
      // Function to save decrypted data to a file
      function saveDecryptedFile(decryptedData) {
        const blob = new Blob([decryptedData]);
        const a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = "decrypted_file.txt"; // Change the file extension as needed
        a.click();
      }
      
      // Function to encrypt a file using ARC4
      async function encryptFile() {
        const fileInput = document.getElementById("fileInput");
        const fileContent = await readFile(fileInput);
        const rc4 = ARC4("your_secret_key");
        const encryptedData = rc4.encrypt(new Uint8Array(fileContent));
        saveEncryptedFile(encryptedData);
      }
      
      // Function to decrypt an encrypted file using ARC4
      async function decryptFile() {
        const encryptedFileInput = document.getElementById("encryptedFileInput");
        const encryptedContent = await readFile(encryptedFileInput);
        const rc4 = ARC4("your_secret_key");
        const decryptedData = rc4.decrypt(new Uint8Array(encryptedContent));
        saveDecryptedFile(decryptedData);
      }
      
  • AES

    // merging splitted Uint8arrays to single one
     const mergeTo1D=(uarrays)=>{
     	if(uarrays.length===0)
     	{
     		return []
     	}
     	const sum=0
     	for(let urray of urray)
     	{
     		sum+=urray/length
     	}
    
     	const mergedArray= new Uint8Array(sum)
    
     	mergedArray.set(uarrays[0],0)
    
     	for(let i=1;i<uarrays.length;i++)
     	{
     		mergedArray.set(uarrays[i],uarrays[i-1].length)	
     	}
    
     	return mergedArray
    
     }
    
    • nodejs
      Streamlined encyption using native crypto module of nodejs
       
      encryption.js

      const fs = require("fs");
      const crypto = require("crypto");
      const CryptoJS = require("crypto-js");
      require("crypto-js/aes");
      
      // const fileName='redis-stack-server-7.2.0-v4-x86_64.AppImage'
      // const fileName='Joplin-2.12.18.AppImage'
      // const fileName='stacer.jpeg'
      const fileName='Black.Mirror.S06E01.Joan.Is.Awful.720p.10Bit.Hindi.English.Esubs.MoviesMod.org.mkv'
      
      // Input and output file paths
      const inputFile = fileName; // Replace with your input file path
      const outputFile = `${fileName}.enc`; // Replace with your output file path
      
      // Encryption parameters
      // const key = "YourSecretKey"; // Replace with your encryption key
      const key = crypto.randomBytes(32);
      const iv = crypto.randomBytes(16); // Initialization Vector (IV)
      
      
      fs.writeFileSync('key.bin',key);
      fs.writeFileSync('iv.bin',iv);
      
      // console.log('key: ',key.toString())
      // console.log('iv: ',iv.toString())
      
      // Create a readable stream for the input file and a writable stream for the output file
      const inputStream = fs.createReadStream(inputFile);
      const outputStream = fs.createWriteStream(outputFile);
      
      // Encrypt and write the file in chunks
      const encryptionStream = crypto.createCipheriv("aes-256-cbc", Buffer.from(key), iv);
      inputStream.pipe(encryptionStream).pipe(outputStream);
      
      // Handle events and errors
      inputStream.on("error", (err) => console.error("Input Stream Error:", err));
      outputStream.on("error", (err) => console.error("Output Stream Error:", err));
      outputStream.on("finish", () => console.log("Encryption completed."));
      
      // Optionally, you can handle stream close events as well
      inputStream.on("close", () => console.log("Input stream closed."));
      outputStream.on("close", () => console.log("Output stream closed."));
      

       
      decryption.js

      const fs = require("fs");
      const crypto = require("crypto");
      const CryptoJS = require("crypto-js");
      require("crypto-js/aes");
      
      
      // const fileName='Joplin-2.12.18.AppImage'
      // const fileName='stacer.jpeg'
      const fileName='Black.Mirror.S06E01.Joan.Is.Awful.720p.10Bit.Hindi.English.Esubs.MoviesMod.org.mkv'
      
      // Input and output file paths
      
      const inputFile = `${fileName}.enc`; // Replace with your output file path
      const outputFile = `${fileName}.dec`; // Replace with your output file path
      
      
      
      
      
      const key=fs.readFileSync('key.bin');
      const iv=fs.readFileSync('iv.bin');
      
      const inputStream = fs.createReadStream(inputFile);
      const outputStream = fs.createWriteStream(outputFile);
      
      // Decrypt and write the file in chunks
      const decryptionStream = crypto.createDecipheriv("aes-256-cbc", Buffer.from(key), iv);
      inputStream.pipe(decryptionStream).pipe(outputStream);
      
      // Handle events and errors
      inputStream.on("error", (err) => console.error("Input Stream Error:", err));
      outputStream.on("error", (err) => console.error("Output Stream Error:", err));
      outputStream.on("finish", () => console.log("Decryption completed."));
      
      // Optionally, you can handle stream close events as well
      inputStream.on("close", () => console.log("Input stream closed."));
      outputStream.on("close", () => console.log("Output stream closed."));
      
    • client side javascript(browser)
       
      encryption.html

      <!DOCTYPE html>
      <html>
      <head>
          <title>Large File Encryption</title>
      </head>
      <body>
          <input type="file" id="fileInput" >
          <button id="encryptButton">Encrypt</button>
          <a id="downloadLink" style="display: none" download="encrypted-file.txt">Download Encrypted File</a>
      
          <script>
              const algorithmName="AES-GCM"
              // const algorithmName="AES-CBC"
              document.getElementById("encryptButton").addEventListener("click", async () => {
                  const fileInput = document.getElementById("fileInput");
                  const file = fileInput.files[0];
                  if (!file) {
                      alert("Please select a file.");
                      return;
                  }
      
                  const chunkSize = 1024 * 1024; // 1 MB chunks
                  const key = await window.crypto.subtle.generateKey({ name: algorithmName, length: 256 }, true, ["encrypt","decrypt"]);
      
                  const keyData = await window.crypto.subtle.exportKey('jwk', key);
      
      // Create a data blob with the key data
      const keyBlob = new Blob([JSON.stringify(keyData)], { type: 'application/json' });
      
      // Create a download link for the key
      const keyUrl = URL.createObjectURL(keyBlob);
      const downloadLink = document.createElement('a');
      downloadLink.href = keyUrl;
      downloadLink.download = 'encryption-key.json';
      downloadLink.click();
      
      const iv=new Uint8Array(16);
      
      const ivBlob= new Blob([JSON.stringify(iv)], { type: 'application/json' })
      const ivUrl=URL.createObjectURL(ivBlob)
      const ivdownloadlink=document.createElement('a')
      ivdownloadlink.href= ivUrl
      ivdownloadlink.download ='encryption-iv.json'
      ivdownloadlink.click()
      
      
      
      
                  const reader = new FileReader();
                  const fileData = [];
                  let offset = 0;
      
                  reader.onload = async function () {
      
                      // const algorithm= { name: "AES-GCM", iv }
                      const algorithm= { name: algorithmName, iv }
                      console.log('algorithm: ',algorithm)
                      const chunk = new Uint8Array(reader.result);
                      const encryptedChunk = await window.crypto.subtle.encrypt(
                          algorithm,
                          key,
                          chunk
                      );
                      // const encryptedChunk=chunk
                      fileData.push(encryptedChunk);
                      offset += chunk.length;
      
                      if (offset < file.size) {
                          readSlice(offset);
                      } else {
                          // All chunks are encrypted; combine them and provide a download link.
                          const encryptedData = new Blob(fileData, { type: file.type });
                          const url = URL.createObjectURL(encryptedData);
                          const downloadLink = document.getElementById("downloadLink");
                          downloadLink.href = url;
                          downloadLink.style.display = "block";
                          console.log('finished')
                      }
                  };
      
                  function readSlice(offset) {
                      const slice = file.slice(offset, offset + chunkSize);
                      reader.readAsArrayBuffer(slice);
                  }
      
                  readSlice(0);
              });
          </script>
      </body>
      </html>
      

       
      decryption.js

      <!DOCTYPE html>
      <html>
      <head>
        <title>File Decryption</title>
      </head>
      <body>
        <h1>File Decryption</h1>
      
        <!-- Input for the encrypted file -->
        <input type="file" id="encryptedFileInput"  />
      
        <!-- Input for the encryption key (as JSON) -->
        <input type="file" id="keyInput" accept=".json" />
      
        <!-- Input for the IV (as JSON) -->
        <input type="file" id="ivInput" accept=".json" />
      
        <button id="decryptButton">Decrypt</button>
      
        <a id="downloadLink" style="display: none;">Download Decrypted File</a>
      
        <script>
          document.getElementById("decryptButton").addEventListener("click", async () => {
            // Get the encrypted file
            const encryptedFileInput = document.getElementById("encryptedFileInput");
            const encryptedFile = encryptedFileInput.files[0];
      
            // Get the encryption key and IV (as JSON)
            const keyInput = document.getElementById("keyInput");
            const ivInput = document.getElementById("ivInput");
      
            const keyFile = keyInput.files[0];
            const ivFile = ivInput.files[0];
      
            if (!encryptedFile || !keyFile || !ivFile) {
              alert("Please select the encrypted file, key, and IV.");
              return;
            }
      
            // Read the key and IV as JSON
            const keyData = await keyFile.text();
            const ivData = await ivFile.text();
      
            // Convert the JSON data to JavaScript objects
            const keyObj = JSON.parse(keyData);
            const iv = JSON.parse(ivData);
      
            console.log('iv: ', new Uint8Array(iv))
      
      //       const importAlgorithm = {
      //   name: "AES-GCM",
      //   namedCurve: "P-256", // Adjust this curve based on your JWK.
      // }
      
      
      const algorithmName="AES-GCM";
      // const algorithmName="AES-CBC";
      
      // const importAlgorithm = {
      //   name: "AES-GCM"
      // };
      
      const importAlgorithm = {
        name: algorithmName
      };
      
      // const ivSize=12
      const ivSize=16
      
      
      const keyUsage = ["encrypt","decrypt"];
      
            const key = await crypto.subtle.importKey("jwk", keyObj, importAlgorithm, false, keyUsage)
      
            // 1 mb( size while encrypting + 12 bytes(iv size) ) 
            const chunkSize= (1024*1024)+ivSize
      
      
             const reader = new FileReader();
                  const fileData = [];
                  let offset = 0;
      
              reader.onload = async function () {
                console.log('chunk loaded')
                      const chunk = new Uint8Array(reader.result);
                      const decryptedChunk = await window.crypto.subtle.decrypt(
                          { name: algorithmName, iv: new Uint8Array(ivSize) },
                          key,
                          chunk
                      );
                      fileData.push(decryptedChunk);
                      offset += chunk.length;
      
                      if (offset < encryptedFile.size) {
                          readSlice(offset);
                      } else {
                          // All chunks are encrypted; combine them and provide a download link.
                          const decryptedData = new Blob(fileData, { type: encryptedFile.type });
                          const url = URL.createObjectURL(decryptedData);
                          const downloadLink = document.getElementById("downloadLink");
                          downloadLink.href = url;
                          downloadLink.download="someting.dec"
                          downloadLink.style.display = "block";
                          downloadLink.click()
                          console.log('finished')
                      }
                  };
      
                  function readSlice(offset) {
                      const slice = encryptedFile.slice(offset, offset + chunkSize);
                      reader.readAsArrayBuffer(slice);
                  }
      
                  readSlice(0);
      
      
      
      
      
      
      
      
      
      
          //   // Read the encrypted file
          //   const encryptedData = await encryptedFile.arrayBuffer();
      
          //   // Decrypt the file using the Web Crypto API
          //   try {
          //     const decryptedData = await window.crypto.subtle.decrypt(
          //       {
          //         name: "AES-GCM",
          //         iv : new Uint8Array(12)
          //       },
          //       key,
          //       encryptedData
          //     );
      
          //     // Create a Blob from the decrypted data
          //     const decryptedBlob = new Blob([decryptedData]);
      
          //     // Create a download link for the decrypted file
          //     const downloadLink = document.getElementById("downloadLink");
          //     downloadLink.href = URL.createObjectURL(decryptedBlob);
          //     downloadLink.download = "decrypted_file.txt"; // Set the desired file name
          //     downloadLink.style.display = "block";
          //   } catch (error) {
          //     console.error("Decryption error:", error);
          //     alert("Decryption failed. Please check the key and IV.");
          //   }
          });
        </script>
      </body>
      </html>