使用较小的结果字符串进行简单的字符串加密/解密

use*_*119 9 c# encryption

我需要加密一个字符串,然后再次解密它.

我在这里实现了解决方案并且它运行良好,但结果字符串不合适,因为它需要简单且足够短以供用户使用.

我正在加密递增数据库ID(从1开始)并且不会超过500.理想情况下,我希望加密字符串的长度不超过6个字符.

任何想法赞赏..

编辑:这是一个冗长的形式,用户可以在以后使用此生成的字符串恢复

ner*_*rdo 6

您可以在CTR模式下使用AES 而无需任何填充.在这种模式下,有一个加密的计数器,然后结果与你的明文xor'd,这是数字.结果应该很小,你将获得AES的加密,这将比你使用的任何替换密码(你可能可以手动破解)更好.您必须获得BouncyCastle加密库,因为Rijndael的Microsoft实现没有将CTR作为可用模式.下面是您需要实现的AES类的示例.以及加密和解密的一个例子.

using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;

public class AES
{
    private readonly Encoding encoding;

    private SicBlockCipher mode;


    public AES(Encoding encoding)
    {
        this.encoding = encoding;
        this.mode = new SicBlockCipher(new AesFastEngine());
    }

    public static string ByteArrayToString(byte[] bytes)
    {
        return BitConverter.ToString(bytes).Replace("-", string.Empty);
    }

    public static byte[] StringToByteArray(string hex)
    {
        int numberChars = hex.Length;
        byte[] bytes = new byte[numberChars / 2];

        for (int i = 0; i < numberChars; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        }

        return bytes;
    }


    public string Encrypt(string plain, byte[] key, byte[] iv)
    {
        byte[] input = this.encoding.GetBytes(plain);

        byte[] bytes = this.BouncyCastleCrypto(true, input, key, iv);

        string result = ByteArrayToString(bytes);

        return result;
    }


    public string Decrypt(string cipher, byte[] key, byte[] iv)
    {
        byte[] bytes = this.BouncyCastleCrypto(false, StringToByteArray(cipher), key, iv);

        string result = this.encoding.GetString(bytes);

        return result;
    }


    private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, byte[] key, byte[] iv)
    {
        try
        {
            this.mode.Init(forEncrypt, new ParametersWithIV(new KeyParameter(key), iv));

            BufferedBlockCipher cipher = new BufferedBlockCipher(this.mode);

            return cipher.DoFinal(input);
        }
        catch (CryptoException)
        {
            throw;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例用法

string test = "1";

AES aes = new AES(System.Text.Encoding.UTF8);

RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
byte[] key = new byte[32];
byte[] iv = new byte[32];

// Generate random key and IV
rngCsp.GetBytes(key);
rngCsp.GetBytes(iv);

string cipher = aes.Encrypt(test, key, iv);

string plaintext = aes.Decrypt(cipher, key, iv);

Response.Write(cipher + "<BR/>");

Response.Write(plaintext);
Run Code Online (Sandbox Code Playgroud)

输出示例

CB
1 
Run Code Online (Sandbox Code Playgroud)


use*_*326 1

如果您希望它简单,可以使用 6 个字母的主键,将其添加到 6 个字母输入中,根据允许的输入字符进行取模

就像=1

b=2

c = 3

然后简单地添加一个数字 a + 13 mod 24 > ...

不会说它安全,但它按照您的要求简单您也可以做一些组合,例如下一个字符被解码为+xx