Cryptography With Python 简明教程

Encryption of files

在 Python 中,可以在传输到通信信道之前对文件进行加密和解密。为此,必须使用插件 PyCrypto 。可以使用以下给出的命令安装此插件。

pip install pycrypto
pycrypto

Code

使用密码保护对文件进行加密的程序代码如下所示:

# =================Other Configuration================
# Usages :
usage = "usage: %prog [options] "
# Version
Version="%prog 0.0.1"
# ====================================================
# Import Modules
import optparse, sys,os
from toolkit import processor as ps
def main():
   parser = optparse.OptionParser(usage = usage,version = Version)
   parser.add_option(
      '-i','--input',type = 'string',dest = 'inputfile',
      help = "File Input Path For Encryption", default = None)

   parser.add_option(
      '-o','--output',type = "string",dest = 'outputfile',
      help = "File Output Path For Saving Encrypter Cipher",default = ".")

   parser.add_option(
      '-p','--password',type = "string",dest = 'password',
      help = "Provide Password For Encrypting File",default = None)

   parser.add_option(
      '-p','--password',type = "string",dest = 'password',
      help = "Provide Password For Encrypting File",default = None)

   (options, args)= parser.parse_args()

   # Input Conditions Checkings
   if not options.inputfile or not os.path.isfile(options.inputfile):
      print " [Error] Please Specify Input File Path"
      exit(0)
   if not options.outputfile or not os.path.isdir(options.outputfile):
      print " [Error] Please Specify Output Path"
      exit(0)
   if not options.password:
      print " [Error] No Password Input"
      exit(0)
   inputfile = options.inputfile

   outputfile = os.path.join(
      options.outputfile,os.path.basename(options.inputfile).split('.')[0]+'.ssb')
   password = options.password
   base = os.path.basename(inputfile).split('.')[1]
   work = "E"

   ps.FileCipher(inputfile,outputfile,password,work)
   return

   if __name__ == '__main__':
   main()

可以使用以下命令执行加密过程和密码:

python pyfilecipher-encrypt.py -i file_path_for_encryption -o output_path -p password

Output

执行上述代码时,可以看到以下输出:

encryption process

Explanation

密码使用 MD5 哈希算法生成,这些值存储在 Windows 系统的简单安全备份文件中,其中包括以下显示的值:

explanation