我需要从python中的c++中实现rand和rands来重新加密一堆文件。但似乎搞错了。
我有一个exe,不加密一个文件为文本,我也有源代码,在编辑文件后,我需要使用相同的方法加密它。
由于我不知道如何编写c++代码,所以我选择用python编写。首先尝试解密它,以知道方法是相同的。
下面的代码是未加密文件的c++代码,其中"buff“是加密块的开头,"len”长度是该块的“len”长度。
static const char KEY[] = "KF4QHcm2";
static const unsigned long KEY_LEN = sizeof(KEY) - 1;
void unobfuscate(unsigned char* buff, unsigned long len) {
srand((char)buff[len - 1]);
for (unsigned long i = 0; i < len - 2; i += 2) {
buff[i] ^= KEY[rand() % KEY_LEN];
}
}据我所知,它以加密块的最后一个字符作为种子,从一开始,它用键数组的一个元素对值进行2字节的by,这个索引由一个随机数除以密钥长度的剩余部分决定。
在网上搜索时,我发现c++使用了一个简单的线性同余发生器,它不应该用于加密,但似乎无法使其工作。
我找到了代码的一个例子,并试图实现另一个,但两者似乎都不起作用。
#My try at implementing it
def rand():
global seed
seed = (((seed * 1103515245) + 12345) & 0x7FFFFFFF)
return seed我还看到rand函数介于0和RAND_MAX之间,但是找不到RAND_MAX的值,如果我找到它,也许可以使用random.randrange()。
它也可以是我设置种子的方式,因为在c++中,char似乎工作,但是在python中,我将它设置为字符的值。
下面是我观察到的,当使用各种方法对文件进行非加密时。这仅仅是前13个字节,所以如果有人需要检查它是否有效,就可以这样做。
The block ends with the sequence: 4C 0A 54 C4 this means C4 is the seed
Example encrypted:
77 43 35 69 26 6B 0C 6E 3A 74 4B 33 71 wC5i&k.n:tK3q
Example un-encrypted using c++:
24 43 6C 69 63 6B 49 6E 69 74 0A 33 34 $ClickInit.34
Example un-encrypted using python example:
1A 43 7E 69 77 6B 38 6E 0E 74 1A 33 3A .C~iwk8n.t.3:
Example un-encrypted using python implementation:
3C 43 73 69 6E 6B 4A 6E 0E 74 1A 33 37 <CsinkJn.t.37我的python脚本也可能有问题,所以这里是文件,以防它有任何错误:
import os
def srand(s):
global seed
seed = s
def rand():
global seed
#Example code
#seed = (seed * 214013 + 2531011) % 2**64
#return (seed >> 16)&0x7fff
#Implementation code
seed = (((seed * 1103515245) + 12345) & 0x7FFFFFFF)
return seed
KEY = ['K','F','4','Q','H','c','m','2']
KEY_LEN = len(KEY) - 1
for filename in os.listdir("."):
if filename.endswith(".dat"):
print(" Decoding " + filename)
#open file
file = open(filename, "rb")
#set file attributes
file_length = os.path.getsize(filename)
file_buffer = [0] * file_length
#copy contents of file to array
for i in range(file_length):
file_buffer[i] = int.from_bytes(file.read(1), 'big')
#close file
file.close()
print(" Random Seed: " + chr(file_buffer[-1]))
#set random generator seed
srand(file_buffer[-1])
#decrypt the file
for i in range(3600, file_length, 2):
file_buffer[i] ^= ord(KEY[rand() % KEY_LEN])
#print to check if output is un-encrypted
for i in range(3600, 3613, 1):
print(file_buffer[i])
print(chr(file_buffer[i]))
continue
else:
#Do not try to un-encrypt the python script
print("/!\ Can't decode " + filename)
continue如果有人能帮我解决这个问题,我会很感激的,如果可能的话,我很乐意在python中工作,但是,从我所能收集到的信息来看,我似乎必须学习c++才能让它工作起来。
发布于 2019-09-04 13:30:35
rand不是加密函数。
rand的算法在系统编译器或其他任何东西之间都不稳定。
如果您别无选择,最好的选择是使用python/C++互操作性技术,并实际运行rand()和srand()。这会很糟糕,但它会像原来的代码那样糟糕。
https://stackoverflow.com/questions/57789083
复制相似问题