CryptoJS corrupts PNG image after decryption

Context

The first half of the project: Encrypt an image through The front-end using CryptoJS, then ZIP the encryption results and push to the server.
The other half: Allow users download the image they uploaded unzipped and decrypted from the server. Zipping happens using the back-end, but Encryption, Decryption, and Unzipping are done on the front-end.

This is the encryption code:

// Upload File upon clicking on "Upload" Button
var upload_button = document.getElementById('upload-button');
upload_button.addEventListener('click', uploadFile);

function uploadFile() {
    var file = fileupload.files[0];
    var reader = new FileReader();
    var key = document.getElementById("enc_key").value;
    var fileEnc = null;

    reader.onload = function() {
        var wordArray = CryptoJS.lib.WordArray.create(reader.result);
        var encrypted = CryptoJS.AES.encrypt(wordArray, key).toString();
        var fileEnc = new Blob([encrypted]);
        encryptAndUpload(fileEnc);
    }

    reader.readAsArrayBuffer(file); 
}

  async function encryptAndUpload(file) {
    
    let formData = new FormData();
    formData.append("file", file);
    
    let response = await fetch('/upload-form.php', {       
      method: "POST",        
      body: formData     
  });
  console.log("Upload, Encryption, and Compression Completed Successfully.")
  }

And This is the decryption Code:

async function decryptAndDownload_Unzipped() {

  var key = document.getElementById("dec_key").value;
  var file_url = window.location.href + '/uploads/test_new.zip' // the uploaded zip file path and name is hardcoded for now
  // var file_url = 'https://url.com/uploads/test_new.zip'; // This is how the front-end fetches the encrypted zip file

  https.get(file_url,  function(res) {
    var data = [], dataLen = 0; 
  
    res.on('data', function(chunk) {
      data.push(chunk);
      dataLen += chunk.length;

    }).on('end', function() {
      var buf = Buffer.alloc(dataLen);
  
      for (var i = 0, len = data.length, pos = 0; i < len; i++) { 
        data[i].copy(buf, pos); 
        pos += data[i].length; 
      } 
  
      var zip = new AdmZip(buf);
      var zipEntries = zip.getEntries();
      var decrypted = hex2ascii(CryptoJS.AES.decrypt(zip.readAsText(zipEntries[0]), key));
      downloadStringAsFile("decrypted_img.png", decrypted);
      

    });
  });

function hex2ascii(hexx){
    var hex = hexx.toString();  //force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2){
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
      }
        return str;
}

function downloadStringAsFile(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain,' + encodeURIComponent(text));
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

I console logged the input from the encryption function wordArray and the input of the decryption function zip.readAsText(zipEntries[0]) and both have the same identical HEX values. There seem to be no issue originated from the encryption/decryption process.

The Problem

I tested this with image black.png, but the downloaded file from the front-end is corrupted. I opened the downloaded PNG file (that was encrypted then decrypted) using text editor, and compared its binary data with the original and found differences between them around the backslashes (image attached). They are different from the original binary values but I’m not sure why this is happening and that’s why I assume what is causing the png file to be corrupted and can’t be read from image viewers.
Here’s an image shows the difference between the 2 images:
Difference between original and dectypted image

I’m trying to troubleshoot the corruption issue and make the downloaded image viewable.

How do I make each thumbnail active for each displayed image

I made an image slider with arrows. I also included an active border, to show that it corresponds with the display slider. So far, I’ve reached this point and I think I need assistance.

————————– Three things I’m trying to achieve ————————–

First: When a thumbnail is clicked, let it reflect in the display slider. And let the clicked thumbnail become active.

Second: Also, when you click the left or right arrow of the display slider, the corresponding thumbnail should be active.

Third: And finally, for the above actions, let the display slider have a fade effect (or transition) for any image displayed.

let leftArrow = document.querySelector('#slide_left')
let rightArrow = document.querySelector('#slide_right')
let slidesContainer = document.querySelector('#slides')

leftArrow.addEventListener('click', function() {
  const last = document.querySelector('#slides > :last-child');
  last.remove();
  slidesContainer.prepend(last);
})

rightArrow.addEventListener('click', function() {
  const first = document.querySelector('#slides > :first-child');
  first.remove();
  slidesContainer.append(first);
})
* {
  box-sizing: border-box;
}

body {
  background-color: #555;
  height: 100vh;
  display: grid;
  align-items: center;
  justify-items: center;
}

div#slides_wrapper {
  width: 400px;
  display: flex;
  border: 2px solid #efefef;
  justify-content: space-between;
  margin-bottom: 20px;
}

