在这里插入图片描述

目录

  1. 概述
  2. 工具功能
  3. 核心实现
  4. Kotlin 源代码
  5. JavaScript 编译代码
  6. ArkTS 调用代码
  7. 实战案例
  8. 最佳实践

概述

本文档介绍如何在 Kotlin Multiplatform (KMP) 鸿蒙跨端开发中实现一个完整的文本加密解密工具系统。文本加密是现代应用开发中的一个核心安全需求,涉及数据保护、隐私安全和信息安全等多个方面。无论是保护用户敏感信息、实现安全通信还是防止数据泄露,一个功能强大的加密解密工具都能提供必要的支持。

这个案例展示了如何使用 Kotlin 的加密库、字符串处理和编码转换来创建一个功能丰富的文本加密解密分析工具。文本加密解密工具需要能够支持多种加密算法、处理不同的编码格式、生成安全的密钥、验证加密数据的完整性等。通过 KMP,这个工具可以无缝编译到 JavaScript,在 OpenHarmony 应用中运行,并支持用户输入进行实时加密解密操作。

在实际应用中,文本加密解密工具广泛应用于以下场景:用户账户密码的存储和验证、API 通信中的数据加密、移动应用中的本地数据保护、云存储中的端到端加密等。通过使用标准的加密算法如 AES、RSA 和 SHA,我们可以确保数据的机密性、完整性和真实性。同时,通过 KMP 框架的跨端能力,我们可以在不同平台上使用相同的加密逻辑,大大提高了代码的可维护性和一致性。

工具的特点

  • 多算法支持:支持 Caesar 密码、Base64 编码、简单 XOR 加密等多种加密方式
  • 密钥管理:提供安全的密钥生成和管理机制
  • 编码转换:支持 UTF-8、Base64 等多种编码格式
  • 加密强度分析:评估加密文本的强度和安全性
  • 批量处理:支持批量加密和解密操作
  • 跨端兼容:一份 Kotlin 代码可同时服务多个平台

工具功能

1. Caesar 密码加密

Caesar 密码是最古老的加密方法之一,通过将字母按照字母表向前或向后移动固定的位数来实现加密。这种方法虽然在现代应用中安全性较低,但作为加密学的基础,它对于理解加密原理非常有帮助。Caesar 密码的优点是实现简单、速度快,缺点是容易被暴力破解。

  • 移位加密:支持自定义移位距离
  • 字母保留:保持字母的大小写
  • 非字母处理:数字和特殊字符保持不变

2. Base64 编码

Base64 是一种将二进制数据转换为可打印 ASCII 字符的编码方式。它广泛应用于电子邮件、数据传输和数据存储中。Base64 编码将每 3 个字节的数据转换为 4 个可打印字符,这样可以确保数据在各种系统中的兼容性。虽然 Base64 不是真正的加密方式,但它可以用于数据的混淆和传输。

  • 编码转换:将文本转换为 Base64 格式
  • 解码转换:将 Base64 格式恢复为原始文本
  • URL 安全:支持 URL 安全的 Base64 编码

3. XOR 加密

XOR 加密是一种简单但有效的对称加密方法,使用异或操作对数据进行加密和解密。XOR 的特性是:如果 A XOR B = C,那么 C XOR B = A,这使得同一个密钥可以用于加密和解密。XOR 加密的优点是速度快、实现简单,缺点是安全性相对较低,容易被频率分析破解。

  • 密钥加密:使用自定义密钥进行 XOR 加密
  • 对称解密:使用相同密钥进行解密
  • 字节级操作:直接对字节进行操作

4. 加密强度分析

  • 熵值计算:计算文本的信息熵
  • 字符多样性:分析字符集的多样性
  • 重复率分析:检测重复字符的出现频率

5. 批量处理

  • 列表加密:支持对多个文本进行批量加密
  • 列表解密:支持对多个密文进行批量解密
  • 进度跟踪:提供处理进度信息

核心实现

1. Caesar 密码实现

fun caesarEncrypt(text: String, shift: Int): String {
    return text.map { char ->
        when {
            char in 'a'..'z' -> {
                val shifted = (char - 'a' + shift) % 26
                'a' + shifted
            }
            char in 'A'..'Z' -> {
                val shifted = (char - 'A' + shift) % 26
                'A' + shifted
            }
            else -> char
        }
    }.joinToString("")
}

fun caesarDecrypt(text: String, shift: Int): String {
    return caesarEncrypt(text, 26 - (shift % 26))
}

代码说明:

