Vue.Draggable拖拽数据加密密钥管理:定期轮换

【免费下载链接】Vue.Draggable 【免费下载链接】Vue.Draggable 项目地址: https://gitcode.com/gh_mirrors/vue/Vue.Draggable

在前端应用中,拖拽功能常涉及敏感数据交互,如任务排序、权限配置等场景。若直接传递原始数据,可能面临数据泄露风险。本文将结合Vue.Draggable组件,实现拖拽过程中的数据加密及密钥定期轮换机制,确保数据传输安全性。

核心实现思路

通过Vue.Draggable的事件钩子与自定义加密模块结合,实现拖拽数据的全生命周期保护。主要流程包括:

  1. 初始化加密密钥并存储于安全存储(如localStorage加密分区)
  2. 拖拽开始时对数据进行AES加密
  3. 拖拽结束后解密并验证数据完整性
  4. 定时触发密钥轮换,更新本地存储密钥

拖拽加密流程

加密模块实现

创建src/util/crypto.js工具模块,封装加密、解密及密钥管理功能:

// src/util/crypto.js
import CryptoJS from 'crypto-js';

const STORAGE_KEY = 'draggable_secure_key';
const KEY_ROTATION_DAYS = 7;

export default {
  // 初始化密钥(首次使用或密钥过期时)
  initKey() {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      const { key, timestamp } = JSON.parse(stored);
      if (this.isKeyValid(timestamp)) return key;
    }
    
    // 生成新的256位随机密钥
    const newKey = CryptoJS.lib.WordArray.random(32).toString();
    localStorage.setItem(STORAGE_KEY, JSON.stringify({
      key: newKey,
      timestamp: Date.now()
    }));
    return newKey;
  },

  // 检查密钥是否过期
  isKeyValid(timestamp) {
    return (Date.now() - timestamp) < (KEY_ROTATION_DAYS * 24 * 60 * 60 * 1000);
  },

  // 加密数据
  encrypt(data, key = this.initKey()) {
    return CryptoJS.AES.encrypt(JSON.stringify(data), key).toString();
  },

  // 解密数据
  decrypt(ciphertext, key = this.initKey()) {
    const bytes = CryptoJS.AES.decrypt(ciphertext, key);
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
  },

  // 强制轮换密钥
  rotateKey() {
    localStorage.removeItem(STORAGE_KEY);
    return this.initKey();
  }
};

拖拽组件集成加密

修改Vue.Draggable组件使用方式,在拖拽事件中集成加密逻辑:

<!-- example/components/secure-draggable.vue -->
<template>
  <draggable 
    v-model="encryptedList" 
    @start="handleDragStart" 
    @end="handleDragEnd"
    tag="div"
    animation="300"
  >
    <div v-for="(item, index) in decryptedList" :key="item.id" class="draggable-item">
      {{ item.content }}
    </div>
  </draggable>
</template>

<script>
import draggable from 'vuedraggable';
import crypto from '../../src/util/crypto';

export default {
  components: { draggable },
  props: ['rawList'],
  data() {
    return {
      encryptedList: []
    };
  },
  computed: {
    decryptedList() {
      return this.encryptedList.map(item => crypto.decrypt(item));
    }
  },
  watch: {
    rawList: {
      handler(newVal) {
        this.encryptedList = newVal.map(item => crypto.encrypt(item));
      },
      immediate: true
    }
  },
  methods: {
    handleDragStart() {
      // 检查密钥有效期,过期则自动轮换
      const stored = JSON.parse(localStorage.getItem(crypto.STORAGE_KEY));
      if (!stored || !crypto.isKeyValid(stored.timestamp)) {
        crypto.rotateKey();
        console.log('密钥已自动轮换');
      }
    },
    handleDragEnd(evt) {
      // 拖拽结束后通知父组件更新原始数据
      this.$emit('update:rawList', this.decryptedList);
    }
  }
};
</script>

密钥轮换机制

在应用入口处注册定时任务,实现密钥定期轮换:

// src/main.js
import crypto from './util/crypto';

// 每日检查密钥有效期
setInterval(() => {
  const stored = localStorage.getItem(crypto.STORAGE_KEY);
  if (stored) {
    const { timestamp } = JSON.parse(stored);
    if (!crypto.isKeyValid(timestamp)) {
      const oldKey = JSON.parse(stored).key;
      const newKey = crypto.rotateKey();
      console.log(`密钥轮换完成 (旧密钥: ${oldKey.slice(0,8)}..., 新密钥: ${newKey.slice(0,8)}...)`);
      
      // 可选:发送密钥轮换日志到后端
      // fetch('/api/log-key-rotation', {
      //   method: 'POST',
      //   body: JSON.stringify({ oldKeyHash: CryptoJS.SHA256(oldKey).toString() })
      // });
    }
  }
}, 24 * 60 * 60 * 1000);

安全性增强建议

  1. 密钥存储优化

    • 生产环境建议使用Web Crypto API替代localStorage
    • 考虑结合后端生成临时密钥,通过HTTPS传输
  2. 数据验证

    • 添加HMAC校验确保数据完整性:
    // src/util/crypto.js 添加校验方法
    sign(data, key) {
      return CryptoJS.HmacSHA256(JSON.stringify(data), key).toString();
    },
    verify(data, signature, key) {
      return this.sign(data, key) === signature;
    }
    
  3. 组件安全配置

    • Vue.Draggable配置中启用filter选项限制可拖拽元素
    • 使用preventOnFilter防止非法拖拽操作

应用场景示例

任务管理系统

在任务看板应用中,拖拽任务卡片时自动加密任务ID和优先级:

<!-- example/components/task-board.vue -->
<template>
  <div class="task-board">
    <secure-draggable 
      v-model="rawTasks" 
      @update:rawList="saveTasks"
    />
  </div>
</template>

<script>
import SecureDraggable from './secure-draggable';

export default {
  components: { SecureDraggable },
  data() {
    return {
      rawTasks: [
        { id: 't1', content: '完成密钥轮换模块', priority: 'high' },
        { id: 't2', content: '集成Web Crypto API', priority: 'medium' }
      ]
    };
  },
  methods: {
    saveTasks(updatedTasks) {
      // 仅发送解密后的必要字段到后端
      const payload = updatedTasks.map(({id, priority}) => ({id, priority}));
      fetch('/api/update-tasks', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(payload)
      });
    }
  }
};
</script>

权限配置界面

在角色权限配置中,拖拽权限项时加密权限标识符:

<!-- example/components/permission-config.vue -->
<secure-draggable 
  v-model="rawPermissions"
  :options="{group: 'permissions'}"
/>

参考文档

通过上述实现,可在保持Vue.Draggable原有拖拽体验的同时,为敏感数据添加加密保护。密钥定期轮换机制进一步降低了长期使用同一密钥带来的安全风险,特别适合需要在前端处理敏感排序数据的企业级应用。

【免费下载链接】Vue.Draggable 【免费下载链接】Vue.Draggable 项目地址: https://gitcode.com/gh_mirrors/vue/Vue.Draggable

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