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)
|
请发表评论