Caesar 密码的实现基于字符的 ASCII 值。对于小写字母,我们首先计算字符相对于 ‘a’ 的偏移量,然后加上移位距离,使用模 26 运算来处理循环。例如,如果字符是 ‘a’,移位距离是 3,那么结果是 (0 + 3) % 26 = 3,对应的字符是 ‘d’。对于大写字母,处理方式相同,只是基准字符改为 ‘A’。非字母字符(如数字和特殊字符)保持不变。解密过程是加密的逆过程,通过使用 26 - shift 作为移位距离来实现。

2. Base64 编码实现

fun base64Encode(text: String): String {
    val bytes = text.toByteArray(Charsets.UTF_8)
    val base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    val result = StringBuilder()
    
    var i = 0
    while (i < bytes.size) {
        val b1 = bytes[i].toInt() and 0xFF
        val b2 = if (i + 1 < bytes.size) bytes[i + 1].toInt() and 0xFF else 0
        val b3 = if (i + 2 < bytes.size) bytes[i + 2].toInt() and 0xFF else 0
        
        val enc1 = b1 shr 2
        val enc2 = ((b1 and 0x03) shl 4) or (b2 shr 4)
        val enc3 = ((b2 and 0x0F) shl 2) or (b3 shr 6)
        val enc4 = b3 and 0x3F
        
        result.append(base64Chars[enc1])
        result.append(base64Chars[enc2])
        result.append(if (i + 1 < bytes.size) base64Chars[enc3] else '=')
        result.append(if (i + 2 < bytes.size) base64Chars[enc4] else '=')
        
        i += 3
    }
    
    return result.toString()
}

fun base64Decode(text: String): String {
    val base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    val bytes = mutableListOf<Byte>()
    
    var i = 0
    while (i < text.length) {
        val enc1 = base64Chars.indexOf(text[i])
        val enc2 = base64Chars.indexOf(text[i + 1])
        val enc3 = if (i + 2 < text.length && text[i + 2] != '=') base64Chars.indexOf(text[i + 2]) else 0
        val enc4 = if (i + 3 < text.length && text[i + 3] != '=') base64Chars.indexOf(text[i + 3]) else 0
        
        val b1 = ((enc1 shl 2) or (enc2 shr 4)).toByte()
        bytes.add(b1)
        
        if (text[i + 2] != '=') {
            val b2 = (((enc2 and 0x0F) shl 4) or (enc3 shr 2)).toByte()
            bytes.add(b2)
        }
        
        if (text[i + 3] != '=') {
            val b3 = (((enc3 and 0x03) shl 6) or enc4).toByte()
            bytes.add(b3)
        }
        
        i += 4
    }
    
    return bytes.toByteArray().toString(Charsets.UTF_8)
}

代码说明:

Base64 编码的实现涉及将 3 个字节的数据转换为 4 个 Base64 字符。在编码过程中,我们首先读取 3 个字节,然后将它们分解为 6 位的组。每个 6 位的组对应 Base64 字符表中的一个字符。如果输入数据不是 3 的倍数,我们使用填充字符 ‘=’ 来补齐。解码过程是编码的逆过程,我们首先找到每个 Base64 字符在字符表中的索引,然后将这些索引值重新组合成原始的字节数据。

3. XOR 加密实现

fun xorEncrypt(text: String, key: String): String {
    val bytes = text.toByteArray(Charsets.UTF_8)
    val keyBytes = key.toByteArray(Charsets.UTF_8)
    val result = ByteArray(bytes.size)
    
    for (i in bytes.indices) {
        result[i] = (bytes[i].toInt() xor keyBytes[i % keyBytes.size].toInt()).toByte()
    }
    
    return result.joinToString("") { "%02x".format(it) }
}

fun xorDecrypt(hexText: String, key: String): String {
    val bytes = hexText.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
    val keyBytes = key.toByteArray(Charsets.UTF_8)
    val result = ByteArray(bytes.size)
    
    for (i in bytes.indices) {
        result[i] = (bytes[i].toInt() xor keyBytes[i % keyBytes.size].toInt()).toByte()
    }
    
    return result.toString(Charsets.UTF_8)
}

代码说明:

XOR 加密的核心是异或操作。我们将文本转换为字节数组,然后将每个字节与密钥中对应位置的字节进行异或操作。由于密钥可能比文本短,我们使用模运算来循环使用密钥字节。加密后的结果转换为十六进制字符串以便传输和存储。解密过程是相同的,因为 XOR 操作具有自逆性质:A XOR B XOR B = A。

4. 加密强度分析

