数据可视化(二):凯撒密码 和 Vigenere 密码,让你轻松学会数据信息加密解密技术

< Python 实现-加密解密技术>

Tips:"分享是快乐的源泉💧,在我的博客里,不仅有知识的海洋🌊,还有满满的正能量加持💪,快来和我一起分享这份快乐吧😊!

喜欢我的博客的话,记得点个红心❤️和小关小注哦!您的支持是我创作的动力!"

一、凯撒密码

        凯撒密码(Caesar cipher)是一种最简单且最广为人知的加密技术。它是一种替换式的密码,通过把字母移动固定数目的位置进行加密。凯撒密码通常又被称作恺撒移位密码或者凯撒加密法。

        凯撒密码的原理是:通过把字母表中的每一个字母移动固定数目的位置进行加密。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推。这个加密方法是以罗马共和时期的凯撒大帝命名的,当年凯撒曾用此方法与其将军们进行联系。

        凯撒密码的安全性基于加密的密钥,即字母移动的位数。只要知道了这个密钥,解密就变得非常简单。因此,凯撒密码并不适合用于加密敏感或重要的信息,但在某些特定场合或教学目的中,它仍然是一个有用的工具。

def caesar_cipher(text, shift):
    result = ""
	
	# 凯撒密码加密逻辑

    for char in text:
        if char.isalpha():
            ascii_offset = ord('A') if char.isupper() else ord('a')
            shifted = (ord(char) - ascii_offset + shift) % 26 + ascii_offset
            result += chr(shifted)
        else:
            result += char

    return result

# 加密
def encrypt(text, shift):
    return caesar_cipher(text, shift)

# 解密
def decrypt(text, shift):
    return caesar_cipher(text, -shift)


def main():
    while True:
        print("1. 加密")
        print("2. 解密")
        print("3. 退出")

        choice = input("请选择操作(1/2/3):")
        if choice == '1':
            text = input("请输入要加密的文本:")
            shift = int(input("请输入偏移量:"))
            encrypted_text = encrypt(text, shift)
            print("加密后的文本:", encrypted_text)
        elif choice == '2':
            text = input("请输入要解密的文本:")
            shift = int(input("请输入解密时使用的偏移量(与加密时相同):"))
            decrypted_text = decrypt(text, shift)
            print("解密后的文本:", decrypted_text)
        elif choice == '3':
            print("程序已退出。")
            break
        else:
            print("无效的选择,请重新选择。")


if __name__ == "__main__":
    main()

运行结果:

D:\anaconda\envs\AI_env\python.exe D:/BaiduSyncdisk/BigData/数据结构和算法python/测试代码/排序/Untitled27.py
1. 加密
2. 解密
3. 退出
请选择操作(1/2/3):1
请输入要加密的文本:HELLO
请输入偏移量:10
加密后的文本: ROVVY
1. 加密
2. 解密
3. 退出
请选择操作(1/2/3):2
请输入要解密的文本:ROVVY
请输入解密时使用的偏移量(与加密时相同):10
解密后的文本: HELLO
1. 加密
2. 解密
3. 退出
请选择操作(1/2/3):3
程序已退出。

Process finished with exit code 0

二、Vigenere 密码

        Vigenère密码是一种使用一系列凯撒密码组成密码字母表的加密算法,它属于多表密码的一种简单形式。这种密码以其简单易用而著称,同时初学者通常难以破解,因此也被称为“不可破译的密码”。

        Vigenère密码的原理是通过使加密相同明文的秘钥不同,来掩盖字符的频率。在加密过程中,相同的明文字符经过不同的秘钥字符加密后,会变成不同的密文,从而有效地掩盖了明文字符的字符频率。

        该密码方法最早由吉奥万·巴蒂斯塔·贝拉索在1553年描述,但是后来误传为是由法国外交官布莱斯·德·维吉尼亚所创造,因此现在被称为“Vigenère密码”。

        Vigenère密码的安全性主要取决于秘钥的长度。秘钥越长,每个字符分别进行加密,破解的难度就越大。如果没有得到秘钥,很难对密文进行解密。

        请注意,尽管Vigenère密码在历史上曾被认为难以破解,但现代密码学已经发展出了更强大和安全的加密算法。因此,对于需要高度安全性的应用,建议使用现代加密算法,而不是依赖Vigenère密码。

def vigenere_encrypt(plaintext, key):
    """
    Vigenère加密函数
    :param plaintext: 明文
    :param key: 密钥
    :return: 密文
    """
    ciphertext = ""
    key_index = 0
    for char in plaintext:
        if char.isalpha():  # 只处理字母字符
            if char.isupper():  # 大写字母
                offset = ord(key[key_index % len(key)]) - ord('A')
                ciphertext += chr((ord(char) - ord('A') + offset) % 26 + ord('A'))
            else:  # 小写字母
                offset = ord(key[key_index % len(key)]) - ord('a')
                ciphertext += chr((ord(char) - ord('a') + offset) % 26 + ord('a'))
            key_index += 1
        else:  # 非字母字符保持不变
            ciphertext += char
    return ciphertext


