从Python传递到C再返回到Python时如何保留文字

How do I preserve literals when passing from Python to C++ and back to Python

好的,这是交易。我有一个程序可以在Python中进行日志记录。我希望该日志在程序不使用时不会受到编辑的影响,因此我编写了一个python脚本,该脚本创建了C源,旨在将日志重新打印回Python。编译此源代码后,我便可以拥有相当安全的日志,然后只需运行可执行文件即可对其进行检索。它令人费解,但可以工作

问题:创建Python日志时,我用等效的文字(\\')替换了',以便它在存储字符串时不会破坏我的字符串。但是,当我使用C拾取它并将其放回原位时,我丢失了文字,因此我得到了断弦的字符串。有没有一种简单的方法可以用类似于Python中replace函数的相应文字来替换C中的'

一些可能有用的代码段:

如何在Python中将字符串写入日志

1
logFile.write("    '{}'".format(somestring.replace("'","\\\'").encode('ascii', 'ignore'))

Python日志如下所示:

1
CRDict = {"ID number string":[list of a bunch of items],"Another ID number: [Another list of things]}

我如何编写C行来存储Python中日志中的字符串(CR {}为struct)

1
2
CFile.write('    CR{}.somestring ="{}";\
'
.format(num,somestring))

存储字符串的C行最终看起来像

1
CR0.somestring ="This is a string and it doesn't keep track of literals";

将字符串写回到Python(称为CRPYLog的文件)的C行

1
CRPYLog <<"    '" + CR0.somestring +"'," << endl;

这是该行被打印回Python日志时的样子

1
'This is a string and it doesn't keep track of literals'

以上行在语法上无效,因此当我尝试使用Python日志时会中断


为了解决您的主要目标,即使应用程序的"日志在程序不使用时不受编辑的影响",我建议坚持使用常用的标准工具,出于相同目的而制作。

例如,添加数字签名:

A digital signature is a mathematical scheme for demonstrating the authenticity of a digital message or document. A valid digital signature gives a recipient reason to believe that the message was created by a known sender, such that the sender cannot deny having sent the message (authentication and non-repudiation) and that the message was not altered in transit (integrity). Digital signatures are commonly used for software distribution, financial transactions, and in other cases where it is important to detect forgery or tampering.

和/或加密文件:

In cryptography, encryption is the process of encoding messages (or information) in such a way that third parties cannot read it, but only authorized parties can.

这两种方法都是加密方法,如果已使用的(专用)加密密钥有效地保密,那么很难很难检测到文件内容的更改。

在Python中,两种方法都可以使用GnuPG(python-gnupg):

The gnupg module allows Python programs to make use of the functionality provided by the GNU Privacy Guard (abbreviated GPG or GnuPG). Using this module, Python programs can encrypt and decrypt data, digitally sign documents and verify digital signatures, manage (generate, list and delete) encryption keys, using proven Public Key Infrastructure (PKI) encryption technology based on OpenPGP.

我自己没有使用过这个Python库,但是GnuPG本身是某种标准,例如,用于保护电子邮件通信或linux软件包分发。

请注意,即使您已经用这种方式加密了文件,也可能需要数字签名。这是因为使用公钥进行加密,即定义为公钥。在非对称加密中,您需要(秘密)私钥来解码密文并创建数字签名,即对接收者(加密)和发送者(签名)的身份进行身份验证。

如果要进行加密和完整性检查,请查看以下库:

  • https://cryptography.io/en/latest/

也就是说,当操作系统的访问控制机制提供的保护足够时,您可以限制性地配置它们并依靠它。 (然后也不需要密码短语检查。)


是否有一种简单的方法可以用对应的文字替换C中的',类似于Python中的replace函数。

实际上是的,您可以为此使用Boost库。

1
2
3
4
#include <boost/algorithm/string.hpp>

std::string some_string("Your string");
boost::replace_all(some_string,"Your","My");