fun calculateEntropy(text: String): Double {
    val charFrequency = mutableMapOf<Char, Int>()
    for (char in text) {
        charFrequency[char] = charFrequency.getOrDefault(char, 0) + 1
    }
    
    var entropy = 0.0
    for ((_, count) in charFrequency) {
        val probability = count.toDouble() / text.length
        entropy -= probability * (Math.log(probability) / Math.log(2.0))
    }
    
    return entropy
}

fun analyzeEncryptionStrength(text: String): Map<String, Any> {
    val uniqueChars = text.toSet().size
    val totalChars = text.length
    val entropy = calculateEntropy(text)
    val diversity = uniqueChars.toDouble() / totalChars
    
    val strength = when {
        entropy > 7.0 && diversity > 0.5 -> "强"
        entropy > 5.0 && diversity > 0.3 -> "中"
        else -> "弱"
    }
    
    return mapOf(
        "entropy" to entropy,
        "uniqueChars" to uniqueChars,
        "totalChars" to totalChars,
        "diversity" to diversity,
        "strength" to strength
    )
}

代码说明:

加密强度分析基于信息论中的熵概念。熵是衡量信息不确定性的指标,熵值越高,说明数据的随机性越好,加密强度越强。我们首先计算文本中每个字符的出现频率,然后根据频率计算熵值。同时,我们还计算字符的多样性,即不同字符数与总字符数的比值。综合考虑熵值和多样性,我们可以给出加密强度的评估。


Kotlin 源代码

// TextEncryptionDecryption.kt
// 文本加密解密工具的完整实现

class TextEncryptionDecryption {
    
    // Caesar 密码加密
    fun caesarEncrypt(text: String, shift: Int): String {
        return text.map { char ->
            when {
                char in 'a'..'z' -> {
                    val shifted = (char - 'a' + shift) % 26
                    'a' + shifted
                }
                char in 'A'..'Z' -> {
                    val shifted = (char - 'A' + shift) % 26
                    'A' + shifted
                }
                else -> char
            }
        }.joinToString("")
    }
    
    // Caesar 密码解密
    fun caesarDecrypt(text: String, shift: Int): String {
        return caesarEncrypt(text, 26 - (shift % 26))
    }
    
    // Base64 编码
    fun base64Encode(text: String): String {
        val bytes = text.toByteArray(Charsets.UTF_8)
        val base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
        val result = StringBuilder()
        
        var i = 0
        while (i < bytes.size) {
            val b1 = bytes[i].toInt() and 0xFF
            val b2 = if (i + 1 < bytes.size) bytes[i + 1].toInt() and 0xFF else 0
            val b3 = if (i + 2 < bytes.size) bytes[i + 2].toInt() and 0xFF else 0
            
            val enc1 = b1 shr 2
            val enc2 = ((b1 and 0x03) shl 4) or (b2 shr 4)
            val enc3 = ((b2 and 0x0F) shl 2) or (b3 shr 6)
            val enc4 = b3 and 0x3F
            
            result.append(base64Chars[enc1])
            result.append(base64Chars[enc2])
            result.append(if (i + 1 < bytes.size) base64Chars[enc3] else '=')
            result.append(if (i + 2 < bytes.size) base64Chars[enc4] else '=')
            
            i += 3
        }
        
        return result.toString()
    }
    
    // Base64 解码
    fun base64Decode(text: String): String {
        val base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
        val bytes = mutableListOf<Byte>()
        
        var i = 0
        while (i < text.length) {
            val enc1 = base64Chars.indexOf(text[i])
            val enc2 = base64Chars.indexOf(text[i + 1])
            val enc3 = if (i + 2 < text.length && text[i + 2] != '=') base64Chars.indexOf(text[i + 2]) else 0
            val enc4 = if (i + 3 < text.length && text[i + 3] != '=') base64Chars.indexOf(text[i + 3]) else 0
            
            val b1 = ((enc1 shl 2) or (enc2 shr 4)).toByte()
            bytes.add(b1)
            
            if (text[i + 2] != '=') {
                val b2 = (((enc2 and 0x0F) shl 4) or (enc3 shr 2)).toByte()
                bytes.add(b2)
            }
            
            if (text[i + 3] != '=') {
                val b3 = (((enc3 and 0x03) shl 6) or enc4).toByte()
                bytes.add(b3)
            }
            
            i += 4
        }
        
        return bytes.toByteArray().toString(Charsets.UTF_8)
    }
    
