简单的方法来加密/混淆在.NET中使用秘密的字节数组?数组、方法来、字节、秘密

2023-09-04 09:15:54 作者:杀死庸碌

我在寻找一种方式来加密/混淆(当然解密/反混淆)使用.NET 3.5的字节数组。

I'm looking for a way to encrypt/obfuscate (and of course decrypt/deobfuscate) an array of byte using .NET 3.5.

基本上是:

byte[] aMixedUp = Encrypt(aMyByteData, "THIS IS THE SECRET KEY USED TO ENCRYPT");

和在另一侧

byte[] aDecrypted = Decrypt(aMixedUp, "THIS IS THE SECRET KEY USED TO ENCRYPT");

有不必是防弹。这个想法仅仅是prevent用户直接看到的就是在它们映射到ASCII码的情况下,字节,但它应该是更好然后ROT13。

It does not have to be bullet proof. The idea is just to prevent users from directly seeing what's in the bytes in case they map to ASCII but it should be better then ROT13.

有什么在.NET库,我可以很容易地使用?

Is there something in the .NET libraries I can easily use?

推荐答案

下面是一些code我写的加密/解密的字符串。加密的字符串是Base64的EN codeD,便于序列化到XML的,等等。你可以很容易地转换这code直接使用字节数组,而不是字符串的工作。

Here's some code I wrote to encrypt/decrypt a string. The encrypted string is Base64 encoded for ease of serialization to XML, etc. You could easily convert this code to work directly with byte arrays instead of strings.

/// <summary>
/// Create and initialize a crypto algorithm.
/// </summary>
/// <param name="password">The password.</param>
private static SymmetricAlgorithm GetAlgorithm(string password)
{
    var algorithm = Rijndael.Create();
    var rdb = new Rfc2898DeriveBytes(password, new byte[] {
        0x53,0x6f,0x64,0x69,0x75,0x6d,0x20,             // salty goodness
        0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
    });
    algorithm.Padding = PaddingMode.ISO10126;
    algorithm.Key = rdb.GetBytes(32);
    algorithm.IV = rdb.GetBytes(16);
    return algorithm;
}


/// <summary>
/// Encrypts a string with a given password.
/// </summary>
/// <param name="clearText">The clear text.</param>
/// <param name="password">The password.</param>
public static string EncryptString(string clearText, string password)
{
    var algorithm = GetAlgorithm(password);
    var encryptor = algorithm.CreateEncryptor();
    var clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (var ms = new MemoryStream())
    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
    {
        cs.Write(clearBytes, 0, clearBytes.Length);
        cs.Close();
        return Convert.ToBase64String(ms.ToArray());
    }
}

/// <summary>
/// Decrypts a string using a given password.
/// </summary>
/// <param name="cipherText">The cipher text.</param>
/// <param name="password">The password.</param>
public static string DecryptString(string cipherText, string password)
{
    var algorithm = GetAlgorithm(password);
    var decryptor = algorithm.CreateDecryptor();
    var cipherBytes = Convert.FromBase64String(cipherText);
    using (var ms = new MemoryStream())
    using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
    {
        cs.Write(cipherBytes, 0, cipherBytes.Length);
        cs.Close();
        return Encoding.Unicode.GetString(ms.ToArray());
    }
}