Min

Min

持续投身前端开发领域,一起分享,交流,成长

Hello everyone, today we are going to explore a library.

crypto-js#

Insert picture description here
Yes, the screenshot above is from Youdao Translation. In order to obtain more authoritative information, this library is used for encryption. However, the introduction says that it has stopped maintenance, but it does not affect our use in front-end projects, so there is no harm in learning.


Application Scenarios#

Determine if the images are the same: This is my recent requirement. Taking this opportunity, I also learned some knowledge about files. I will share it with you below. Before learning, it is best for us to know some concepts.
What is FileReader

MD5 (Message-Digest Algorithm 5) is a widely used cryptographic hash function that can produce a 128-bit (16-byte) hash value, usually represented as 32 hexadecimal digits. The design of MD5 is to make different input data produce different hash values, and it is theoretically impossible to reverse the hash value to obtain the original data.
However, it is worth noting that the MD5 algorithm is considered insecure in cryptographic applications because it has weaknesses in collision.

SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function that belongs to the SHA-2 (Secure Hash Algorithm 2) family of hash functions. The SHA-256 algorithm can calculate a fixed-length output value from data blocks of any length, and the output value is usually 256 bits (32 bytes).
In general, SHA-256 is a secure, reliable, and widely used hash algorithm that provides an efficient method for verifying the integrity and consistency of data. For more information about SHA-256, it is recommended to consult cryptographic books or experts in the field.

Yes, these three points are the concepts we need to understand in order to determine the same image. What we need to do can be divided into three steps:

  1. Get file information from the control.
  2. Use fileReader to read the file and convert it to a file buffer.
  3. Use cryptographic algorithms to calculate a fixed-length input value for comparison.

Practical Analysis#

<script setup lang="ts">
import { ref } from 'vue'
import CryptoJS from 'crypto-js' //4.2.0

defineProps<{ msg: string }>()

const count = ref(0)
const file1 = ref()
const file2 = ref()

function onFileChange1(e:any) {
  const files = e.target.files;
  if (files && files.length) {
    file1.value = files[0]
  }
}
function onFileChange2(e:any) {
  const files = e.target.files;
  if (files && files.length) {
    file2.value = files[0]
  }
}
async function calculateFileHash(file:any) {  
  return new Promise((resolve, reject) => {  
    // Read the file's buffer
    const reader = new FileReader();  
    reader.onload = (e:any) => {
      // The ArrayBuff needs to be converted to WorkArray before it can be calculated by SHA256
      const wa = CryptoJS.lib.WordArray.create(e.target.result);
      resolve(CryptoJS.SHA256(wa).toString());  
    };  
    reader.onerror = error => reject(error);  
    reader.readAsArrayBuffer(file);  
  });  
}

async function compareFiles() {  
  try {  
    const [file1r, file2r] = await Promise.all(  
      [file1.value,file2.value].map((file:any) => calculateFileHash(file))  
    );
    console.log('%c [ file1r, file2r ]-39', 'font-size:13px; background:pink; color:#bf2c9f;', file1r == file2r)
  } catch (error) {  
    console.error('An error occurred while calculating the file hash:', error);  
  }  
}
</script>

<template>
  <h1>{{ msg }}</h1>
  <input type="file" @change="onFileChange1" ref="fileInput" />
  <input type="file" @change="onFileChange2" ref="fileInput" />

  <button type="button" @click="count++">count is {{ count }}</button>
  <button type="button" @click="compareFiles">Compare</button>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>

const wa = CryptoJS.lib.WordArray.create(e.target.result);
CryptoJS.SHA256(wa).toString()

The core is the two methods inside. If you are interested, you can try them yourself. You need to convert it to wa before it can be calculated. The above is from my personal practice. Thank you for your support.


Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.