    // XOR 加密
    fun xorEncrypt(text: String, key: String): String {
        val bytes = text.toByteArray(Charsets.UTF_8)
        val keyBytes = key.toByteArray(Charsets.UTF_8)
        val result = ByteArray(bytes.size)
        
        for (i in bytes.indices) {
            result[i] = (bytes[i].toInt() xor keyBytes[i % keyBytes.size].toInt()).toByte()
        }
        
        return result.joinToString("") { "%02x".format(it) }
    }
    
    // XOR 解密
    fun xorDecrypt(hexText: String, key: String): String {
        val bytes = hexText.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
        val keyBytes = key.toByteArray(Charsets.UTF_8)
        val result = ByteArray(bytes.size)
        
        for (i in bytes.indices) {
            result[i] = (bytes[i].toInt() xor keyBytes[i % keyBytes.size].toInt()).toByte()
        }
        
        return result.toString(Charsets.UTF_8)
    }
    
    // 计算信息熵
    fun calculateEntropy(text: String): Double {
        val charFrequency = mutableMapOf<Char, Int>()
        for (char in text) {
            charFrequency[char] = charFrequency.getOrDefault(char, 0) + 1
        }
        
        var entropy = 0.0
        for ((_, count) in charFrequency) {
            val probability = count.toDouble() / text.length
            entropy -= probability * (Math.log(probability) / Math.log(2.0))
        }
        
        return entropy
    }
    
    // 分析加密强度
    fun analyzeEncryptionStrength(text: String): Map<String, Any> {
        val uniqueChars = text.toSet().size
        val totalChars = text.length
        val entropy = calculateEntropy(text)
        val diversity = uniqueChars.toDouble() / totalChars
        
        val strength = when {
            entropy > 7.0 && diversity > 0.5 -> "强"
            entropy > 5.0 && diversity > 0.3 -> "中"
            else -> "弱"
        }
        
        return mapOf(
            "entropy" to entropy,
            "uniqueChars" to uniqueChars,
            "totalChars" to totalChars,
            "diversity" to diversity,
            "strength" to strength
        )
    }
    
    // 批量加密
    fun batchEncrypt(texts: List<String>, method: String, key: String = ""): List<String> {
        return texts.map { text ->
            when (method) {
                "caesar" -> caesarEncrypt(text, 3)
                "base64" -> base64Encode(text)
                "xor" -> xorEncrypt(text, key)
                else -> text
            }
        }
    }
    
    // 批量解密
    fun batchDecrypt(texts: List<String>, method: String, key: String = ""): List<String> {
        return texts.map { text ->
            when (method) {
                "caesar" -> caesarDecrypt(text, 3)
                "base64" -> base64Decode(text)
                "xor" -> xorDecrypt(text, key)
                else -> text
            }
        }
    }
}

// 使用示例
fun main() {
    val tool = TextEncryptionDecryption()
    
    // Caesar 密码示例
    val originalText = "Hello World"
    val caesarEncrypted = tool.caesarEncrypt(originalText, 3)
    val caesarDecrypted = tool.caesarDecrypt(caesarEncrypted, 3)
    println("Caesar 加密: $caesarEncrypted")
    println("Caesar 解密: $caesarDecrypted")
    
    // Base64 编码示例
    val base64Encoded = tool.base64Encode(originalText)
    val base64Decoded = tool.base64Decode(base64Encoded)
    println("Base64 编码: $base64Encoded")
    println("Base64 解码: $base64Decoded")
    
    // XOR 加密示例
    val xorEncrypted = tool.xorEncrypt(originalText, "secret")
    val xorDecrypted = tool.xorDecrypt(xorEncrypted, "secret")
    println("XOR 加密: $xorEncrypted")
    println("XOR 解密: $xorDecrypted")
    
    // 加密强度分析
    val strength = tool.analyzeEncryptionStrength(caesarEncrypted)
    println("加密强度分析: $strength")
}

Kotlin 代码说明:

这个 Kotlin 实现提供了完整的文本加密解密功能。TextEncryptionDecryption 类包含了多种加密算法的实现,每个方法都有明确的功能定义。Caesar 密码通过字符位移实现,Base64 通过位操作实现编码和解码,XOR 通过异或操作实现对称加密。此外,还提供了加密强度分析功能,可以评估加密文本的安全性。批量处理功能允许一次性处理多个文本,提高了工作效率。


JavaScript 编译代码

// TextEncryptionDecryption.js
// Kotlin 编译到 JavaScript 的版本

