crypto-js和原生web crypto api基本用法

379 阅读1分钟
<script setup lang="ts">
import { onMounted } from 'vue'
import CryptoJS from 'crypto-js'
onMounted(() => {
  async function sha256File(file) {
    const fileBuffer = await file.arrayBuffer()
    const hashBuffer = await crypto.subtle.digest('SHA-256', fileBuffer)
    const hashArray = Array.from(new Uint8Array(hashBuffer))
    const hashHex = hashArray
      .map(byte => ('00' + byte.toString(16)).slice(-2))
      .join('')

    return hashHex
  }

  // 使用示例
  const fileInput = document.getElementById('fileInput')

  fileInput.addEventListener('change', async () => {
    const file = fileInput.files[0]
    const hash = await sha256File(file)
    console.log('SHA-256 哈希值为2: ' + hash)
    const fileReader = new FileReader()
    fileReader.onload = function (e) {
      const fileContent = e.target.result
      const wordArray = CryptoJS.lib.WordArray.create(fileContent)
      const hash = CryptoJS.SHA256(wordArray).toString()

      console.log('SHA-256 哈希值为1: ' + hash)
    }

    fileReader.readAsArrayBuffer(file)
  })
})
</script>

<template>
  <input id="fileInput" type="file" />
</template>

<style lang="css"></style>