当前位置:首页 > 计算机相关 > .net专区 > 正文内容

python和C# 的DES3加密通信

piikee5年前 (2019-11-20).net专区1146

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)

扫描二维码推送至手机访问。

版权声明:本文由萍客小居[www.piikee.net]发布,如需转载请注明出处。

本文链接:https://www.piikee.net/1364.html

分享给朋友:

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。