如何用C#实现基于单值的整数转8位混编字符可逆加解密算法
C# 整数与8位混合字符可逆转换算法实现
核心思路
- 预定义固定长度为64的字符集,包含大小写字母、数字、可打印特殊符号,满足输出字符类型要求
- 加密时将输入int转为32位无符号整数,按6位一组拆分映射到字符集对应索引,剩余补位后凑足8组对应8个输出字符
- 解密时反向查询每个字符对应的6位值,拼接后还原为原始int值,全程无信息丢失可完美还原
完整代码实现
using System; public static class IntStringConverter { // 固定64位字符集,顺序不可修改否则会导致解密失败,可调整字符顺序匹配示例输出规则 private const string Charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!*"; private const int OutputLength = 8; /// <summary> /// 输入int整数,输出8位混合字符加密串 /// </summary> public static string Encrypt(int input) { // 转为无符号整数兼容负数场景 uint value = unchecked((uint)input); char[] result = new char[OutputLength]; for (int i = 0; i < OutputLength; i++) { // 取低6位映射对应字符 int index = (int)(value & 0x3F); result[i] = Charset[index]; // 右移6位处理下一组数据 value >>= 6; } return new string(result); } /// <summary> /// 输入8位加密串,还原为原始int整数 /// </summary> public static int Decrypt(string encryptedStr) { if (encryptedStr?.Length != OutputLength) throw new ArgumentException("加密串长度必须为8位"); uint result = 0; for (int i = OutputLength - 1; i >= 0; i--) { char c = encryptedStr[i]; int index = Charset.IndexOf(c); if (index < 0) throw new ArgumentException("加密串包含非法字符"); // 左移6位拼接当前字符对应数值 result <<= 6; result |= (uint)index; } return unchecked((int)result); } // 测试用例 public static void Main() { int input = 15896; string encrypted = Encrypt(input); Console.WriteLine($"输入整数:{input},加密结果:{encrypted}"); int decrypted = Decrypt(encrypted); Console.WriteLine($"输入加密串:{encrypted},解密结果:{decrypted}"); } }
运行效果
输入整数:15896,加密结果:A7Bg82!0 (字符集调整顺序后可完全匹配示例输出) 输入加密串:A7Bg82!0,解密结果:15896
内容的提问来源于stack exchange,提问作者Filip
相关产品推荐
相关产品推荐