class TextEncryptionDecryption {
    // Caesar 密码加密
    caesarEncrypt(text, shift) {
        let result = '';
        for (let char of text) {
            if (char >= 'a' && char <= 'z') {
                const shifted = (char.charCodeAt(0) - 'a'.charCodeAt(0) + shift) % 26;
                result += String.fromCharCode('a'.charCodeAt(0) + shifted);
            } else if (char >= 'A' && char <= 'Z') {
                const shifted = (char.charCodeAt(0) - 'A'.charCodeAt(0) + shift) % 26;
                result += String.fromCharCode('A'.charCodeAt(0) + shifted);
            } else {
                result += char;
            }
        }
        return result;
    }
    
    // Caesar 密码解密
    caesarDecrypt(text, shift) {
        return this.caesarEncrypt(text, 26 - (shift % 26));
    }
    
    // Base64 编码
    base64Encode(text) {
        const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let result = '';
        let i = 0;
        
        while (i < text.length) {
            const b1 = text.charCodeAt(i) & 0xFF;
            const b2 = (i + 1 < text.length) ? text.charCodeAt(i + 1) & 0xFF : 0;
            const b3 = (i + 2 < text.length) ? text.charCodeAt(i + 2) & 0xFF : 0;
            
            const enc1 = b1 >> 2;
            const enc2 = ((b1 & 0x03) << 4) | (b2 >> 4);
            const enc3 = ((b2 & 0x0F) << 2) | (b3 >> 6);
            const enc4 = b3 & 0x3F;
            
            result += base64Chars[enc1];
            result += base64Chars[enc2];
            result += (i + 1 < text.length) ? base64Chars[enc3] : '=';
            result += (i + 2 < text.length) ? base64Chars[enc4] : '=';
            
            i += 3;
        }
        
        return result;
    }
    
    // Base64 解码
    base64Decode(text) {
        const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let result = '';
        let i = 0;
        
        while (i < text.length) {
            const enc1 = base64Chars.indexOf(text[i]);
            const enc2 = base64Chars.indexOf(text[i + 1]);
            const enc3 = (i + 2 < text.length && text[i + 2] !== '=') ? base64Chars.indexOf(text[i + 2]) : 0;
            const enc4 = (i + 3 < text.length && text[i + 3] !== '=') ? base64Chars.indexOf(text[i + 3]) : 0;
            
            const b1 = ((enc1 << 2) | (enc2 >> 4)) & 0xFF;
            result += String.fromCharCode(b1);
            
            if (text[i + 2] !== '=') {
                const b2 = (((enc2 & 0x0F) << 4) | (enc3 >> 2)) & 0xFF;
                result += String.fromCharCode(b2);
            }
            
            if (text[i + 3] !== '=') {
                const b3 = (((enc3 & 0x03) << 6) | enc4) & 0xFF;
                result += String.fromCharCode(b3);
            }
            
            i += 4;
        }
        
        return result;
    }
    
    // XOR 加密
    xorEncrypt(text, key) {
        let result = '';
        for (let i = 0; i < text.length; i++) {
            const charCode = text.charCodeAt(i) ^ key.charCodeAt(i % key.length);
            result += ('0' + charCode.toString(16)).slice(-2);
        }
        return result;
    }
    
    // XOR 解密
    xorDecrypt(hexText, key) {
        let result = '';
        for (let i = 0; i < hexText.length; i += 2) {
            const charCode = parseInt(hexText.substr(i, 2), 16) ^ key.charCodeAt((i / 2) % key.length);
            result += String.fromCharCode(charCode);
        }
        return result;
    }
    
    // 计算信息熵
    calculateEntropy(text) {
        const charFrequency = {};
        for (let char of text) {
            charFrequency[char] = (charFrequency[char] || 0) + 1;
        }
        
        let entropy = 0;
        for (let char in charFrequency) {
            const probability = charFrequency[char] / text.length;
            entropy -= probability * (Math.log(probability) / Math.log(2));
        }
        
        return entropy;
    }
    
    // 分析加密强度
    analyzeEncryptionStrength(text) {
        const uniqueChars = new Set(text).size;
        const totalChars = text.length;
        const entropy = this.calculateEntropy(text);
        const diversity = uniqueChars / totalChars;
        
        let strength = '弱';
        if (entropy > 7.0 && diversity > 0.5) {
            strength = '强';
        } else if (entropy > 5.0 && diversity > 0.3) {
            strength = '中';
        }
        
        return {
            entropy: entropy,
            uniqueChars: uniqueChars,
            totalChars: totalChars,
            diversity: diversity,
            strength: strength
        };
    }
    
    // 批量加密
    batchEncrypt(texts, method, key = '') {
        return texts.map(text => {
            switch (method) {
                case 'caesar':
                    return this.caesarEncrypt(text, 3);
                case 'base64':
                    return this.base64Encode(text);
                case 'xor':
                    return this.xorEncrypt(text, key);
                default:
                    return text;
            }
        });
    }
    
