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

时间:2016-02-26 05:46:58

标签: javascript c# jquery asp.net json

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

我可以将长字符串加密为short并再次解密以在c#或javascript中使用吗?

1 个答案:

答案 0 :(得分:0)

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

这将是实际的代码:

trimmed_stocks = [ x for x in stocks if not 'Berhad' in x ]

一个例子:

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());
    }
}

您将无法在控制台窗口上呈现它,因为文本现在是UTF8,但string text = "This is some large text which will be reduced by half!"; string encoded = text.Encode(); 保留的是encoded

正如您所看到的,我们设法将桔獩椠⁳潳敭氠牡敧琠硥⁴桷捩⁨楷汬戠⁥敲畤散⁤祢栠污Ⅶ个字符长字符串编码为只有54个字符的字符串。

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

27