### Installation and Import Source: https://context7.com/lesixcoder/encryptlong/llms.txt Methods for installing the library via npm and importing it into browser or Node.js environments. ```bash # npm 安装 npm install encryptlong --save ``` ```html ``` ```javascript // ES6 模块引入 import JSEncrypt from 'encryptlong'; // CommonJS 引入 const JSEncrypt = require('encryptlong'); ``` -------------------------------- ### Install encryptlong via npm Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md Install the encryptlong package using npm for use in your project. ```bash npm i encryptlong -S ``` -------------------------------- ### Full Long Text Encryption/Decryption Example Source: https://context7.com/lesixcoder/encryptlong/llms.txt This example demonstrates the complete workflow for encrypting and decrypting long text. It requires setting up public and private keys, preparing the data, performing encryption using `encryptLong`, and decryption using `decryptLong`. Verification ensures data integrity. ```javascript // 定义密钥对 const PUBLIC_KEY = `-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKX1Fs2JUD25zrAEwPnjnZC0az rl1XjGzGrJ64eb1lr9QVVOO2zGKZdqDLZD4Ut4Mp6GHMaqqFXKm+zN7IAXu+mqZb UrqUziHE5YGC02wObiZEzfa6V9a8ZvqpB+Z8KO+hAkkjzjMl+E+hDORpZmez3SMz etn7mcCeLw8/vmxz3QIDAQAB -----END PUBLIC KEY----- `; const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDKX1Fs2JUD25zrAEwPnjnZC0azrl1XjGzGrJ64eb1lr9QVVOO2 zGKZdqDLZD4Ut4Mp6GHMaqqFXKm+zN7IAXu+mqZbUrqUziHE5YGC02wObiZEzfa6 V9a8ZvqpB+Z8KO+hAkkjzjMl+E+hDORpZmez3SMzetn7mcCeLw8/vmxz3QIDAQAB AoGBAJBr6b4V6nJwXdHPyngy4PGl/HTqcK60BkTamALqzmEtU9tNU5z2yz7dy+6a wTsjo7Vao8CwNrUp5fHGXw65EEc1/3Iu2Fiix0XF7RP4NFSoxbBmzQW1nUK/5DFi 4VR1uhEmdbgLwGabsdqzeUqhRKkRGAPVCotBjaDBOu0J3Mu5AkEA+SM7Ctu7evOv ZwjWrp9a5MGxJ9yLLabbIuWL+420jr2G6ojaTZ2ROA2DWWQPx4JqWxDHttomrb38 dk2emP2WAwJBAM/yU58YRQ+dTeuTzNYC1JdWcs35n9+hoVP7y+x29CmcqDTPp3nR Bbbq88yMb2nZdlwthWi7BurNHsRJFqj0GJ8CQF5gJCuW1UxcJ2PGi1yW7R2e6fcJ qoden8B2aDKgmXdBAGyz7s5cE/jB1bH1H60aECPzFVSFCwXh5FMEUEHwPfUCQQC7 JqZ57lbhebrSRcA58GwzFFvY40wu8gIHWvwqgti2xsZgWW+qZCPXf9gSBWaUhmJP Da0fGAxesGN7VyhswNuTAkEAzCFNqL/zwHXcwh9YyHTdk/bRWIJq49jTA+vbgGv0 szKIvGRKoRbub3NEUiI80TDsCAvbJ6R80J7RjnpmShOwcA== -----END RSA PRIVATE KEY----- `; // 创建实例并设置密钥 const jsencrypt = new JSEncrypt(); jsencrypt.setPublicKey(PUBLIC_KEY); jsencrypt.setPrivateKey(PRIVATE_KEY); // 准备长文本数据 const originalData = { code: 200, message: 'success', result: { timestamp: Date.now(), users: Array.from({ length: 10 }, (_, i) => ({ id: i + 1, name: `用户${i + 1}`, email: `user${i + 1}@example.com`, role: i % 2 === 0 ? 'admin' : 'user' })) } }; const plainText = JSON.stringify(originalData); console.log('原文长度:', plainText.length, '字节'); // 加密 const startEncrypt = Date.now(); const encrypted = jsencrypt.encryptLong(plainText); const encryptTime = Date.now() - startEncrypt; console.log('加密耗时:', encryptTime, 'ms'); console.log('密文长度:', encrypted.length, '字节'); // 解密 const startDecrypt = Date.now(); const decrypted = jsencrypt.decryptLong(encrypted); const decryptTime = Date.now() - startDecrypt; console.log('解密耗时:', decryptTime, 'ms'); // 验证 const isMatch = plainText === decrypted; console.log('加解密验证:', isMatch ? '成功' : '失败'); // 解析结果 if (isMatch) { const result = JSON.parse(decrypted); console.log('用户总数:', result.result.users.length); } // 输出示例: // 原文长度: 523 字节 // 加密耗时: 89 ms // 密文长度: 1368 字节 // 解密耗时: 156 ms // 加解密验证: 成功 // 用户总数: 10 ``` -------------------------------- ### Get Private Key in PEM or Base64 Format Source: https://context7.com/lesixcoder/encryptlong/llms.txt Retrieve the private key as a PEM formatted string. getPrivateKey() returns the full PEM format with headers, while getPrivateKeyB64() returns the pure Base64 encoded string without headers. ```javascript const jsencrypt = new JSEncrypt(); jsencrypt.getKey(); // 生成密钥对 // 获取带头尾的私钥 const privateKeyPEM = jsencrypt.getPrivateKey(); console.log(privateKeyPEM); // 输出: // -----BEGIN RSA PRIVATE KEY----- // MIICXQIBAAKBgQDKX1Fs2JUD25zrAEwPnj... // -----END RSA PRIVATE KEY----- // 获取纯 Base64 私钥 const privateKeyB64 = jsencrypt.getPrivateKeyB64(); console.log(privateKeyB64); // 输出: MIICXQIBAAKBgQDKX1Fs2JUD25zrAEwPnj... ``` -------------------------------- ### Get Public Key in PEM or Base64 Format Source: https://context7.com/lesixcoder/encryptlong/llms.txt Retrieve the public key as a PEM formatted string. getPublicKey() returns the full PEM format with headers, while getPublicKeyB64() returns the pure Base64 encoded string without headers. ```javascript const jsencrypt = new JSEncrypt(); jsencrypt.getKey(); // 生成密钥对 // 获取带头尾的公钥 const publicKeyPEM = jsencrypt.getPublicKey(); console.log(publicKeyPEM); // 输出: // -----BEGIN PUBLIC KEY----- // MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ... // -----END PUBLIC KEY----- // 获取纯 Base64 公钥 const publicKeyB64 = jsencrypt.getPublicKeyB64(); console.log(publicKeyB64); // 输出: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ... ``` -------------------------------- ### Get or Generate RSA Key Pair with JSEncrypt Source: https://context7.com/lesixcoder/encryptlong/llms.txt Retrieve the current RSA key object. If no key is set, a new key pair will be automatically generated. An optional callback can be provided for asynchronous key generation. ```javascript const jsencrypt = new JSEncrypt({ default_key_size: '1024' }); // 同步获取/生成密钥 const key = jsencrypt.getKey(); console.log('密钥已生成'); // 异步生成密钥(推荐用于大密钥) const jsencrypt2048 = new JSEncrypt({ default_key_size: '2048' }); jsencrypt2048.getKey(function() { console.log('2048位密钥异步生成完成'); console.log('公钥:', jsencrypt2048.getPublicKey()); }); ``` -------------------------------- ### Initialize JSEncrypt Instance Source: https://context7.com/lesixcoder/encryptlong/llms.txt Create instances with default or custom configurations including key size, public exponent, and logging. ```javascript // 创建默认配置实例 const encrypt = new JSEncrypt(); // 创建自定义配置实例 const encrypt2 = new JSEncrypt({ default_key_size: '2048', // 密钥长度 2048 位 default_public_exponent: '010001', // 公钥指数 65537 log: true // 开启日志 }); ``` -------------------------------- ### JSEncrypt Instance Initialization Source: https://context7.com/lesixcoder/encryptlong/llms.txt Create a new JSEncrypt instance with optional configuration for key size, public exponent, and logging. ```APIDOC ## new JSEncrypt(options) ### Description Initializes a new JSEncrypt instance. The optional `options` object allows configuration of the default key size, public exponent, and logging behavior. ### Parameters #### Request Body - **options** (object) - Optional - Configuration object containing `default_key_size` (string, default '1024'), `default_public_exponent` (string, default '010001'), and `log` (boolean, default false). ``` -------------------------------- ### Generate RSA Key Pairs with OpenSSL Source: https://context7.com/lesixcoder/encryptlong/llms.txt This section provides command-line instructions for generating RSA private and public key pairs using OpenSSL. It covers generating 1024-bit and 2048-bit keys, viewing the keys, and exporting the public key from the private key. ```bash # 生成 1024 位 RSA 私钥 openssl genrsa -out rsa_1024_priv.pem 1024 # 查看私钥 cat rsa_1024_priv.pem # 从私钥导出公钥 openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem # 查看公钥 cat rsa_1024_pub.pem # 生成 2048 位密钥(更安全) openssl genrsa -out rsa_2048_priv.pem 2048 openssl rsa -pubout -in rsa_2048_priv.pem -out rsa_2048_pub.pem ``` -------------------------------- ### View RSA Private Key Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md Display the content of the generated RSA private key file in the terminal. ```bash cat rsa_1024_priv.pem ``` -------------------------------- ### getPublicKey() / getPublicKeyB64() Source: https://context7.com/lesixcoder/encryptlong/llms.txt Retrieves the public key in different formats. ```APIDOC ## getPublicKey() / getPublicKeyB64() ### Description Retrieves the public key. getPublicKey() returns PEM format with headers, while getPublicKeyB64() returns raw Base64. ### Response - **result** (string) - The public key string. ``` -------------------------------- ### View RSA Public Key Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md Display the content of the generated RSA public key file in the terminal. ```bash cat rsa_1024_pub.pem ``` -------------------------------- ### getPrivateKey() / getPrivateKeyB64() Source: https://context7.com/lesixcoder/encryptlong/llms.txt Retrieves the private key in different formats. ```APIDOC ## getPrivateKey() / getPrivateKeyB64() ### Description Retrieves the private key. getPrivateKey() returns PEM format with headers, while getPrivateKeyB64() returns raw Base64. ### Response - **result** (string) - The private key string. ``` -------------------------------- ### getKey(callback) Source: https://context7.com/lesixcoder/encryptlong/llms.txt Retrieves or generates the RSA key object. ```APIDOC ## getKey(callback) ### Description Returns the current RSA key object. If no key exists, it generates a new one. Supports an optional callback for asynchronous generation. ### Parameters - **callback** (function) - Optional - Callback function executed after key generation. ``` -------------------------------- ### Sign Text with JSEncrypt Source: https://context7.com/lesixcoder/encryptlong/llms.txt Sign a given text using your private key. Requires a hash function and its name. The signature is returned as a Base64 encoded string. Returns false on failure. ```javascript // 需要引入 CryptoJS 或其他哈希库 // const signer = new JSEncrypt(); signer.setPrivateKey(PRIVATE_KEY); // SHA256 哈希函数 function sha256(str) { return CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex); } // 对消息进行签名 const message = '这是需要签名的重要消息'; const signature = signer.sign(message, sha256, 'sha256'); if (signature) { console.log('签名成功'); console.log('签名值:', signature); // 输出: Base64 编码的数字签名 } else { console.log('签名失败'); } ``` -------------------------------- ### Generate RSA Private Key with OpenSSL Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md Use OpenSSL to generate a 1024-bit RSA private key. This key is essential for asymmetric encryption operations. ```bash openssl genrsa -out rsa_1024_priv.pem 1024 ``` -------------------------------- ### Key Management Source: https://context7.com/lesixcoder/encryptlong/llms.txt Methods for setting RSA public and private keys for encryption and decryption operations. ```APIDOC ## setPublicKey(pubkey) ### Description Sets the RSA public key for encryption operations. Supports PEM format strings. ## setPrivateKey(privkey) ### Description Sets the RSA private key for decryption operations. Supports PEM format strings. ``` -------------------------------- ### HTML with JSEncrypt for Long Text Encryption/Decryption Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md An HTML file demonstrating the use of JSEncrypt to encrypt and decrypt long text data using provided public and private keys. Ensure jQuery and jsencrypt.js are included. ```html 使用jsencrypt执行长文本加密,解密
长文本加解密
``` -------------------------------- ### verify(text, signature, digestMethod) Source: https://context7.com/lesixcoder/encryptlong/llms.txt Verifies a digital signature using a public key. ```APIDOC ## verify(text, signature, digestMethod) ### Description Verifies a digital signature against the original text using the public key. ### Parameters - **text** (string) - Required - The original message. - **signature** (string) - Required - The Base64 encoded signature. - **digestMethod** (function) - Required - The hash function used for verification. ### Response - **result** (boolean) - Returns true if the signature is valid, false otherwise. ``` -------------------------------- ### Verify Signature with JSEncrypt Source: https://context7.com/lesixcoder/encryptlong/llms.txt Verify a digital signature using the public key. Pass the original text, the Base64 encoded signature, and the hash function. Returns a boolean indicating signature validity. ```javascript const verifier = new JSEncrypt(); verifier.setPublicKey(PUBLIC_KEY); // SHA256 哈希函数 function sha256(str) { return CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex); } // 验证签名 const message = '这是需要签名的重要消息'; const signature = 'Base64EncodedSignature...'; const isValid = verifier.verify(message, signature, sha256); if (isValid) { console.log('签名验证通过 - 消息未被篡改'); } else { console.log('签名验证失败 - 消息可能被篡改'); } ``` -------------------------------- ### sign(text, digestMethod, digestName) Source: https://context7.com/lesixcoder/encryptlong/llms.txt Generates a digital signature for a given text using a private key. ```APIDOC ## sign(text, digestMethod, digestName) ### Description Signs text using the private key with a specified hash function. ### Parameters - **text** (string) - Required - The message to sign. - **digestMethod** (function) - Required - The hash function to use. - **digestName** (string) - Required - The name of the hash algorithm (e.g., sha256). ### Response - **result** (string|boolean) - Returns the Base64 encoded signature or false if signing fails. ``` -------------------------------- ### Encrypt Short Text Source: https://context7.com/lesixcoder/encryptlong/llms.txt Encrypt short strings using the public key, returning Base64 encoded ciphertext. ```javascript const encrypt = new JSEncrypt(); encrypt.setPublicKey(PUBLIC_KEY); // 加密短文本 const plainText = 'This is a test!'; const encrypted = encrypt.encrypt(plainText); if (encrypted) { console.log('加密成功:', encrypted); // 输出: "kHJvB9x8Qe5..." (Base64 编码) } else { console.log('加密失败: 文本可能过长'); } ``` -------------------------------- ### Generate RSA Public Key from Private Key Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md Extract the public key from the generated private key file using OpenSSL. This public key can be shared for encryption. ```bash openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem ``` -------------------------------- ### Base64 Encoded 1024-bit RSA Private Key Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md A sample 1024-bit RSA private key in Base64 format. This key should be kept confidential and is used for decryption. ```text -----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDHikastc8+I81zCg/qWW8dMr8mqvXQ3qbPAmu0RjxoZVI47tvs kYlFAXOf0sPrhO2nUuooJngnHV0639iTTEYG1vckNaW2R6U5QTdQ5Rq5u+uV3pMk 7w7Vs4n3urQ6jnqt2rTXbC1DNa/PFeAZatbf7ffBBy0IGO0zc128IshYcwIDAQAB AoGBALTNl2JxTvq4SDW/3VH0fZkQXWH1MM10oeMbB2qO5beWb11FGaOO77nGKfWc bYgfp5Ogrql4yhBvLAXnxH8bcqqwORtFhlyV68U1y4R+8WxDNh0aevxH8hRS/1X5 031DJm1JlU0E+vStiktN0tC3ebH5hE+1OxbIHSZ+WOWLYX7JAkEA5uigRgKp8ScG auUijvdOLZIhHWq7y5Wz+nOHUuDw8P7wOTKU34QJAoWEe771p9Pf/GTA/kr0BQnP QvWUDxGzJwJBAN05C6krwPeryFKrKtjOGJIniIoY72wRnoNcdEEs3HDRhf48YWFo riRbZylzzzNFy/gmzT6XJQTfktGqq+FZD9UCQGIJaGrxHJgfmpDuAhMzGsUsYtTr iRox0D1Iqa7dhE693t5aBG010OF6MLqdZA1CXrn5SRtuVVaCSLZEL/2J5UcCQQDA d3MXucNnN4NPuS/L9HMYJWD7lPoosaORcgyK77bSSNgk+u9WSjbH1uYIAIPSffUZ bti+jc1dUg5wb+aeZlgJAkEAurrpmpqj5vg087ZngKfFGR5rozDiTsK5DceTV97K a3Y+Nzl+XWTxDBWk4YPh2ZlKv402hZEfWBYxUDn5ZkH/bw== -----END RSA PRIVATE KEY----- ``` -------------------------------- ### Encrypt and Decrypt Long Text with encryptlong Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md Demonstrates encrypting a long JSON string using a public key and decrypting it with a private key. Ensure both public and private keys are set for reliable long text encryption. ```javascript let startTime = new Date(); //公钥 const PUBLIC_KEY = ` -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKX1Fs2JUD25zrAEwPnjnZC0az rl1XjGzGrJ64eb1lr9QVVOO2zGKZdqDLZD4Ut4Mp6GHMaqqFXKm+zN7IAXu+mqZb UrqUziHE5YGC02wObiZEzfa6V9a8ZvqpB+Z8KO+hAkkjzjMl+E+hDORpZmez3SMz etn7mcCeLw8/vmxz3QIDAQAB -----END PUBLIC KEY----- `; //私钥 const PRIVATE_KEY = ` -----BEGIN PUBLIC KEY----- MIICXgIBAAKBgQDKX1Fs2JUD25zrAEwPnjnZC0azrl1XjGzGrJ64eb1lr9QVVOO2 zGKZdqDLZD4Ut4Mp6GHMaqqFXKm+zN7IAXu+mqZbUrqUziHE5YGC02wObiZEzfa6 V9a8ZvqpB+Z8KO+hAkkjzjMl+E+hDORpZmez3SMzetn7mcCeLw8/vmxz3QIDAQAB AoGBAJBr6b4V6nJwXdHPyngy4PGl/HTqcK60BkTamALqzmEtU9tNU5z2yz7dy+6a wTsjo7Vao8CwNrUp5fHGXw65EEc1/3Iu2Fiix0XF7RP4NFSoxbBmzQW1nUK/5DFi 4VR1uhEmdbgLwGabsdqzeUqhRKkRGAPVCotBjaDBOu0J3Mu5AkEA+SM7Ctu7evOv ZwjWrp9a5MGxJ9yLLabbIuWL+420jr2G6ojaTZ2ROA2DWWQPx4JqWxDHttomrb38 dk2emP2WAwJBAM/yU58YRQ+dTeuTzNYC1JdWcs35n9+hoVP7y+x29CmcqDTPp3nR Bbbq88yMb2nZdlwthWi7BurNHsRJFqj0GJ8CQF5gJCuW1UxcJ2PGi1yW7R2e6fcJ qoden8B2aDKgmXdBAGyz7s5cE/jB1bH1H60aECPzFVSFCwXh5FMEUEHwPfUCQQC7 JqZ57lbhebrSRcA58GwzFFvY40wu8gIHWvwqgti2xsZgWW+qZCPXf9gSBWaUhmJP Da0fGAxesGN7VyhswNuTAkEAzCFNqL/zwHXcwh9YyHTdk/bRWIJq49jTA+vbgGv0 szKIvGRKoRbub3NEUiI80TDsCAvbJ6R80J7RjnpmShOwcA== -----END PUBLIC KEY----- `; // 使用设置公私钥 const enc = new JSEncrypt(); enc.setPublicKey(PUBLIC_KEY); enc.setPublicKey(PRIVATE_KEY); // 一段长文本json let data = { code: 200, result: { timestamp: 1572321851823, inter1: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter2: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter3: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter4: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter5: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter6: ["123123123", "123123123", "123123123", "123123123", "123123123"], stream: {}, caton: {}, card: [] } }; data = JSON.stringify(data); let encrypted = enc.encryptLong(data); let endTime = new Date(); console.log("加密后数据:%o", encrypted); console.log("加密时间" + (endTime - startTime) + "ms"); //使用私钥解密 let uncrypted = enc.decryptLong(encrypted); console.log("解密后数据:%o", uncrypted); ``` -------------------------------- ### Set RSA Private Key Source: https://context7.com/lesixcoder/encryptlong/llms.txt Configure the private key for decryption operations using PEM format strings. ```javascript const decrypt = new JSEncrypt(); // 设置私钥 const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH m7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd 8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5 rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876 -----END RSA PRIVATE KEY-----`; decrypt.setPrivateKey(PRIVATE_KEY); // 使用私钥解密 const decrypted = decrypt.decrypt(encryptedText); console.log('解密结果:', decrypted); // 输出: 原始明文 ``` -------------------------------- ### Set RSA Public Key Source: https://context7.com/lesixcoder/encryptlong/llms.txt Configure the public key for encryption operations using PEM format strings. ```javascript const encrypt = new JSEncrypt(); // 设置公钥(带 PEM 头尾) const PUBLIC_KEY = `-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76 xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4 gwQco1KRMDSmXSMkDwIDAQAB -----END PUBLIC KEY-----`; encrypt.setPublicKey(PUBLIC_KEY); // 使用公钥加密 const encrypted = encrypt.encrypt('Hello World'); console.log('加密结果:', encrypted); // 输出: Base64 编码的加密字符串 ``` -------------------------------- ### Encryption and Decryption Methods Source: https://context7.com/lesixcoder/encryptlong/llms.txt Core methods for encrypting and decrypting text, including support for long text via segmented encryption. ```APIDOC ## encrypt(text) ### Description Encrypts short text using the public key. Returns a Base64 encoded string or false on failure. ## decrypt(ciphertext) ### Description Decrypts Base64 encoded ciphertext using the private key. Returns the original plaintext or false on failure. ## encryptLong(text) ### Description Encrypts long text by segmenting it into smaller chunks, bypassing standard RSA length limitations. Returns a Base64 encoded string or false on failure. ``` -------------------------------- ### Include encryptlong in browser Source: https://github.com/lesixcoder/encryptlong/blob/master/README.md Include the encryptlong script in your HTML for browser-based usage. ```html ``` -------------------------------- ### Decrypt Ciphertext Source: https://context7.com/lesixcoder/encryptlong/llms.txt Decrypt Base64 encoded ciphertext using the private key. ```javascript const decrypt = new JSEncrypt(); decrypt.setPrivateKey(PRIVATE_KEY); // 解密 const encrypted = 'kHJvB9x8Qe5F3K...'; // Base64 编码的密文 const decrypted = decrypt.decrypt(encrypted); if (decrypted) { console.log('解密成功:', decrypted); // 输出: "This is a test!" } else { console.log('解密失败'); } ``` -------------------------------- ### Encrypt Long Text Source: https://context7.com/lesixcoder/encryptlong/llms.txt Perform segmented encryption for long text to bypass standard RSA length limitations. ```javascript const encrypt = new JSEncrypt(); // 重要:长文本加密时建议同时设置公私钥,避免加密概率性失败 encrypt.setPublicKey(PUBLIC_KEY); encrypt.setPrivateKey(PRIVATE_KEY); // 加密长 JSON 数据 const longData = { code: 200, result: { timestamp: 1572321851823, users: [ { id: 1, name: '张三', email: 'zhangsan@example.com' }, { id: 2, name: '李四', email: 'lisi@example.com' }, { id: 3, name: '王五', email: 'wangwu@example.com' } ], metadata: { total: 100, page: 1, pageSize: 20 } } }; const startTime = Date.now(); const encrypted = encrypt.encryptLong(JSON.stringify(longData)); const endTime = Date.now(); if (encrypted) { console.log('长文本加密成功'); console.log('密文长度:', encrypted.length); console.log('加密耗时:', endTime - startTime, 'ms'); // 输出示例: // 长文本加密成功 // 密文长度: 1368 // 加密耗时: 45ms } else { console.log('长文本加密失败'); } ``` -------------------------------- ### Decrypt Long Ciphertext with JSEncrypt Source: https://context7.com/lesixcoder/encryptlong/llms.txt Use decryptLong to decrypt Base64 encoded ciphertext that has been split into segments. Ensure the private key is set before decryption. Returns false on failure. ```javascript const decrypt = new JSEncrypt(); decrypt.setPrivateKey(PRIVATE_KEY); // 解密长文本 const encryptedLongText = 'Base64EncodedLongCiphertext...'; const decrypted = decrypt.decryptLong(encryptedLongText); if (decrypted) { const data = JSON.parse(decrypted); console.log('解密成功:', data); console.log('时间戳:', data.result.timestamp); console.log('用户数:', data.result.users.length); // 输出: // 解密成功: { code: 200, result: {...} } // 时间戳: 1572321851823 // 用户数: 3 } else { console.log('长文本解密失败'); } ``` -------------------------------- ### decryptLong(ciphertext) Source: https://context7.com/lesixcoder/encryptlong/llms.txt Decrypts long text by splitting the ciphertext into segments. ```APIDOC ## decryptLong(ciphertext) ### Description Decrypts long text ciphertexts by converting Base64 to hex, splitting into 256-character segments, and concatenating the results. ### Parameters - **ciphertext** (string) - Required - The Base64 encoded long ciphertext. ### Response - **result** (string|boolean) - Returns the decrypted plaintext string or false if decryption fails. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.