使用python实现简单的序列密码

使用python 实现简单的序列密码


#!/usrs/bin/env python
print '\nStream Ciphers:\n'
before = 'One apple a day, keeps the doctor away!'
after = ""
i = 1
for each in before:
    after += chr(ord(each)^(63+i))
    if i == 4:
        i = 1
print 'before: ',before,'\n'
print 'after: ',after,'\n'
revert = ""
i = 1
for each in after:
    revert += chr(ord(each)^(63+i))
    if i == 4:
        i = 1
print 'revert: ',revert,'\n'

    


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
序列密码是一种简单的加密方式,它可以通过将明文中的每个字符按照一定顺序进行重新排列来实现加密。下面是一个使用Python实现序列密码的示例代码: ```python def encrypt(plaintext, key): """使用序列密码加密明文""" ciphertext = "" for i in key: if i < len(plaintext): ciphertext += plaintext[i] return ciphertext def decrypt(ciphertext, key): """使用序列密码解密密文""" plaintext = [""] * len(ciphertext) for i, val in enumerate(key): if val < len(ciphertext): plaintext[val] = ciphertext[i] return "".join(plaintext) ``` 在上面的代码中,我们定义了两个函数:`encrypt`和`decrypt`。`encrypt`函数接受两个参数:明文和密钥。它首先创建一个空字符串`ciphertext`,然后遍历密钥中的每个数字。对于每个数字,如果它小于明文的长度,则将明文中相应位置的字符添加到`ciphertext`中。最后,函数返回`ciphertext`。 `decrypt`函数也接受两个参数:密文和密钥。它首先创建一个长度与密文相同的空列表`plaintext`。然后遍历密钥中的每个数字,将密文中相应位置的字符添加到`plaintext`中。最后,函数返回由`plaintext`列表中的所有字符组成的字符串。 下面是一个例子,展示了如何使用上面的函数进行加密和解密: ```python plaintext = "hello world" key = [2, 1, 4, 0, 6, 5, 3] ciphertext = encrypt(plaintext, key) print(ciphertext) # Output: "lhod ll" decrypted_text = decrypt(ciphertext, key) print(decrypted_text) # Output: "hello world" ``` 在这个例子中,我们使用`[2, 1, 4, 0, 6, 5, 3]`作为密钥对明文`"hello world"`进行加密,得到了密文`"lhod ll"`。然后,我们使用相同的密钥对密文进行解密,得到了原始明文`"hello world"`。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值