BitConverter.ToString(hash).Replace(“-”,string.Empty)是否等效于python?

时间:2018-12-05 10:54:44

标签: c# python encryption

如何在python中编写以下行?

BitConverter.ToString(hash).Replace("-", string.Empty)

这就是我正在尝试的

import random
import uuid
import base64
from Crypto.Cipher import AES
import hashlib
from Crypto import Random
import binascii

key = hashlib.sha256(b'SOmeKEyy').digest()
key1 = base64.b64encode(key)
iv_value = b'RandomValuie'
iv = base64.b64decode(iv_value)

cipher = AES.new(key, AES.MODE_CFB, iv)

message = Mac_AddressBytes + ip_address_Bytes + DeviceIdBytes
msg = iv + cipher.encrypt(message)

s =encrypt(message, key)
print(s)

sa = bytearray(s)
DeviceIdentity1 = binascii.b2a_hex(s)
DeviceIdentityDecoded = "0x" + DeviceIdentity1.decode('utf-8')
print (str(DeviceIdentityDecoded))

Mac_AddressBytes + ip_address_Bytes + DeviceIdBytes是有效的字符串。

我要到达的输出是我想要的十六进制,但是如果我在C#中运行相同的字符串,我得到的字符串有所不同,那么我在python中缺少的部分就是BitConverter.ToString(hash).Replace("-", string.Empty)
我已经尝试遵循DeviceIdentity2 = "0x" + DeviceIdentity1.decode('utf-8').replace("-", ""),但是这给了我与DeviceIdentityDecoded = "0x" + DeviceIdentity1.decode('utf-8')相同的价值 当我Decrpyt字符串时,我得到以下内容

Îí5ó/½û.qõX9D&Ç:eXM»Bñj2µ\ëÁ§ÓËÔ¤ý  ¼t®@Z9)Àåñr¹ Ör¾hÅåéÙ|¶nÙZÆÃï,¡WÀj©r{ÆR¥f,|^W¯C
Ù1¾+MöB;S­ô«¹næk0ú·7e,atMìÆ¿Kfí

上面的c#代码在python中是否等效?

1 个答案:

答案 0 :(得分:0)

对于感兴趣的人,我发现我缺少PKCS7Encoder()

这是有效的更新答案

key = base64.b64decode("SOmeKEyy")
    iv_value = 'RandomValue'
    iv = base64.b64decode(iv_value)
    encoder = PKCS7Encoder()
    padded_text = encoder.encode(secret_text)
    padded_text1 = padded_text.encode()
    print(padded_text1)
    e = AES.new(key, AES.MODE_CBC, iv)
    cipher_text = e.encrypt(padded_text1)
    Finally = binascii.b2a_hex(cipher_text)
    DeviceIdentity = "0x" + Finally.decode('utf-8').replace("-", "")
    print(DeviceIdentity)