网络编程
位置:首页>> 网络编程>> Go语言>> Go 语言简单实现Vigenere加密算法

Go 语言简单实现Vigenere加密算法

作者:宇宙之一粟???????  发布时间:2024-05-08 10:14:04 

标签:Go,Vigenere,加密,算法

Vigenere 加密算法

该密码由意大利密码学家 Giovan Battista Bellaso 于 1553 年发明,但几个世纪以来一直归功于 16 世纪的法国密码学家 Blaise de Vigenère,他在 1586 年设计了类似的密码。

Vigenere Cipher 是一种加密字母文本的方法。它使用一种简单的多字母表替换形式。多字母密码是基于替换的任何密码,使用多个替换字母表。原始文本的加密是使用 Vigenère square 或 Vigenère table 完成的。

该表由在不同行中写出 26 次的字母组成,与前一个字母相比,每个字母循环向左移动,对应于 26 种可能的凯撒密码。

在最简单的 Vigenère 类型系统中,密钥是一个单词或短语,它可以根据需要重复多次以加密消息。如果密钥是欺骗性的,并且消息是我们被发现了,请自救,那么生成的密码将是

Go 语言简单实现Vigenere加密算法

在加密过程的不同点,密码使用与其中一行不同的字母表。每个点使用的字母取决于重复的关键字。

又例如:

Input : Plaintext :   GEEKSFORGEEKS
            Keyword :  AYUSH
Output : Ciphertext :  GCYCZFMLYLEIM
For generating key, the given keyword is repeated
in a circular manner until it matches the length of
the plain text.
The keyword "AYUSH" generates the key "AYUSHAYUSHAYU"
The plain text is then encrypted using the process
explained below.

加密:

明文的第一个字母 G 与密钥的第一个字母 A 配对。所以使用 Vigenère 正方形的 G 行和 A 列,即 G。同理,对于明文的第二个字母,使用密钥的第二个字母,E 行的字母,Y 列的字母是 C。明文以类似的方式加密。

解密的方法是到表中与密钥对应的行,找到该行中密文字母的位置,然后将该列的标签作为明文。例如,在 A 行(来自 AYUSH)中,密文 G 出现在 G 列中,这是第一个明文字母。接下来,我们转到 Y 行(来自 AYUSH),找到在 E 列中找到的密文 C,因此 E 是第二个明文字母。

一个更简单的实现可能是通过将 [A-Z] 转换为数字 [0-25] 以代数方式可视化 Vigenère。

Go 代码

package main

import (
"fmt"
"strings"
)
func encodeString(cipher, key rune) rune {
const asciiA rune = 65
const numLetters = 26

plainTextIndex := cipher + key
asciiLetter := (plainTextIndex+numLetters)%numLetters + asciiA
return asciiLetter
}
func encode(message, kw string) string {
var plainText strings.Builder
kwChars := []rune(kw)

for i, cipherChar := range message {
key := i % len(kwChars)
plainText.WriteRune(encodeString(cipherChar, kwChars[key]))
}

return plainText.String()
}
func decipherString(cipher, key rune) rune {
const asciiA rune = 65
const numLetters = 26

plainTextIndex := cipher - key
asciiLetter := (plainTextIndex+numLetters)%numLetters + asciiA
return asciiLetter
}

func decipher(message, kw string) string {
var plainText strings.Builder
kwChars := []rune(kw)

for i, cipherChar := range message {
key := i % len(kwChars)
plainText.WriteRune(decipherString(cipherChar, kwChars[key]))
}

return plainText.String()
}

func main() {
fmt.Println("Enter Your string: ")

var first string

fmt.Scanln(&first)
fmt.Println("Enter your KEY: ")
var second string
fmt.Scanln(&second)
cipherText := first
keyword := second
fmt.Print("Do you want to  1. Encrypt or 2. Decrypt")
var option int
fmt.Scanln(&option)
if option == 1 {
fmt.Println(encode(cipherText, keyword))
} else if option == 2 {
fmt.Println(decipher(cipherText, keyword))
} else {
fmt.Println("please choose the right option")
}

}

来源:https://juejin.cn/post/7140296036429348878

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com