div#slides_wrapper div#slides {
  width: 300px;
  overflow: hidden;
  display: flex;
  background-color: #0ff3;
}

img.slide {
  width: 100%;
}

img.thumbnail {
  width: 50px;
}

div.slide_arrow {
  font-size: 20px;
  background-color: #0f0f0f;
  color: #f0f0f0;
  height: 40px;
  width: 40px;
  display: grid;
  justify-items: center;
  align-items: center;
  align-self: center;
}

div.slide_arrow:hover {
  cursor: pointer;
}

div.slide_arrow#slide_left {
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}

div.slide_arrow#slide_right {
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
}

div#thumbnails {
  width: 400px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

div#thumbnails img.thumbnail {
  background-color: #888;
  margin: 5px;
}

div#thumbnails img.thumbnail.active {
  border: 2px solid #0ff;
}
<div id="main_wrapper">
  <div id="slides_wrapper">
    <div id="slide_left" class="slide_arrow"><span>&#10094;</span></div>
    <div id="slides">
      <img class="slide" src="https://images.pexels.com/photos/1564149/pexels-photo-1564149.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
      <img class="slide" src="https://images.pexels.com/photos/783243/pexels-photo-783243.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
      <img class="slide" src="https://images.pexels.com/photos/4066293/pexels-photo-4066293.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
      <img class="slide" src="https://images.pexels.com/photos/428340/pexels-photo-428340.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
      <img class="slide" src="https://images.pexels.com/photos/9558760/pexels-photo-9558760.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
      <img class="slide" src="https://images.pexels.com/photos/5701644/pexels-photo-5701644.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
      <img class="slide" src="https://images.pexels.com/photos/1639729/pexels-photo-1639729.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
      <img class="slide" src="https://images.pexels.com/photos/4965343/pexels-photo-4965343.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
    </div>
    <div id="slide_right" class="slide_arrow"><span>&#10095;</span></div>
  </div>
  <div id="thumbnails">
    <img class="thumbnail active" src="https://images.pexels.com/photos/1564149/pexels-photo-1564149.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
    <img class="thumbnail" src="https://images.pexels.com/photos/783243/pexels-photo-783243.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
    <img class="thumbnail" src="https://images.pexels.com/photos/4066293/pexels-photo-4066293.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
    <img class="thumbnail" src="https://images.pexels.com/photos/428340/pexels-photo-428340.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
    <img class="thumbnail" src="https://images.pexels.com/photos/9558760/pexels-photo-9558760.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
    <img class="thumbnail" src="https://images.pexels.com/photos/5701644/pexels-photo-5701644.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
    <img class="thumbnail" src="https://images.pexels.com/photos/1639729/pexels-photo-1639729.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
    <img class="thumbnail" src="https://images.pexels.com/photos/4965343/pexels-photo-4965343.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="" />
  </div>
</div>

How to retrieve data from local storage in javascript

i have a class called ui and after saving data in local storage using save method it works but when i’m getting the data with loadData method it gives me undefined .. i want to know why ?!!

class UI{ 

 save(key, value) {
  localStorage.setItem(key, value);
 }

 getValue(key) {
  localStorage.getItem(key);
 }

Can’t update object in state

Help, please, to solve a problem. I tried a huge number of solutions, but nothing worked.

My state

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      countId:{quantityId:[]},
    }}

CountId creates an array of objects in state. Id is taken from another component (no problem with this). To demonstrate what is in id, you can take Product 1,Product 2…. and accordingly this.state.countId.quantityId will be
{Product 1, quantity: 1}, {Product 2, quantity: 1}

CountId = (event) => {
    this.setState({
          countId:{
            ...this.state.countId,
            quantityId:
            this.state.countId.quantityId.concat({id:(event.currentTarget.id), quantity: 1})}})
  }

I am using cloneDeep lodash to create a deep copy of an object.

IncrementItem = () => {
  const deepIncrement = cloneDeep(this.state.countId.quantityId);
  this.setState({
    ...this.state.countId.quantityId,
    quantity: deepIncrement.map(i => i.id ).quantity + 1
})}

buttons to increase or decrease the quantity and the quantity output itself

     <button onClick={this.IncrementItem}>+</button>
        <div>{this.state.countId.quantityId.map(c => c.id ? c.quantity: null)}</div>
     <button onClick={this.DecrementItem}>-</button>

Is it possible to convert this solution to JavaScript or PHP for? valid parentheses javascript or PHP [closed]

Problem Statement:

Given a string s containing only three types of characters: ‘(‘ , ‘)’ and ‘*’ ,
return true if s is valid.

The following rules define a valid string:

