C#我的加密和解密功能一段时间无法使用 [英] c# My encrypt and decrypt function is not working some time

查看:60
本文介绍了C#我的加密和解密功能一段时间无法使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将正常字母传递给我的加密和解密功能时,它可以按预期工作,但是当我将字母数字文本传递给我的加密和解密功能时,则它无法正常工作.

例如,当我通过加密("test1")或解密("test1")时,它就无法正常工作.特别解密,不适用于字母数字大小写.

我想要重组我的加密和解密功能,因此无论我通过该功能的任何值都可以工作.假设我可以传递带有特殊字符的字母数字数据.因此,请查看代码并附带经过纠正的版本.

围绕加密/解密的小包装

私有字符串加密(字符串消息)
        {
            EncryptClass.EncryptClass ec =新的EncryptClass.EncryptClass();
            字符串encryStr = ec.custEncrypt(message);
            返回encryStr;
        }

        私有字符串解密(字符串消息)
        {
            EncryptClass.EncryptClass ec =新的EncryptClass.EncryptClass();
            字符串cryptoStr =消息;
            返回ec.custDecrypt(decryptStr);
        } 

用于加密和解密的完整代码

公共类EncryptClass
    {
        DESCryptoServiceProvider rj;
        byte []键=新的byte [] {11,9,3,4,1,8,12,7};
        byte [] IV =新的byte [] {1,8,7,16,1,9,0,3};
        公共EncryptClass()
        {
            //
            //TODO:在此处添加构造函数逻辑
            //
            rj =新的DESCryptoServiceProvider();
        }

        //用于加密
        公共字符串custEncrypt(字符串消息)
        {
            //创建一个内存流
            MemoryStream ciphertextmem =新的MemoryStream();
            //以写模式创建加密流
            CryptoStream crystm =新的CryptoStream(ciphertextmem,rj.CreateEncryptor(key,IV),CryptoStreamMode.Write);
            //将传递的纯文本字符串编码为Unicode字节流
            Byte [] plaintextbyte =新的UnicodeEncoding().GetBytes(message);
            //将纯文本字节流写入CryptoStream
            crystm.Write(plaintextbyte,0,plaintextbyte.Length);
            //不要忘记关闭流
            crystm.Close();
            //提取密文字节流并关闭MemoryStream
            Byte [] ciphertextbyte = ciphertextmem.ToArray();
            ciphertextmem.Close();
            //将密文字节编码为Unicode字符串
            字符串ciphertext =新的UnicodeEncoding().GetString(ciphertextbyte);
            返回密文;
            //返回加密" +讯息;


        }

        //用于解密
        公共字符串custDecrypt(字符串消息)
        {
            //创建一个内存流,CryptoStream将从中读取密文
            MemoryStream ciphertextmem =新的MemoryStream(新的UnicodeEncoding().GetBytes(消息));

            //在读取模式下创建一个CryptoStream;用Rijndael的Decryptor ICryptoTransform初始化
            CryptoStream crystm =新的CryptoStream(ciphertextmem,rj.CreateDecryptor(key,IV),CryptoStreamMode.Read);

            //创建一个临时内存流,将其复制到
            //来自CryptoStream的纯文本字节数组

            MemoryStream plaintextmem =新的MemoryStream();
            做
            {
                //创建一个字节数组,我们将在其中读取明文
                //来自CryptoStream
                Byte [] buf = new Byte [100];

                //从CryptoStream读取纯文本
                int actualbytesread = crystm.Read(buf,0,100);

                //如果我们已经到达流的末尾,请退出循环
                如果(0 ==实际读取的字节数)
                    休息;

                //将纯文本字节数组复制到MemoryStream
                plaintextmem.Write(buf,0,actualbytesread);

            } while(true);

            //不要忘记关闭流
            crystm.Close();
            ciphertextmem.Close();

            //提取明文字节流并关闭MemoryStream
            Byte [] plaintextbyte = plaintextmem.ToArray();
            plaintextmem.Close();

            //将纯文本字节编码为Unicode字符串
            字符串plaintext =新的UnicodeEncoding().GetString(plaintextbyte);

            返回明文;

            //返回拒绝" +消息;
        }
    } 

请查看我的代码和纠正区域,如果我仅传递文本,或者如果我传递带有数字数据的文本或带有特殊字符的字母数字,它应该可以工作.

寻求帮助.

解决方案

当您执行以下操作时,我会看到一个问题:

字符串 密文 = UnicodeEncoding (). GetString ( 密文字节 ) ;
          

密文字节是一个字节数组,其中包含加密文本的二进制值.这些二进制值可以具有任何可能的值,并且其中许多值将不等同于任何合法的Unicode编码.因此,GetString将返回 一个无法预测的字符串,当您想要对密文进行解码时,您将无法将其转换回字节.当您足够幸运的是,加密值恰好都是合法的Unicode编码时,它可能适用于某些字符串. 对于其他字符串,它将失败.包含字母数字文本"不是问题.就像您提到的一样,但是运气取决于纯文本如何转换为密文.

如果您需要将编码后的内容作为字符串而不是字节数组来处理,那么最好通过对所有可能的字节值都有效的机制来转换字节数组.例如,您可以使用 Convert.ToBase64 ,而不是UnicodeEncoding.GetString.而且,显然,当您要执行解码时,使用Convert.FromBase64.


