序
换位算法的加解密
实验
# @file main.py
# @brief trans position cipher
# run result
"""
--------------------------------------------------------------------------------
trans position cipher
--------------------------------------------------------------------------------
Python 3.6.2
b_encryp = 1, i_cipher_key = 8, i_len_msg = 20, sz_cipher_msg = "This is plain text:)"
cipher text = "Tpxhltia:si) ni st e"
b_encryp = 0, i_cipher_key = 8, i_len_msg = 20, sz_cipher_msg = "Tpxhltia:si) ni st e"
plain text = "This is plain text:)"
END
"""
from subprocess import call
def main():
cipher_key = 8
sz_cipher_msg = ""
print("--------------------------------------------------------------------------------");
print("trans position cipher")
print("--------------------------------------------------------------------------------");
# print python version
call(["python", "-V"])
# caesar encrypt
sz_cipher_msg = trans_position_cipher(True, "This is plain text:)", cipher_key)
print("cipher text = \"%s\"" % sz_cipher_msg)
# caesar decrypt
sz_cipher_msg = trans_position_cipher(False, sz_cipher_msg, cipher_key)
print("plain text = \"%s\"" % sz_cipher_msg)
print("END")
# @fn trans_position_cipher
# @brief trans position cipher encrypt or decrypt
# @param b_encryp, True = encrypt; False = decrypt
# @param str_msg,
# when (b_encryp == True), msg is plain text
# when (b_encryp == False), msg is cipher text
# @param i_cipher_key, the cipher key by trans position cipher
# @return string, the result string
# when (b_encryp == True), return cipher text
# when (b_encryp == False), return plain text
def trans_position_cipher(b_encryp, str_msg, i_cipher_key):
sz_cipher_ary = ['.'] * len(str_msg)
sz_cipher_msg = ""
i_len_msg = len(str_msg)
i_col = 0
i_col_cur = 0
i_cipher_pos_cur = 0
print("b_encryp = %d, i_cipher_key = %d, i_len_msg = %d, sz_cipher_msg = \"%s\"" % (b_encryp, i_cipher_key, i_len_msg, str_msg))
for i_col in range(i_cipher_key):
i_col_cur = i_col
while (i_col_cur < i_len_msg):
if (True == b_encryp):
sz_cipher_ary[i_cipher_pos_cur] = str_msg[i_col_cur]
else:
sz_cipher_ary[i_col_cur] = str_msg[i_cipher_pos_cur]
i_cipher_pos_cur += 1
i_col_cur += i_cipher_key
sz_cipher_msg = ''.join(sz_cipher_ary)
return sz_cipher_msg
if __name__ == "__main__":
main();