zoukankan      html  css  js  c++  java
  • python 和 C# DES加密

    C# code:

    using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace LamicSdk.Func { public class HelpEncrypt { private static string GetDefaultKeyAndIv() { return ""; } /// <summary>字符串DES加密函数</summary> /// <param name="str">被加密字符串</param> /// <param name="keyAndIv">加密向量和密钥</param> /// <returns>加密后字符串</returns> 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; } } /// <summary><![CDATA[字符串DES解密函数]]></summary> /// <param name="str"><![CDATA[被解密字符串 ]]></param> /// <param name="keyAndIv">解密向量和密钥</param> /// <returns><![CDATA[解密后字符串]]></returns> 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 code:
    import pyDes
    import binascii

    #des 加密
    k = pyDes.des("", pyDes.CBC,"", pad=None, padmode=pyDes.PAD_PKCS5)
    d = k.encrypt("22222222222".encode('utf-8'))
    result= binascii.b2a_hex(d)
    print(result)

     

      

    请尽量按照自己期望的生活 email:18980489167@189.cn
  • 相关阅读:
    Bash 小问题【待更新】
    进程动态优先级调度
    密码
    [Noi2016]优秀的拆分
    [Tjoi2016&Heoi2016]字符串
    [BZOJ 1901]Dynamic Rankings
    [HDU 2665]Kth number
    [BZOJ 4310]跳蚤
    [Sdoi2008]Sandy的卡片
    [Usaco2007 Dec]队列变换
  • 原文地址:https://www.cnblogs.com/gytangyao/p/9174336.html
Copyright © 2011-2022 走看看