凯撒密码最早由古罗马军事统帅盖乌斯·尤利乌斯·凯撒在军队中用来传递加密信息,故称凯撒密码。这是一种位移加密方式,只对26个字母进行位移替换加密,规则简单,容易破解。若将明文字母表向后移动3位:

明文字母表

X

Y

Z

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

Q

R

S

T

U

V

W

密文字母表

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

Q

R

S

T

U

V

W

X

Y

Z

则A变成了D,B变成了E……,Z变成了C。

字母表最多可以移动25位。凯撒密码的明文字母表向后或向前移动都是可以的,通常表述为向后移动,如果要向前移动1位,则等同于向后移动25位,位移选择为25即可。

假设:现在我们要传递消息,明文为'leave at zero in the night',请加密成密文,用python语言实现。

代码如下:

def caesar_cipher(text, shift):
    # 定义明文字母表和密文字母表
    plain_alphabet = 'abcdefghijklmnopqrstuvwxyz'
    cipher_alphabet = plain_alphabet[shift:] + plain_alphabet[:shift]
    # 将明文中的每个字母替换成密文字母表中对应的字母
    cipher_text = ''
    for letter in text:
        if letter.isalpha():
            # 如果是字母,则进行替换
            index = plain_alphabet.index(letter.lower())
            if letter.isupper():
                cipher_text += cipher_alphabet[index].upper()
            else:
                cipher_text += cipher_alphabet[index]
        else:
            # 如果不是字母,则直接加入密文中
            cipher_text += letter
    return cipher_text

# 测试
text = 'leave at zero in the night'
 shift = 3
cipher_text = caesar_cipher(text, shift)
print(cipher_text)
# 输出:ohdyh dw crw rqlq lq wkh qljkw

注:此代码仅为示例,实际使用中需要注意安全性和加密强度等问题。

凯撒密码 Python 实现:古典加密算法详解

原文地址: http://www.cveoy.top/t/topic/fWHJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录