01-Any left parenthesis ‘(‘ must have a corresponding right parenthesis ‘)’ .

02-Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(‘ .

03-Left parenthesis ‘(‘ must go before the corresponding right parenthesis ‘)’ .

04- ‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(‘ or an empty string “” .

Example 1:
Input: s = “()”
Output: true

Example 2:
Input: s = “(*)”
Output: true

Example 3:
Input: s = “(*))”
Output: true

Example 4:
Input: s = “)(*))”
Output: false

The examples above are not enough. Please make sure to cover all possible inputs to string s in
your solution.

Constraints:

1 <= s.length <= 100
s[i] is ‘(‘ , ‘)’ or ‘*’ .

Shopify, return product tags except certain prefixed tags, in Javascript

New to Shopify and Liquid (enjoying it). Not greatly experienced with JS! We have Shopify site that uses product tags for the chocolates in various chocolate boxes. The theme is not compatible with collection filtering and is setup to use tags for this also. Thus the tags now contain “Price £10 – £20” etc.

I have code on the product page that loops over all product tags and renders a snippet unless the tag contains ‘price’:

{% for tag in product.tags %}
  {% unless tag contains 'Price' %}
    <li>{% render 'chocolate-menu' with tag as tag %}</li>
  {% endunless %}
{% endfor %}

All good and easy (with StackOverflow help). However, on the collection pages the ‘quickview’ option (which launches a popup) inserts a list of the chocolates (tags) via javascript:

var chocolatesMenu = product.tags;
var chocolatesMenuSpaced = chocolatesMenu.join(', ');
quickview.find(".proBoxInfo .quickViewSKU").append("<label>Chocolates:</label> " + chocolatesMenuSpaced);

How can I ‘scrub’ the price-related tags from product.tags in js? Or is there a clever liquid and js way to do this? I just want to list all tags that don’t start with ‘Price’.

Why in WeakMap key and value are not removed when you display the entire collection, but are removed when you display one element?

Example with “nulling” value. Why does the element still exist in the WeakMap collection in this case?

let weakMap = new WeakMap();
let obj = {name: 'Ivan'};
//adding some new element
weakMap.set({}, obj);
obj = null;
console.log(weakMap);
console.log(weakMap.get({}));

Whole collection

enter image description here

One element
enter image description here

Example with “nulling” key:

enter image description here

What’s going on here? What does it come from? The garbage collector does not have time to clean up everything or what?

Problem adding my firebase project to my react project

So Im making an ecommerce react app, and decided to integrate firebase database to my project. I already created my first project on firebase and loaded all my products there with a random ID.
I imported firebase into my project. Problem is that the general product container seems to be working good but when i do the detail container (which is my one product page view), everything breaks. I will leave the code to each sections in which i implemented firebase database.

This is my cardliscontainer which seems to be working fine

This is my detail container which is gving me blank page

I would really appreciate some help, if you need more info please let me know.

Thanks

Bootstrap-select ‘refresh’ function now re-adds all items to the list

I have markup and JavaScript similar to the following.

<select class="selectpicker" multiple>
  <option value="1">Mustard</option>
  <option value="2">Ketchup</option>
  <option value="3">Barbecue</option>
</select>
$('button').on('click', function () {
  var select = $('select');
  select.val([ 1, 3 ]);
  select.selectpicker('refresh');
});

It selects the selected items in the list and then refreshes the Bootstrap-select component.

This was working in an older version of the component. But now it re-adds everything in the list. So if there are three items, there will be six after running this code.

I’ve created a CodePen to demonstrate:

https://codepen.io/softcircuits/pen/gOvEXJV?editors=1111

How can i add foreach inside my if conditional

I have this code and I’m trying to select all the buttons with that same class

if (window.innerWidth < 768) {
   document.querySelector(".product-info-button").innerHTML = "Product Info >"; 
}  else {
        document.querySelector(".product-info-button").innerHTML = "View Product Info >"; 
    }

But I have no idea how to put a foreach in there.

How to use firebase realtime database and firebase firestore database in the same file.js?

How to use firebase realtime database and firebase firestore database in the same file.js because both modules use a query variable and it is conflicting when importing both modules in the same file.

e.g query imported from "firebase/database"

import { getDatabase, ref, query, orderByChild } from "firebase/database"; 

const mostViewedPosts = query(ref(db, 'posts'), orderByChild('metrics/views'));

e.g query imported from "firebase/firestore"

import { collection, query, where, onSnapshot } from "firebase/firestore";

const q = query(collection(db, "cities"), where("state", "==", "CA"));

Running into NaN error in JavaScript while trying to build a job bonus calculator

