import React, { useEffect, useState } from 'react'; import { Form, Input, DatePicker, Select, Button, message, FormInstance, Space } from 'antd'; import moment from 'moment'; import { useNavigate } from 'react-router-dom'; import { GetMachineAuthorizationTypeOptions } from '@/services/enum/machineAuthorizationEnum'; const { TextArea } = Input; import CryptoJS from 'crypto-js'; // 添加这一行导入 import * as LZString from 'lz-string'; import cusRequest from '@/request'; import { AddMachineIdAuthorizationFunc } from '@/services/services/other'; interface AddMachineIdAuthorizationProps { setFormRef: (form: FormInstance) => void; } const AddMachineIdAuthorization: React.FC = ({ setFormRef }) => { const [form] = Form.useForm(); const [loading, setLoading] = useState(false); const [messageApi, messageHolder] = message.useMessage(); useEffect(() => { setFormRef(form); form.setFieldsValue({ type: 0, useType: 0, expiryTime: 365, authorizationCode: "" }) }, [form, setFormRef]); const handleSubmit = async () => { try { setLoading(true); // TODO: Implement API call to save the authorization let values = form.getFieldsValue(); await AddMachineIdAuthorizationFunc(values); messageApi.success('Machine ID authorization added successfully'); } catch (error: any) { messageApi.error(error.message); } finally { setLoading(false); } }; /** * 生成唯一授权码 * @returns 返回一个唯一的授权码字符串,长度与UUID相似 */ function generateUniqueAuthCode(): string { // 基于时间戳的组件 const timestamp = Date.now().toString(16); // 使用加密安全的随机值生成函数 const getRandomHex = (length: number): string => { const bytes = new Uint8Array(length); // 使用浏览器的加密API生成随机数 window.crypto.getRandomValues(bytes); // 转换为十六进制字符串 return Array.from(bytes) .map(b => b.toString(16).padStart(2, '0')) .join(''); }; // 生成四个随机组件 const randomA = getRandomHex(4); const randomB = getRandomHex(2); const randomC = getRandomHex(2); const randomD = getRandomHex(6); // 组合成类似UUID格式的字符串,但算法完全不同 return `${timestamp}${randomA}${randomB}${randomC}${randomD}`.toUpperCase(); } function GenerateAuthorizationCode() { let code = generateUniqueAuthCode(); form.setFieldsValue({ authorizationCode: code }); // return; // const values = form.getFieldsValue(); // const { machineId, type, authorizedDate, expiryDate } = values; // if (!machineId || type === undefined || !authorizedDate || !expiryDate) { // messageApi.error('请先填写必要信息(机器码、类型和日期)'); // return; // } // try { // // Format dates to strings // const authDate = moment(authorizedDate).format('YYYY-MM-DD HH:mm:ss'); // const expDate = moment(expiryDate).format('YYYY-MM-DD HH:mm:ss'); // let obj = { // machineId: machineId, // type: type, // authorizedDate: authDate, // expiryDate: expDate // } // // Create the string to encrypt // const dataToEncrypt = JSON.stringify(obj); // // Assuming CryptoJS is imported // const secretKey = machineId; // // Generate a secure encryption key from machineId // const key = CryptoJS.enc.Utf8.parse(CryptoJS.SHA256(secretKey).toString()); // // Generate a random initialization vector // const iv = CryptoJS.lib.WordArray.random(16); // // Encrypt the data using AES encryption // const encrypted = CryptoJS.AES.encrypt(dataToEncrypt, key, { // iv: iv, // mode: CryptoJS.mode.CBC, // padding: CryptoJS.pad.Pkcs7 // }); // // Convert IV to base64 for storage // const ivBase64 = CryptoJS.enc.Base64.stringify(iv); // // Get the encrypted data in base64 format // const encryptedBase64 = encrypted.toString(); // // Combine IV and encrypted data with a delimiter for future decryption // const authCode = ivBase64 + ':' + encryptedBase64; // // 使用LZString压缩 // const compressedCode = LZString.compressToEncodedURIComponent(authCode); // // Set the encrypted value in the form // form.setFieldsValue({ authorizationCode: compressedCode }); // messageApi.success('授权码已生成'); // } catch (error) { // console.error('生成授权码时出错:', error); // messageApi.error('生成授权码失败'); // } } function DecryptAuthorizationCode(authCode: string, machineId: string) { try { // 解压缩 const originalAuthCode = LZString.decompressFromEncodedURIComponent(authCode); // 拆分授权码,获取IV和加密数据 const [ivBase64, encryptedBase64] = originalAuthCode.split(':'); if (!ivBase64 || !encryptedBase64) { throw new Error('无效的授权码格式'); } // 从Base64转换回IV const iv = CryptoJS.enc.Base64.parse(ivBase64); // 使用相同的方法生成密钥 const secretKey = machineId; const key = CryptoJS.enc.Utf8.parse(CryptoJS.SHA256(secretKey).toString()); // 解密数据 const decrypted = CryptoJS.AES.decrypt(encryptedBase64, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); // 将解密后的数据转换为字符串 const decryptedData = decrypted.toString(CryptoJS.enc.Utf8); // 将JSON字符串解析为对象 const decodedObject = JSON.parse(decryptedData); return { success: true, data: decodedObject }; } catch (error) { console.error('解密授权码时出错:', error); return { success: false, error: error instanceof Error ? error.message : '未知错误' }; } } return (
{/* */} {messageHolder}
); }; export default AddMachineIdAuthorization;