对称加密后的C#字符串字节转换

时间:2015-08-09 07:04:40

标签: c# string byte type-conversion encryption-symmetric

我一直致力于对称加密,但突然出现了疯狂的错误。我无法从字节转换回字符串。之前我曾经多次使用类似的方法对数据进行数据操作,但这次我被卡住了。首先,我在神秘错误之后使用 Encoding.UTF8.GetBytes() Encoding.UTF8.GetString()字节,想到这可能是基于.net框架内的文化。所以我复制了“旧的”代码用于字符串字节[]转换只是为了检查什么是错的。似乎没什么不对的,但它根本就没有用。

Ofc的第一印象是它与对称加密有某种关系,但我仔细检查从它们进出的字节,它们是相等的。

(附加信息:我目前正在研究.net 4客户端配置文件)

有什么想法吗?

public class Test
{
    public static byte[] GetBytesFromString(string str)
    {
        var bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    public static string GetStringFromBytes(byte[] bytes)
    {
        var chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }

    public static bool ArraysAreEqual<T>(T[] array0, T[] array1)
    {
        if (array0.Length != array1.Length) return false;
        return !array0.Where((t, i) => t.Equals(array1[i])).Any();
    }

    public static void Run()
    {
        var aes = new System.Security.Cryptography.AesCryptoServiceProvider();
        byte[] key = aes.Key;
        byte[] iv = aes.IV;

        string text = "hello World!"; // initial text

        byte[] plainBytes = GetBytesFromString(text);       // get some bytes
        string plainText = GetStringFromBytes(plainBytes);  // reverse bytes back;
        if (string.Compare(text, plainText, StringComparison.InvariantCulture) != 0)    // check strings
            throw new NotSupportedException();
        System.Diagnostics.Debug.WriteLine(plainText);      // all good!

        // up to this point I assume GetBytesFromString<->GetStringFromBytes methods works fine

        byte[] encrytpedBytes = AES.AesEncrypt(plainBytes, key, iv);       // implementation of encryption
        byte[] decryptedBytes = AES.AesDecrypt(encrytpedBytes, key, iv);   // implementation of decryption

        if (ArraysAreEqual(encrytpedBytes, decryptedBytes)) // check arrays
            throw new NotSupportedException();
        // I even print them to check manually.. by my eyes..
        System.Diagnostics.Debug.WriteLine(System.BitConverter.ToString(encrytpedBytes));   
        System.Diagnostics.Debug.WriteLine(System.BitConverter.ToString(decryptedBytes));

        string decrytpedText = GetStringFromBytes(decryptedBytes);  // and..... we get incorrect string! :/
        System.Diagnostics.Debug.WriteLine(decrytpedText);
    }
}

输出:

hello World!
22-CD-FF-14-69-37-0C-CC-44-C6-F6-61-95-1A-AA-0A
22-CD-FF-14-69-37-0C-CC-44-C6-F6-61-95-1A-AA-0A
촢ᓿ㝩찌완懶᪕પ

谢谢!

0 个答案:

没有答案