I am extremely new to Javascript and I’m working on a project where the goal is to determine what an employee’s compensation including salary, review rating, and length of service. The problem I’ve been running into is, in my console log its stating NaN, which I understand the so-called error but I’m not sure where the problem lies. I’ve tried plugging in parseInt in various places and had no luck. Also have played with toString() and valueOf() but can’t seem to find the right spot for it to work. I have attached the whole code(cause not sure where the problem lies) and a screenshot of the console log output. This is not for an assignment or grade, just a solo project to build knowledge of language. I’m writing this code in VS Code on a PC if that info is needed. I also only added one employee to the code below to help with length. Screenshot of Console log

const employees = [
{
    name: 'Atticus',
    employeeNumber: '2405',
    annualSalary: '47000',
    reviewScore: 3,
},
function processEmployee(employee) {

  let bonusPercentage = calculateBonus(employee);

  let totalBonus = Math.round(bonusPercentage * Number(employee.annualSalary));

  let totalCompensation = totalBonus + Number(employee.annualSalary);

  let processedEmployee = {
    name: employee.name,
    bonusPercentage: bonusPercentage,
    totalBonus: totalBonus,
    totalCompensation: totalCompensation
  }

  return processedEmployee;
}

function calculateBonus(employee) {
  let bonusPercentage;


  if (employee.reviewRating <= 2) {
  //  <=2 -- NO BONUS
  bonusPercentage = 0;} 
  else if (employee.reviewRating === 3) {
  //  ===3 - 4% 
  bonusPercentage = .04;
} else if (employee.reviewRating === 4) {
  //  ===4 - 6% 
  bonusPercentage = .06;
} else if (employee.reviewRating === 5) {
  //  ===5 - 10%
  bonusPercentage = .1;
}

if (employee.employeeNumber.length === 4) {
  // IF employeeNumber is 4 digits
  // +5% to BONUS
  bonusPercentage += .05;
}
if (parseInt(employee.annualSalary) > 65000) {
  // IF income > $65,000
  // -1% to BONUS
  bonusPercentage -= .01;
}
// CAP bonusPercentage at 13%
if (bonusPercentage > 0.13) {
    bonusPercentage = 0.13;
} else if (bonusPercentage < 0) {
    bonusPercentage = 0;
}

return bonusPercentage;
}

for (let employee of employees) {
    console.log(processEmployee(employee));
  }
  console.log( employees );

Component Components are not displayed on the page how to fix

I have a blocks generator

const database = getDatabase()
const shop = ref(database, '/games')

onValue(shop,(snapshot) =>{
    const gamesInfo = snapshot.val()
    for (let key in gamesInfo){
        GamePrice.push(gamesInfo[key]["price"])
        GameValueType.push(gamesInfo[key]["currency_type"])
        GameName.push(gamesInfo[key]["Name"])
        GameImg.push(gamesInfo[key]["ImgUrl"])
        GameDesc.push(gamesInfo[key]["Desc"])
    }
    for(var i = 0; i < GameName.length;i++){
        const CardBlockFront = document.createElement("div")
        const CardBlock = document.createElement("div")
        const CardName = document.createElement("div")
        const CardPrice = document.createElement("div")
        const CardDesc = document.createElement("div")
        const CardBlockBack = document.createElement("div")
        const CardFlipper = document.createElement("div")

        CardBlockFront.setAttribute("class", `front`)
        CardBlock.setAttribute("class", "flip-container")
        CardFlipper.setAttribute("class", "flipper")
        CardBlockBack.setAttribute("class","back")
        CardBockFront.setAttribute("style", "background-image: url(" + GameImg[i] + ");background-repeat: no-repeat;background-size: cover" )

        CardPrice.innerHTML = GamePrice[i] + " " + GameValueType[i]
        CardName.innerHTML = GameName[i]
        CardDesc.innerHTML = GameDesc[i]
        CardBlockBack.append(CardName,CardPrice,CardDesc)
        CardFlipper.append(CardBlockFront,CardBlockBack)
        CardBlock.append(CardFlipper)
        
        document.getElementById("ShopCards").appendChild(CardBlock)

    }
    console.log(GameName)

which adds elements here

import React from 'react';
import GetAndPastData from "../Components/GetAndPastData";
export default function Shop (){

        return (
            <>
                <div>
                    <h2 className={"text-center m-4"}>Games</h2>
                    <div className={"m-4"} id="ShopCards">
                    </div>
                </div>
            </>
        );
}

And Routed in Headers.js

export default function Headers (){

    const [show, setShow] = useState(false)
    const handleClose = () => setShow(false)
    const handleShow = () => setShow(true)

    const [theme, setTheme] = useState("dark")
    const  themeToggle = () => {
        theme === "light" ? setTheme("dark") : setTheme("light")
    };

    return(
            <>
            <ThemeProvider theme={theme === "light" ? lightTheme : darkTheme}>
                <GlobalStyles/>
                <SyledApp>
                <Router>
                <Navbar fixed={"top"} id={"MS"} collapseOnSelect expand={"md"} bg={"dark"} variant={"dark"} className={"MainSite"}>
                    <Button variant={"info"} className={"me-sm-3"} onClick={()=> themeToggle()}>change theme</Button>
                    <Container>
                        <Navbar.Brand className={"SiteName"} as={Link} to={"/"}>
                            <img
                                src = {logo}
                                height={"30"}
                                width={"30"}
                                className={"d-inline-block align-top"}
                                alt ={"Logo"}
                            /> DpGame
                        </Navbar.Brand>
                        <Navbar.Toggle aria-controls={"responsive-navbar-nav"} />
                        <Navbar.Collapse id={"responsive-navbar-nav"}>
                            <Nav className={"me-auto"}>
                                <Nav.Link as={Link} to={"/about"} >About us</Nav.Link>
                                <Nav.Link as={Link} to={"/contacts"} >Contacts</Nav.Link>
                                <Nav.Link as={Link} to={"/shop"}  >Shop</Nav.Link>
                            </Nav>
                        <Form className={"d-flex"}>
                            <FormControl
                                type={"text"}
                                placeholder="Search (didnt work yet)"
                                className={"me-sm-2"}
                            />
                            <Button variant={"outline-info"}>Search</Button>
                        </Form>
                    </Navbar.Collapse>
                </Container>
                <Form className={"d-flex me-sm-2"}>
                    <Button variant={"info"} className={"me-sm-3"} onClick={handleShow}>Sing Up</Button>
                    <Button variant={"outline-info"} onClick={handleShow}>Log In</Button>
                </Form>
            </Navbar>
                <Routes>
                    <Route path={"/"} element={<Home />}/>
                    <Route path={"/about"} element={<About />}/>
                    <Route path={"/contacts"} element={<Contacts />}/>
                    <Route path={"/shop"}  element={<Shop />}/>
                </Routes>
            </Router>

The problem is that only when I refresh the page, these blocks are generated, but if I move to it from another page, they do not appear. I roughly understand why. But how to fix it I do not know. Please help .I am new in React.

Get child nodes

I have this code

<div id="page1-div" style="position:relative;width:1347px;height:1189px;">
        <img width="1347" height="1189" src="target001.png" alt="background image" />
        <p style="position:absolute;top:218px;left:209px;white-space:nowrap" class="ft10">Mario</p>
        <p style="position:absolute;top:218px;left:263px;white-space:nowrap" class="ft10">Lopez</p>
        <p style="position:absolute;top:218px;left:827px;white-space:nowrap" class="ft10">18987456O</p>
        <p style="position:absolute;top:395px;left:183px;white-space:nowrap" class="ft10">25</p>
        <p style="position:absolute;top:395px;left:402px;white-space:nowrap" class="ft10">Fisica y Química</p>
        <p style="position:absolute;top:433px;left:298px;white-space:nowrap" class="ft10">Ninguna</p>
        <p style="position:absolute;top:502px;left:633px;white-space:nowrap" class="ft10">230</p>
</div>
<div id="page2-div" style="position:relative;width:1347px;height:1189px;">
        <img width="1347" height="1189" src="target002.png" alt="background image" />
        <p style="position:absolute;top:149px;left:300px;white-space:nowrap" class="ft20">25</p>
        <p style="position:absolute;top:149px;left:565px;white-space:nowrap" class="ft20">Fisica y Química</p>
        <p style="position:absolute;top:149px;left:984px;white-space:nowrap" class="ft20">fevev</p>
        <p style="position:absolute;top:172px;left:425px;white-space:nowrap" class="ft20">fevevvvev</p>
        <p style="position:absolute;top:172px;left:912px;white-space:nowrap" class="ft20">Juan Soler</p>
        <p style="position:absolute;top:195px;left:319px;white-space:nowrap" class="ft20">Ana&#160;Abarca</p>
        <p style="position:absolute;top:195px;left:981px;white-space:nowrap" class="ft20">9:30-14:30</p>
</div>`

I want to get all p elements inside both divs to set different id attributes (or change the values of the class attributes if that is easier) to each of them so I can modify the styles in a css file. But I don´t know how to properly access the p elements inside the two divs