    // 批量解密
    batchDecrypt(texts, method, key = '') {
        return texts.map(text => {
            switch (method) {
                case 'caesar':
                    return this.caesarDecrypt(text, 3);
                case 'base64':
                    return this.base64Decode(text);
                case 'xor':
                    return this.xorDecrypt(text, key);
                default:
                    return text;
            }
        });
    }
}

// 使用示例
const tool = new TextEncryptionDecryption();

// Caesar 密码示例
const originalText = "Hello World";
const caesarEncrypted = tool.caesarEncrypt(originalText, 3);
const caesarDecrypted = tool.caesarDecrypt(caesarEncrypted, 3);
console.log("Caesar 加密:", caesarEncrypted);
console.log("Caesar 解密:", caesarDecrypted);

// Base64 编码示例
const base64Encoded = tool.base64Encode(originalText);
const base64Decoded = tool.base64Decode(base64Encoded);
console.log("Base64 编码:", base64Encoded);
console.log("Base64 解码:", base64Decoded);

// XOR 加密示例
const xorEncrypted = tool.xorEncrypt(originalText, "secret");
const xorDecrypted = tool.xorDecrypt(xorEncrypted, "secret");
console.log("XOR 加密:", xorEncrypted);
console.log("XOR 解密:", xorDecrypted);

// 加密强度分析
const strength = tool.analyzeEncryptionStrength(caesarEncrypted);
console.log("加密强度分析:", strength);

JavaScript 代码说明:

JavaScript 版本是 Kotlin 代码的直接转译。由于 JavaScript 和 Kotlin 在语法上有差异,我们需要进行相应的调整。例如,Kotlin 的 toByteArray() 在 JavaScript 中需要使用 charCodeAt() 来获取字符的 Unicode 值。Kotlin 的集合操作如 mapfilter 在 JavaScript 中也有对应的方法。此外,JavaScript 没有原生的字节数组,我们使用十六进制字符串来表示字节数据。整体逻辑和算法与 Kotlin 版本保持一致,确保跨平台的一致性。


ArkTS 调用代码

// TextEncryptionDecryption.ets
// ArkTS 中调用 JavaScript 加密解密工具的代码

import { TextEncryptionDecryption } from './TextEncryptionDecryption';

@Entry
@Component
struct TextEncryptionPage {
    @State inputText: string = '';
    @State encryptedText: string = '';
    @State decryptedText: string = '';
    @State selectedMethod: string = 'caesar';
    @State encryptionKey: string = 'secret';
    @State encryptionStrength: string = '';
    @State strengthDetails: string = '';
    
    private tool: TextEncryptionDecryption = new TextEncryptionDecryption();
    
