#! /Usr/bin/python
# Encoding: UTF-8
######################################## #########################
# Script: encode. py
# Description: implements file-related encryption and decryption.
# Version: 0.1 implements encryption and decryption of common files
# Usage: python encode. py [encode | decode] filename [key]
######################################## #########################
Import sys, OS, struct
# Encrypted string
Def encodeString (str ):
Key_index = 0
# Define an encrypted string
Str_encode =''
# Converting a string to a byte array
Bytes = bytearray (str)
# Byte Encryption
For B in bytes:
B _encode = (B + key_bytes [key_index]) % 256
Str_encode + = struct. pack ('B', B _encode)
Key_index = (key_index + 1) % len (key_bytes)
# Return encrypted string
Return str_encode
# Decryption string
Def decodeString (str ):
Key_index = 0
# Define a decryption string
Str_decode =''
# Converting a string to a byte array
Bytes = bytearray (str)
For B in bytes:
B _decode = (B + 256-key_bytes [key_index]) % 256
Str_decode + = struct. pack ('B', B _decode)
Key_index = (key_index + 1) % len (key_bytes)
# Return decryption string
Return str_decode
# Check command line parameters
If len (sys. argv) <3 or len (sys. argv)> 4:
Print 'usage: python', sys. argv [0], '[encode | decode] filename [key]'
Exit (1)
If sys. argv [1] not in ('encode', 'decode '):
Print 'usage: python', sys. argv [0], '[encode | decode] filename [key]'
Exit (1)
# File name
Filename = sys. argv [2]
If not OS. path. isfile (filename ):
Print 'file "'+ filename +'" is not exsisted'
Print 'usage: python', sys. argv [0], '[encode | decode] filename [key]'
Exit (1)
# Define the key. Encryption Method: add each byte of the string and the corresponding byte of the key to obtain the remainder.
Key = 'testkey'
If len (sys. argv) = 4:
Key = sys. argv [3]
Key_bytes = bytearray (key)
# Encryption or decryption
Mode = sys. argv [1]
# Encrypt or decrypt files
File_mode_name = filename + '.' + mode
# Encryption or decryption
If mode = 'encoding ':
File = open (filename, 'R ')
File_encode = open (file_mode_name, 'w ')
Str = file. read ()
Str_encode = encodeString (str)
File_encode.write (str_encode)
File. close ()
File_encode.close ()
Else:
File = open (filename, 'R ')
File_decode = open (file_mode_name, 'w ')
Str = file. read ()
Str_decode = decodeString (str)
File_decode.write (str_decode)
File. close ()
File_decode.close ()
Print 'succeed to ', mode, 'file "' + filename + '", result file is "' + file_mode_name + '"'