密码学的加密实现

仿射密码

m = "n"  # 明文
a = list(m)  # 将明文转换为列表形式
k1 = 17  # 密钥k1与26互素的数
k2 = 9  # 偏移量
# 将明文字符串转化为Acsll码然后将0-a,25-z对应


def tihuan(a, m):
    temp = []
    for i in range(len(m)):
        if a[i].islower():
            temp.append(ord(a[i])-97)
        else:
            temp.append(ord(a[i])-65)
    return temp

# 加密函数


def encryption(temp, m, k1, k2):
    c = []
    for i in range(len(m)):
        c.append(chr((temp[i]*k1+k2) % 26+97))
    return c


temp = tihuan(a, m)
c = encryption(temp, m, k1, k2)
c1 = ""
for i in range(len(m)):
    c1 = c1+c[i]  # 将列表转化为字符串
print(c1)

维吉尼亚密码

import math
m = "appliedcryptosystem"  # 明文
a = list(m)
k = "cipher"  # 密钥
b = list(k)
# 确定分组数
if len(m) > len(k):
    x = len(m)//len(k)
else:
    x = 0
# Ascll


def tihuan(a, m):
    temp = []
    for i in range(len(m)):
        if a[i].islower():
            temp.append(ord(a[i])-97)
        else:
            temp.append(ord(a[i])-65)
    return temp

# 加密


def encryption(tempm, tempk, x):
    c = []
    z = 0
    n = len(k)
    if x == 0:  # 如果组数为0
        for i in range(len(z, n)):
            c.append(chr((tempm[i]+tempk[i % n]) % 26+97))
    else:
        for i in range(x):
            for j in range(z, n):
                c.append(chr((tempm[j]+tempk[j % len(k)]) % 26+97))
            z = n
            n += len(k)  # 我是sb能用常量不要用变量
        for d in range(x*len(k), len(m)):
            c.append(chr((tempm[d]+tempk[d % len(k)]) % 26+97))
    return c


tempm = tihuan(a, m)
tempk = tihuan(b, k)

c = encryption(tempm, tempk, x)
c1 = ""
for i in range(len(m)):
    c1 = c1+c[i]
print(c1)

hill密码

import numpy as np
m = 'se'  # 明文
a = np.matrix([[11, 2], [5, 23]])  # 密钥LCTFXZUHR
num_m = []
temp = []
count = 1
for i in m:  # 将明文分为三个一组
    temp.append(ord(i)-ord('A'))
    if count % 3 == 0:
        num_m.append(temp)
        temp = []
    count += 1
mat_m = [np.matrix(i).T for i in num_m]  # 将明文分组转换为向量形式
mat_c = [a * i % 26 for i in mat_m]  # 得到密文分组的向量形式
num_c = []
temp = []
for i in mat_c:  # 将密文向量转换为列表形式,且合并到一个列表
    temp = i.tolist()
    for j in range(3):
        num_c.append(temp[j][0])
c = [chr(i+ord('A')) for i in num_c]
print(''.join(c))  # 连接成字符串,输出密文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值