python与C#相互加解密
C#加解密
using System; using System.Text; using System.IO; using System.Security.Cryptography; namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { var testData = "{'username':'admin','password':'123.com'}"; Console.WriteLine("测试数据:"+testData); Console.WriteLine("C#加密:" + Encode(testData)); Console.Write("C#解密:"+ Decode(Encode(testData))); Console.ReadLine(); } static string GetDefaultKeyAndIv() { return "12345678"; } //加密 public static string Encode(string str, string keyAndIv = null) { try { keyAndIv = string.IsNullOrEmpty(keyAndIv) ? GetDefaultKeyAndIv() : keyAndIv; var provider = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyAndIv), IV = Encoding.ASCII.GetBytes(keyAndIv) }; var bytes = Encoding.UTF8.GetBytes(str); 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; } } //解密 public static string Decode(string str, string keyAndIv = null) { try { keyAndIv = string.IsNullOrEmpty(keyAndIv) ? GetDefaultKeyAndIv() : keyAndIv; var provider = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyAndIv), IV = Encoding.ASCII.GetBytes(keyAndIv) }; var buffer = new byte[str.Length / 2]; for (var i = 0; i < str.Length / 2; i++) { var num2 = Convert.ToInt32(str.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()); } } } catch (Exception) { return null; } } } }
python加解密
import base64 class DESSecret: def __init__(self,key): self.KEY = key def des_en(self,text): iv=secret_key=self.KEY k = pyDes.des(secret_key,pyDes.CBC,iv,padmode=pyDes.PAD_PKCS5) data = k.encrypt(text,padmode=pyDes.PAD_PKCS5) # 字符串转16进制 return binascii.b2a_hex(data).decode() def des_de(self,text): iv = secret_key = self.KEY k = pyDes.des(secret_key, pyDes.CBC, iv, padmode=pyDes.PAD_PKCS5) # 十六进制转字符串 # binascii.a2b_hex(text) data = k.decrypt(binascii.a2b_hex(text),padmode=pyDes.PAD_PKCS5) return data.decode()