def vigenere_decrypt(ciphertext, key):
    """
    Vigenère解密函数
    :param ciphertext: 密文
    :param key: 密钥
    :return: 明文
    """
    plaintext = ""
    key_index = 0
    for char in ciphertext:
        if char.isalpha():  # 只处理字母字符
            if char.isupper():  # 大写字母
                offset = ord(key[key_index % len(key)]) - ord('A')
                plaintext += chr((ord(char) - ord('A') - offset) % 26 + ord('A'))
            else:  # 小写字母
                offset = ord(key[key_index % len(key)]) - ord('a')
                plaintext += chr((ord(char) - ord('a') - offset) % 26 + ord('a'))
            key_index += 1
        else:  # 非字母字符保持不变
            plaintext += char
    return plaintext


if __name__ == '__main__':
    plaintext = input("请输入明文(可包含英文字母、空格和标点符号): ")
    key = input("请输入密钥(仅包含英文字母): ")
    ciphertext = vigenere_encrypt(plaintext, key)
    print("加密后的密文为:", ciphertext)
    ciphertext = input("请输入密文:")
    plaintext_recovered = vigenere_decrypt(ciphertext, key)
    print("解密后的明文为:", plaintext_recovered)

运行结果:

================================运行结果===========================================
D:\anaconda\envs\AI_env\python.exe D:/BaiduSyncdisk/BigData/数据结构和算法python/测试代码/排序/Untitled27.py
请输入明文(可包含英文字母、空格和标点符号): HELLO
请输入密钥(仅包含英文字母): KEY
加密后的密文为: RIJVS
请输入密文:RIJVS
解密后的明文为: HELLO

Process finished with exit code 0

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
凯撒密码加解密程序(C语言) 2009年09月30日 星期三 13:21 1、程序结构化,用函数分别实现 2、对文件的加密,解密输出到文件 #include #include void menu()/*菜单,1.加密 2.解密 3.退出*/ { clrscr(); printf("\n==============================================================================="); printf("\n1.Encrypt the file"); printf("\n2.Decrypt the file"); printf("\n3.Quit\n"); printf("===============================================================================\n"); printf("Please select a item:"); return; } char encrypt(char ch,int n)/*加密函数,把字符向右循环移位n*/ { while(ch>='A'&&ch='a'&&ch<='z') { return ('a'+(ch-'a'+n)%26); } return ch; } main() { int i,n; char ch0,ch1; FILE *in,*out; char infile[10],outfile[10]; textbackground(RED); textcolor(LIGHTGREEN); clrscr(); menu(); ch0=getch(); while(ch0!='3') { if(ch0=='1') { clrscr(); printf("\nPlease input the infile:"); scanf("%s",infile);/*输入需要加密的文件名*/ if((in=fopen(infile,"r"))==NULL) { printf("Can not open the infile!\n"); printf("Press any key to exit!\n"); getch(); exit(0); } printf("Please input the key:"); scanf("%d",&n);/*输入加密密码*/ printf("Please input the outfile:"); scanf("%s",outfile);/*输入加密后文件的文件名*/ if((out=fopen(outfile,"w"))==NULL) { printf("Can not open the outfile!\n"); printf("Press any key to exit!\n"); fclose(in); getch(); exit(0); } while(!feof(in))/*加密*/ { fputc(encrypt(fgetc(in),n),out); } printf("\nEncrypt is over!\n"); fclose(in); fclose(out); sleep(1); } if(ch0=='2') { clrscr(); printf("\nPlease input the infile:"); scanf("%s",infile);/*输入需要解密的文件名*/ if((in=fopen(infile,"r"))==NULL) { printf("Can not open the infile!\n"); printf("Press any key to exit!\n"); getch(); exit(0); } printf("Please input the key:"); scanf("%d",&n);/*输入解密密码(可以为加密时候的密码)*/ n=26-n; printf("Please input the outfile:"); scanf("%s",outfile);/*输入解密后文件的文件名*/ if((out=fopen(outfile,"w"))==NULL) { printf("Can not open the outfile!\n"); printf("Press any key to exit!\n"); fclose(in); getch(); exit(0); } while(!feof(in)) { fputc(encrypt(fgetc(in),n),out); } printf("\nDecrypt is over!\n"); fclose(in); fclose(out); sleep(1); } clrscr(); printf("\nGood Bye!\n"); sleep(3); getch(); } }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡林神不是猫

如果您觉得有帮助可以鼓励小卡哦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值