when i am passing normal alphabet to my encrypt and decrypt function then it is working as expected but when i am passing alphanumeric text to encrypt and decrypt function then it is not working.

say when i pass encrypt("test1") or decrypt("test1") then it is not working. specially decrypt not working with alphanumeric case.

i want to restructure my encrypt and decrypt function as a result whatever value i pass the function can work. suppose i may pass alpha numeric data with special character. so plerase see the code and come with rectified version.

a small wrapper around encrypt/decrypt

       private string encrypt(string message)
        {
            EncryptClass.EncryptClass ec = new EncryptClass.EncryptClass();
            string encryStr = ec.custEncrypt(message);
            return encryStr;
        }

        private string decrypt(string message)
        {
            EncryptClass.EncryptClass ec = new EncryptClass.EncryptClass();
            string decryptStr = message;
            return ec.custDecrypt(decryptStr);
        }

full code for encrypt ans decrypt

    public class EncryptClass
    {
        DESCryptoServiceProvider rj;
        byte[] key = new byte[] { 11, 9, 3, 4, 1, 8, 12, 7 };
        byte[] IV = new byte[] { 1, 8, 7, 16, 1, 9, 0, 3 };
        public EncryptClass()
        {
            //
            // TODO: Add constructor logic here
            //
            rj = new DESCryptoServiceProvider();
        }

        // for encryption
        public string custEncrypt(string message)
        {
            //create a memory stream
            MemoryStream ciphertextmem = new MemoryStream();
            //create a crypto stream in write mode
            CryptoStream crystm = new CryptoStream(ciphertextmem, rj.CreateEncryptor(key, IV), CryptoStreamMode.Write);
            //Encode the passed plain text string into Unicode byte stream
            Byte[] plaintextbyte = new UnicodeEncoding().GetBytes(message);
            //Write the plaintext byte stream to CryptoStream
            crystm.Write(plaintextbyte, 0, plaintextbyte.Length);
            //don't forget to close the stream
            crystm.Close();
            //Extract the ciphertext byte stream and close the MemoryStream
            Byte[] ciphertextbyte = ciphertextmem.ToArray();
            ciphertextmem.Close();
            //Encode the ciphertext byte into Unicode string
            string ciphertext = new UnicodeEncoding().GetString(ciphertextbyte);
            return ciphertext;
            //return "encry " + message;


        }

        // for decryption
        public string custDecrypt(string message)
        {
            //Create a memory stream from which CryptoStream will read the cipher text
            MemoryStream ciphertextmem = new MemoryStream(new UnicodeEncoding().GetBytes(message));

            //Create a CryptoStream in Read Mode; initialise with the Rijndael's Decryptor ICryptoTransform
            CryptoStream crystm = new CryptoStream(ciphertextmem, rj.CreateDecryptor(key, IV), CryptoStreamMode.Read);

            //Create a temporary memory stream to which we will copy the 
            //plaintext byte array from CryptoStream

            MemoryStream plaintextmem = new MemoryStream();
            do
            {
                //Create a byte array into which we will read the plaintext 
                //from CryptoStream
                Byte[] buf = new Byte[100];

                //read the plaintext from CryptoStream
                int actualbytesread = crystm.Read(buf, 0, 100);

                //if we have reached the end of stream quit the loop
                if (0 == actualbytesread)
                    break;

                //copy the plaintext byte array to MemoryStream
                plaintextmem.Write(buf, 0, actualbytesread);

            } while (true);

            //don't forget to close the streams
            crystm.Close();
            ciphertextmem.Close();

            //Extract the plaintext byte stream and close the MemoryStream
            Byte[] plaintextbyte = plaintextmem.ToArray();
            plaintextmem.Close();

            //Encode the plaintext byte into Unicode string
            string plaintext = new UnicodeEncoding().GetString(plaintextbyte);

            return plaintext;

            //return "decry "+ message;
        }
    }

please see my code and rectified area as a result it should work if i pass only text or if i pass text with numeric data or alphanumeric with special character.

looking for help.

解决方案

I can see a problem when you do things like this:

string ciphertext = new UnicodeEncoding().GetString(ciphertextbyte);
           

The ciphertextbyte is an array of bytes that contains binary values for the encrypted text. Those binary values can have any possible value, and many of these values will not be equivalent to any legal Unicode Encoding. Therefore, the GetString will return an unpredictabe string that you will not be able to then convert back into bytes when you wan to decode your ciphered text. It may work for SOME strings when you are lucky enough that the ciphered values happen to all be legitimate Unicode encodings, and it will fail for other strings. It's not a matter of containing "alphanumeric text" like you mentioned, but a matter of random luck depending on how the plaintext encodes into the cyphertext.

If you need to handle your encoded content as strings instead of byte arrays, then it is better to convert the byte array by means of a mechanism that is valid for all possible byte values. For instance, you can use Convert.ToBase64 instead of UnicodeEncoding.GetString. And, obviously, Convert.FromBase64 when you want to perform decoding.


这篇关于C#我的加密和解密功能一段时间无法使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