python和C# 的DES3加密通信

python和C#的兼容DES3通讯,triple des 通用C#和python。C#和python的兼容加密通讯方式

C# DES3加密模块:

 public static string Encrypt(string text, string iv, string key)//要加密的内容,IV,KEY
        {
            try
            {

                var provider = new DESCryptoServiceProvider
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    IV = Encoding.UTF8.GetBytes(iv)
                };
                var bytes = Encoding.UTF8.GetBytes(text);
                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, provider.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytes, 0, bytes.Length);
                        cryptoStream.FlushFinalBlock();
                        var builder = new StringBuilder();
                        foreach (var num in memoryStream.ToArray())
                        {
                            builder.AppendFormat("{0:x2}", num);
                        }
                        return builder.ToString();
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

C# DES3解密模块:

    public static string Decrypt(string text, string iv, string key)//要加密的内容,IV,KEY
        {


            var provider = new DESCryptoServiceProvider
            {
                Key = Encoding.UTF8.GetBytes(key),
                IV = Encoding.UTF8.GetBytes(iv)
            };
            var buffer = new byte[text.Length / 2];
            for (var i = 0; i < text.Length / 2; i++)
            {
                var num2 = Convert.ToInt32(text.Substring(i * 2, 2), 0x10);
                buffer[i] = (byte)num2;
            }
            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, provider.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(buffer, 0, buffer.Length);
                    cryptoStream.FlushFinalBlock();
                    return Encoding.UTF8.GetString(memoryStream.ToArray());
                }
            }


        }

python DES3加密模块:

 
import pyDes

k = pyDes.des(key, pyDes.CBC,iv, pad=None, padmode=pyDes.PAD_PKCS5)
oktext=k.encrypt(text)

python DES3解密模块:

 
import pyDes
k = pyDes.des(key, pyDes.CBC,iv, pad=None, padmode=pyDes.PAD_PKCS5)
oktext=k.decrypt(text) 
打赏

发表评论

电子邮件地址不会被公开。 必填项已用*标注