python : trans position cipher

换位算法的加解密

实验

# @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();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值