ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

设计一个最简单的字符串加密

设计一个最简单的字符串加密
package com.android.format.lifecycle fun genKey(): String { return "ABCDEFGHIJKLMNOPQRSTUVWXYZ" .toCharArray() .apply { shuffle() } .concatToString() } //将所有的字符转成16进制,比如{},\n //**`.padStart(2, '0')`** //如果 16 进制结果只有 1 位(0~f),**左边补 0,固定占 2 个字符** //例:`10` → `"a"` → 补零后变成 `"0a"` //非常关键:保证 hex 字符串总长度一定是偶数,满足`decode2`要求(`require(hexString.length % 2 ==0)`) fun encode2(str: String): String { return str.toByteArray(Charsets.UTF_8).joinToString("") { it.toUByte().toString(16).uppercase().padStart(2, '0') } } fun decode2(hexString: String): String? { require(hexString.length % 2 == 0) { "Invalid hex string" } val binaryData = hexString.chunked(2).map { val high = it[0].digitToIntOrNull(16) ?: -1 val low = it[1].digitToIntOrNull(16) ?: -1 require(high >=0 && low >=0) { "Invalid hex string" } ((high shl 4) + low).toByte() }.toByteArray() return String(binaryData, Charsets.UTF_8) } fun decode(text: String, key: String): String? { val stringBuilder = StringBuilder() for (i in 0 until text.length) { val c = text[i].toString() var index = key.indexOf(c) if (index != -1) { index-- if (index < 0) { index = key.length - 1 } stringBuilder.append(key[index]) } else { stringBuilder.append(c) } } return stringBuilder.toString() //return decode2(stringBuilder.toString()); } fun encode(text: String, key: String): String { val stringBuilder = StringBuilder() for (i in text.indices) { val c = text[i] val index = key.indexOf(c) if (index != -1) { // 找到字符,取密钥中的下一个字符 var nextIndex = index + 1 if (nextIndex >= key.length) { nextIndex = 0 } stringBuilder.append(key[nextIndex]) } else { // 未在密钥中找到,原样保留 stringBuilder.append(c) } } return stringBuilder.toString() } fun main(){ val str = "https://www.kk.vip"; val str2 = "{\n" + "\"800021\":\"https://www.aa.com\",\n" + "\"28\":\"https://www.bb.club\",\n" + "\"30\":\"https://www.cc.net\",\n" + "\"33\":\"https://www.dd.net\",\n" + "\"32\":\"https://www.ee.net\",\n" + "\"38\":\"https://www.ff.fun\",\n" + "\"41\":\"https://www.gg.club\",\n" + "\"42\":\"https://www.hh.mobi\",\n" + "\"43\":\"https://www.ii.com\"\n" + "\"154\":\"https://www.jj.vip\"\n"+ "}" val encodeStr = encode2(str2) System.out.println(encodeStr) System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxx") val key = genKey(); System.out.println(key) System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxx") val encodeStr2 = encode(encodeStr,key); System.out.println(encodeStr2) System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxx") val decodeStr1 = decode(encodeStr2,key) System.out.println(decodeStr1) val decodeStr2 = decode2(decodeStr1!!) System.out.println(decodeStr2) }
RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进