可以使用OpenSSL进行加密解密和签名验证。OpenSSL是一个开源的加密库,提供了许多加密算法和协议的实现。以下是使用OpenSSL库进行加密解密和签名验证的步骤:
1、生成私钥:运行以下命令生成私钥文件(例如,private.key):
openssl genpkey -algorithm RSA -out private.key
2、从私钥中提取公钥:运行以下命令生成公钥文件(例如,public.key):
openssl rsa -pubout -in private.key -out public.key
现在您已经生成了一个私钥文件(private.key)和一个公钥文件(public.key)。
接下来,您可以使用私钥对.tar.gz文件进行加密,然后使用公钥对加密后的数据进行解密。同时,您还可以对加密后的数据进行签名,然后使用公钥对签名进行验证。
加密文件:
openssl rsautl -encrypt -inkey private.key -in input.tar.gz -out encrypted.tar.gz
解密文件:
openssl rsautl -decrypt -pubin -inkey public.key -in encrypted.tar.gz -out decrypted.tar.gz
签名文件:(一般来说是对加密前的文件进行签名)
openssl dgst -sha256 -sign private.key -out signature.bin encrypted.tar.gz
验证签名:
openssl dgst -sha256 -verify public.key -signature signature.bin encrypted.tar.gz
请注意,上述命令中的"input.tar.gz"是待加密的.tar.gz文件,"encrypted.tar.gz"是加密后的文件,"decrypted.tar.gz"是解密后的文件,"signature.bin"是签名文件。
注意:非对称加密对加密文件的大小有要求,文件太大会导致无法加密,对于大文件的加密一般是先使用对称加密对大文件进行加密,加密完成后使用非对称加密对对称加密的密钥文件进行非对称加密,接收方通过公钥解密对称加密密钥,然后用密钥解密加密大文件,然后对解密出来的大文件进行验签。例子如下:
1、加密
def main():
if os.path.exists('cache'):
shutil.rmtree('cache')
if os.path.exists('new_build'):
shutil.rmtree('new_build')
os.mkdir('cache')
os.mkdir('new_build')
# 对原文件生成签名
cmd = f'openssl dgst -sha256 -sign private.key -out {os.path.join("cache", app_name)}.sign {pyapp_name}'
os.system(cmd)
# 生成对称加密密钥
cmd = f'openssl rand -out {os.path.join("cache", "symmetry")}.bin 32'
os.system(cmd)
# 对大文件进行对称加密
cmd = f'openssl enc -aes-256-cbc -salt -in {pyapp_name} -out {os.path.join("cache", app_name)}.enc -pass file:{os.path.join("cache", "symmetry")}.bin'
os.system(cmd)
# 对对称加密密钥进行非对称加密
cmd = f'openssl rsautl -encrypt -inkey private.key -in {os.path.join("cache", "symmetry.bin")} -out {os.path.join("cache", app_name)}.bin'
os.system(cmd)
# 对加密文件,加密对称密钥,签名文件打包
cmd = f'tar -czf {os.path.join("new_build", pyapp_name)} -C cache {app_name}.enc {app_name}.sign {app_name}.bin'
os.system(cmd)
shutil.rmtree('cache')
2、解密
_path = os.path.join(DOWNLOAD_PATH, app_name)
# 对非对称加密的对称密钥进行解密
cmd = f'openssl rsautl -decrypt -pubin -inkey public.key -in {os.path.join(_path, app_name)}.bin -out {os.path.join(_path, "symmetry.bin")}'
os.system(cmd)
# 通过解密出来的密钥对加密大文件进行对称解密
cmd = f'openssl enc -d -aes-256-cbc -in {os.path.join(_path, app_name)}.enc -out {os.path.join(_path, filename)} -pass file:{os.path.join(_path, "symmetry.bin")}'
os.system(cmd)
# 对解密出来的大文件进行验签
cmd = f'openssl dgst -sha256 -verify public.key -signature {os.path.join(_path, app_name)}.sign {os.path.join(_path, filename)}'
res = os.system(cmd)
if res == 0:
print('签名验证通过')
else:
print('签名验证失败')