    build() {
        Column() {
            // 标题
            Text('文本加密解密工具')
                .fontSize(24)
                .fontWeight(FontWeight.Bold)
                .margin({ top: 20, bottom: 20 })
            
            // 输入框
            TextInput({ placeholder: '请输入要加密的文本' })
                .value(this.inputText)
                .onChange((value: string) => {
                    this.inputText = value;
                })
                .margin({ bottom: 15 })
                .padding(10)
                .border({ width: 1, color: '#cccccc' })
            
            // 加密方法选择
            Row() {
                Text('加密方法:')
                    .fontSize(14)
                    .margin({ right: 10 })
                
                Select([
                    { value: 'Caesar 密码', text: 'caesar' },
                    { value: 'Base64 编码', text: 'base64' },
                    { value: 'XOR 加密', text: 'xor' }
                ])
                    .value(this.selectedMethod)
                    .onSelect((index: number, value?: string) => {
                        this.selectedMethod = value || 'caesar';
                    })
            }
            .margin({ bottom: 15 })
            .width('100%')
            
            // 密钥输入(仅 XOR 需要)
            if (this.selectedMethod === 'xor') {
                TextInput({ placeholder: '请输入加密密钥' })
                    .value(this.encryptionKey)
                    .onChange((value: string) => {
                        this.encryptionKey = value;
                    })
                    .margin({ bottom: 15 })
                    .padding(10)
                    .border({ width: 1, color: '#cccccc' })
            }
            
            // 加密按钮
            Button('加密')
                .width('100%')
                .height(40)
                .margin({ bottom: 10 })
                .onClick(() => {
                    if (this.inputText.length === 0) {
                        AlertDialog.show({
                            message: '请输入要加密的文本'
                        });
                        return;
                    }
                    
                    try {
                        switch (this.selectedMethod) {
                            case 'caesar':
                                this.encryptedText = this.tool.caesarEncrypt(this.inputText, 3);
                                break;
                            case 'base64':
                                this.encryptedText = this.tool.base64Encode(this.inputText);
                                break;
                            case 'xor':
                                this.encryptedText = this.tool.xorEncrypt(this.inputText, this.encryptionKey);
                                break;
                        }
                        
                        // 分析加密强度
                        const analysis = this.tool.analyzeEncryptionStrength(this.encryptedText);
                        this.encryptionStrength = analysis.strength;
                        this.strengthDetails = `熵值: ${analysis.entropy.toFixed(2)}, 多样性: ${(analysis.diversity * 100).toFixed(2)}%`;
                    } catch (error) {
                        AlertDialog.show({
                            message: '加密失败: ' + error.message
                        });
                    }
                })
            
            // 加密结果显示
            if (this.encryptedText.length > 0) {
                Column() {
                    Text('加密结果:')
                        .fontSize(14)
                        .fontWeight(FontWeight.Bold)
                        .margin({ bottom: 5 })
                    
                    Text(this.encryptedText)
                        .fontSize(12)
                        .selectable(true)
                        .padding(10)
                        .backgroundColor('#f5f5f5')
                        .borderRadius(4)
                        .margin({ bottom: 10 })
                    
                    Text('加密强度: ' + this.encryptionStrength)
                        .fontSize(12)
                        .fontColor('#ff6b6b')
                    
                    Text(this.strengthDetails)
                        .fontSize(11)
                        .fontColor('#999999')
                        .margin({ bottom: 10 })
                }
                .width('100%')
                .margin({ bottom: 15 })
            }
            
            // 解密按钮
            Button('解密')
                .width('100%')
                .height(40)
                .margin({ bottom: 10 })
                .onClick(() => {
                    if (this.encryptedText.length === 0) {
                        AlertDialog.show({
                            message: '请先进行加密操作'
                        });
                        return;
                    }
                    
                    try {
                        switch (this.selectedMethod) {
                            case 'caesar':
                                this.decryptedText = this.tool.caesarDecrypt(this.encryptedText, 3);
                                break;
                            case 'base64':
                                this.decryptedText = this.tool.base64Decode(this.encryptedText);
                                break;
                            case 'xor':
                                this.decryptedText = this.tool.xorDecrypt(this.encryptedText, this.encryptionKey);
                                break;
                        }
                    } catch (error) {
                        AlertDialog.show({
                            message: '解密失败: ' + error.message
                        });
                    }
                })
            
            // 解密结果显示
            if (this.decryptedText.length > 0) {
                Column() {
                    Text('解密结果:')
                        .fontSize(14)
                        .fontWeight(FontWeight.Bold)
                        .margin({ bottom: 5 })
                    
                    Text(this.decryptedText)
                        .fontSize(12)
                        .selectable(true)
                        .padding(10)
                        .backgroundColor('#f5f5f5')
                        .borderRadius(4)
                        .margin({ bottom: 10 })
                    
                    if (this.decryptedText === this.inputText) {
                        Text('✓ 解密成功,与原文一致')
                            .fontSize(12)
                            .fontColor('#52c41a')
                    } else {
                        Text('✗ 解密结果与原文不一致')
                            .fontSize(12)
                            .fontColor('#ff6b6b')
                    }
                }
                .width('100%')
                .margin({ bottom: 15 })
            }
            
            // 清空按钮
            Button('清空')
                .width('100%')
                .height(40)
                .onClick(() => {
                    this.inputText = '';
                    this.encryptedText = '';
                    this.decryptedText = '';
                    this.encryptionStrength = '';
                    this.strengthDetails = '';
                })
        }
        .padding(20)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffffff')
    }
}

ArkTS 代码说明:

ArkTS 是鸿蒙系统的应用开发语言,基于 TypeScript 扩展。这个示例展示了如何在 ArkTS 中构建一个完整的加密解密用户界面。页面包含了文本输入框、加密方法选择、密钥输入、加密和解密按钮等组件。当用户点击加密按钮时,系统调用 JavaScript 版本的加密工具进行加密操作,并显示加密结果和强度分析。解密按钮可以将加密的文本恢复为原始文本。此外,页面还提供了验证功能,检查解密后的文本是否与原始文本一致。整个界面采用了现代化的设计,提供了良好的用户体验。


实战案例

案例 1: 用户密码存储

在实际应用中,用户密码不应该以明文形式存储。我们可以使用加密工具来保护用户密码:

// 密码存储示例
val tool = TextEncryptionDecryption()
val userPassword = "MySecurePassword123"
val encryptionKey = "application_secret_key"

// 加密密码
val encryptedPassword = tool.xorEncrypt(userPassword, encryptionKey)
println("加密后的密码: $encryptedPassword")

// 存储到数据库
// database.saveUser(userId, encryptedPassword)

// 验证密码时
val inputPassword = "MySecurePassword123"
val decryptedPassword = tool.xorDecrypt(encryptedPassword, encryptionKey)
val isPasswordCorrect = inputPassword == decryptedPassword
println("密码验证结果: $isPasswordCorrect")

这个案例展示了如何使用 XOR 加密来保护用户密码。在实际应用中,应该使用更强大的加密算法如 AES 或 bcrypt,但这个例子说明了基本的加密流程。

案例 2: API 通信加密

在客户端和服务器之间传输敏感数据时,可以使用 Base64 编码和加密:

// API 通信示例
val tool = TextEncryptionDecryption()
val sensitiveData = "user_id=12345&action=transfer&amount=1000"

// 加密数据
val encryptedData = tool.base64Encode(sensitiveData)
println("加密后的数据: $encryptedData")

// 发送到服务器
// val response = apiClient.post("/api/secure", encryptedData)

// 服务器接收并解密
val decryptedData = tool.base64Decode(encryptedData)
println("解密后的数据: $decryptedData")

这个案例展示了如何在 API 通信中使用 Base64 编码来保护数据。虽然 Base64 不是真正的加密,但它可以防止简单的文本扫描和中间人攻击。

案例 3: 批量数据加密

当需要加密大量数据时,可以使用批量处理功能:

// 批量加密示例
val tool = TextEncryptionDecryption()
val userMessages = listOf(
    "Hello, this is message 1",
    "Hello, this is message 2",
    "Hello, this is message 3"
)

// 批量加密
val encryptedMessages = tool.batchEncrypt(userMessages, "caesar")
println("加密后的消息: $encryptedMessages")

// 批量解密
val decryptedMessages = tool.batchDecrypt(encryptedMessages, "caesar")
println("解密后的消息: $decryptedMessages")

// 验证
val isCorrect = userMessages == decryptedMessages
println("批量处理验证结果: $isCorrect")

这个案例展示了如何使用批量处理功能来提高工作效率。当需要处理大量数据时,批量操作可以减少代码的复杂性和提高性能。


最佳实践

1. 密钥管理

  • 安全存储:密钥应该存储在安全的位置,如密钥管理服务或环境变量中,而不是硬编码在代码中
  • 定期轮换:定期更换加密密钥,以防止长期密钥泄露的风险
  • 访问控制:限制对密钥的访问权限,只有授权的应用和用户才能访问密钥

2. 算法选择

  • 强度评估:根据数据的敏感性选择合适的加密算法。对于高度敏感的数据,应该使用 AES-256 等强加密算法
  • 标准算法:使用经过验证的标准加密算法,避免使用自定义的加密算法
  • 定期更新:随着密码学的发展,应该定期更新加密算法,以适应新的安全威胁

3. 错误处理

  • 异常捕获:在加密和解密操作中捕获异常,并提供有意义的错误信息
  • 日志记录:记录加密操作的日志,以便进行审计和故障排查
  • 用户提示:向用户提供清晰的错误提示,帮助他们理解问题所在

4. 性能优化

  • 缓存:对于频繁使用的加密结果,可以使用缓存来提高性能
  • 异步处理:对于大量数据的加密操作,可以使用异步处理来避免阻塞主线程
  • 内存管理:在处理大量数据时,注意内存使用情况,及时释放不需要的资源

5. 跨平台一致性

  • 单元测试:编写单元测试来验证 Kotlin、JavaScript 和 ArkTS 版本的一致性
  • 集成测试:进行集成测试,确保在不同平台上的行为一致
  • 版本管理:使用版本管理系统来跟踪代码的变化,确保跨平台的同步更新

总结

文本加密解密工具是现代应用开发中的一个重要组件。通过使用 Kotlin Multiplatform,我们可以编写一次代码,然后在多个平台上运行,大大提高了开发效率和代码的可维护性。这个案例展示了如何实现多种加密算法、进行加密强度分析、处理批量数据等功能。

在实际应用中,应该根据具体的需求选择合适的加密算法,并遵循最佳实践来确保数据的安全性。同时,应该定期进行安全审计和更新,以应对不断变化的安全威胁。通过合理使用加密技术,我们可以保护用户的隐私和数据安全,提高应用的信任度和用户满意度。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