如何在不将字符串编码为byte []的情况下完成加密?

时间:2014-05-26 20:14:25

标签: c# tripledes

我一直试图了解TripleDES的加密/解密代码。我在google中看到了很多代码,下面显示的代码就是其中之一。

static void Main(string[] args)
    {

        string original = "Here is some data to encrypt!";
        TripleDESCryptoServiceProvider myTripleDES = new TripleDESCryptoServiceProvider();
        byte[] encrypted = EncryptStringToBytes(original, myTripleDES.Key, myTripleDES.IV);
        string encrypt = Convert.ToBase64String(encrypted);
        string roundtrip = DecryptStringFromBytes(encrypted, myTripleDES.Key, myTripleDES.IV);
        Console.WriteLine("encryted:   {0}", encrypt);
        Console.WriteLine("Round Trip: {0}", roundtrip);
        Console.ReadLine();
    }



    static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {

        byte[] encrypted; 
        using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
        {
            tdsAlg.Key = Key;
            tdsAlg.IV = IV;
            ICryptoTransform encryptor = tdsAlg.CreateEncryptor(tdsAlg.Key, tdsAlg.IV);
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        return encrypted;
    }


    static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
    { 
        string plaintext = null; 
        using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
        {
            tdsAlg.Key = Key;
            tdsAlg.IV = IV;
            ICryptoTransform decryptor = tdsAlg.CreateDecryptor(tdsAlg.Key, tdsAlg.IV);
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;

    } 

代码中没有错误。我工作得很好。但奇怪的是我注意到plainText从未编码过。没有类似Encoding.Unicode.GetBytes(plainText);Encoding.UTF8.GetBytes(plainText);或类似的行。所以,我的问题是,(在代码中)作为字符串的plainText如何转换为加密字节?流内是否有任何工作?如果那么那么在哪里以及如何?据我所知,流之间没有这样的行将字符串转换为字节。那么,如果没有这种基本转换,整体代码如何工作呢?

更新: 这段代码真的是一个有效的代码吗?

2 个答案:

答案 0 :(得分:1)

您正在将明文发送到行swEncrypt.Write(plaintext)中的加密流。这会进行字节转换。

答案 1 :(得分:1)

StreamWriter正在进行编码。正在使用的constructor指定UTF-8编码:

  

此构造函数使用UTF-8编码创建StreamWriter而不使用   字节顺序标记(BOM)