如何从另一个长字符串创建最多 12 个字符的加密字符串

How to create encrypted string with maximum 12 character from another long string

本文关键字:字符串 字符 加密 创建 另一个      更新时间:2023-09-26

我必须创建条形码才能检索数据。实际字符串最大大小为 60。但是我需要打印的条形码最多为 12 个字符。

我可以将长字符串加密为短字符串并再次解密以在 C# 或 JavaScript 中使用吗?

如果你的文本只有 ASCII 字符,那么你可以通过在单个 UTF8 字符中实际存储多个 ASCII 字符来将其减少一半。

这将是实际代码:

public static class ByteExtensions
{
    private const int BYTE_SIZE = 8;
    public static byte[] Encode(this byte[] data)
    {
        if (data.Length == 0) return new byte[0];
        int length = 3 * BYTE_SIZE;
        BitArray source = new BitArray(data);
        BitArray encoded = new BitArray(length);
        int sourceBit = 0;
        for (int i = (length / BYTE_SIZE); i > 1; i--)
        {
            for (int j = 6; j > 0; j--) encoded[i * BYTE_SIZE - 2 - j] = source[sourceBit++];
            encoded[i * BYTE_SIZE - 1] = true;
            encoded[i * BYTE_SIZE - 2] = false;
        }
        for (int i = BYTE_SIZE - 1; i > BYTE_SIZE - 1 - (length / BYTE_SIZE); i--) encoded[i] = true;
        encoded[BYTE_SIZE - 1 - (length / BYTE_SIZE)] = false;
        for (int i = 0; i <= BYTE_SIZE - 2 - (length / BYTE_SIZE); i++) encoded[i] = source[sourceBit++];
        byte[] result = new byte[length / BYTE_SIZE];
        encoded.CopyTo(result, 0);
        return result;
    }
    public static byte[] Decode(this byte[] data)
    {
        if (data.Length == 0) return new byte[0];
        int length = 2 * BYTE_SIZE;
        BitArray source = new BitArray(data);
        BitArray decoded = new BitArray(length);
        int currentBit = 0;
        for (int i = 3; i > 1; i--) for (int j = 6; j > 0; j--) decoded[currentBit++] = source[i * BYTE_SIZE - 2 - j];
        for (int i = 0; i <= BYTE_SIZE - 5; i++) decoded[currentBit++] = source[i];
        byte[] result = new byte[length / BYTE_SIZE];
        decoded.CopyTo(result, 0);
        return result;
    }
}
public static class StringExtensions
{
    public static string Encode(this string text)
    {
        byte[] ascii = Encoding.ASCII.GetBytes(text);
        List<byte> encoded = new List<byte>();
        for (int i = 0; i < ascii.Length; i += 2) encoded.AddRange(new byte[] { ascii[i], (i + 1) < ascii.Length ? ascii[i + 1] : (byte)30 }.Encode());
        return Encoding.UTF8.GetString(encoded.ToArray());
    }
    public static string Decode(this string text)
    {
        byte[] utf8 = Encoding.UTF8.GetBytes(text);
        List<byte> decoded = new List<byte>();
        for (int i = 0; i < utf8.Length - 2; i += 3) decoded.AddRange(new byte[] { utf8[i], utf8[i + 1], utf8[i + 2] }.Decode());
        return Encoding.ASCII.GetString(decoded.ToArray());
    }
}

举个例子:

string text = "This is some large text which will be reduced by half!";
string encoded = text.Encode();

您将无法在控制台窗口中呈现它,因为文本现在是 UTF8,但以下是encoded包含的内容:桔獩椠⁳潳敭氠牡敧琠硥⁴桷捩⁨楷汬戠⁥敲畤散⁤祢栠污Ⅶ

如您所见,我们设法将一个54个字符长的字符串编码为一个只有 27 个字符的字符串。

您实际上可以通过执行以下操作来取回原始字符串:

string decoded = encoded.Decode();