gpt4 book ai didi

python - 密码学:将 C 函数转换为 python

转载 作者:行者123 更新时间:2023-11-30 18:50:40 26 4
gpt4 key购买 nike

我正在尝试解决密码学问题( https://callicode.fr/pydefis/Reverse/txt ),该算法使用以下 C 函数(F1)。我不懂C,我尝试将其转换为python(F2),但没有成功。预先感谢您让我知道我做错了什么。

F1:

void Encrypt(unsigned char key[20], unsigned char *pPlainBuffer, unsigned char *pCipherBuffer, unsigned int nLength) 
{
int nKeyPos = 0;
unsigned int n;
unsigned char KeyA = 0;

if ((pPlainBuffer != NULL) && (pCipherBuffer != NULL)) {
for (n = 0; n < 20; n++)
KeyA ^= key[n];
nKeyPos = KeyA % 20;
for (n = 0; n < nLength; n++) {
pCipherBuffer[n] = pPlainBuffer[n]^(key[nKeyPos]*KeyA);
KeyA += pCipherBuffer[n];
nKeyPos = pCipherBuffer[n] % 20;
}
}
}

F2:

def Encrypt(plainText, key):  # plainText is a list of hexadecimals representing ascii 
# characters, key is a list of int size 20 each int
# beetween 0 and 255
keyA = 0

for n in range(20):
keyA ^= key[n]

nKeyPos = KeyA % 20

for n in range(len(plainText)):
codedText[n] = plainText[n]^(key[nKeyPos]*KeyA)
keyA += codedText[n]
nKeyPos = codedText[n] % 20

最佳答案

你有很多问题......最明显的是Python整数默认情况下不受字节宽度的限制,所以你必须显式设置宽度

此外,您必须在 python 中将字母转换为数字,因为它们本质上是不同的东西(在 C/c++ 中字母实际上只是数字)

def Encrypt(plainText, key):  # plainText is a list of hexadecimals representing ascii 
# characters, key is a list of int size 20 each int # beetween 0 and 255
keyA = 0
for letter in key:
keyA ^= ord(letter) # conver letter to number
keyA = keyA & 0xFF # fix width to one byte
key = itertools.cycle(key) # repeate forever
codedText = ""
for letter,keyCode in zip(plainText,key):
xorVal = (ord(keyCode) * keyA) & 0xFF # make one byte wide
newLetter = chr((ord(letter) ^ xorVal )&0xFF) # make one byte wide

codedText += newLetter
keyA += ord(newLetter)
keyA = keyA&0xFF # keep it one byte wide

关于python - 密码学:将 C 函数转换为 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39515934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com