Python中如何将这段C#代码改写成Python?

请教这段 C#的代码怎么改写成 Python

public class Encrypt
{
	public static string DoEncrypt(string ls_input)
	{
		MD5 mD = new MD5CryptoServiceProvider();
		ls_input = string.Format("aaa{0}bbb", ls_input);
		byte[] bytes = Encoding.Unicode.GetBytes(ls_input);
		byte[] array = mD.ComputeHash(bytes);
		string text = null;
		for (int i = 0; i < array.Length; i++)
		{
			text += array[i].ToString("x");
		}
		return string.Format("bkSystem_{0}", text);
	}
}

我自己写了一段,不过加密出来的值和 C#生成的值不一样,还请帮忙改下

import hashlib

data = ‘[{“lxdh”:“134859393”,“content”:“testbk”}]’

def encrypt(input): is_input = ‘aaa%sbbb’ %input print (is_input) is_input = hashlib.md5(is_input.encode(‘utf-8’)).hexdigest() is_input = ‘bkSystem_’ + is_input

print(is_input)

encrypt(data)


Python中如何将这段C#代码改写成Python?

9 回复

要帮你把C#代码转成Python,得先看到具体的C#代码才行。不过我可以给你一些常见的转换思路:

  1. 语法差异

    • C#的Console.WriteLine() → Python的print()
    • C#的List<T> → Python的list
    • C#的Dictionary<K,V> → Python的dict
  2. 类型声明

    # C#: int x = 5;
    x = 5  # Python是动态类型
    
  3. 循环和条件

    # C#的for循环
    for i in range(10):  # 相当于for(int i=0; i<10; i++)
        print(i)
    
  4. 类定义

    # Python类
    class MyClass:
        def __init__(self, value):
            self.value = value
    
  5. 异步代码

    # Python async/await
    async def my_async_func():
        await some_async_call()
    

把具体的C#代码贴出来,我直接给你转成Python。

不帮

byte[] bytes = Encoding.Unicode.GetBytes(ls_input);

is_input.encode(‘utf-8’)

是什么让你觉得 Unicode = UTF-8 ?在 Windows 语境下,Unicode 是 UTF16LE。

嗯,看来是 Windows 上 Unicode 和 Python 上转化的区别,不过好像 UTF16LE 也是不对的,不知道该用什么字符集合适

非常感谢,确实像你说的一样,我把 utf-8 改成 utf-16LE 就已经编码一致了,再一次感谢.

UTF-8 ~~哦。。楼上有人答了啊。。

嗯,是的



不好意思,我再请教下,我加密出来的东西好像基本一致,就是有时候会和 c#生成的多出来一至两个 0 是什么情况?

回到顶部