日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Go?語言簡單實現Vigenere加密算法_Golang

作者:宇宙之一粟??????? ? 更新時間: 2022-11-02 編程語言

Vigenere 加密算法

該密碼由意大利密碼學家 Giovan Battista Bellaso 于 1553 年發明,但幾個世紀以來一直歸功于 16 世紀的法國密碼學家 Blaise de Vigenère,他在 1586 年設計了類似的密碼。

Vigenere Cipher 是一種加密字母文本的方法。它使用一種簡單的多字母表替換形式。多字母密碼是基于替換的任何密碼,使用多個替換字母表。原始文本的加密是使用 Vigenère square 或 Vigenère table 完成的。

該表由在不同行中寫出 26 次的字母組成,與前一個字母相比,每個字母循環向左移動,對應于 26 種可能的凱撒密碼。

在最簡單的 Vigenère 類型系統中,密鑰是一個單詞或短語,它可以根據需要重復多次以加密消息。如果密鑰是欺騙性的,并且消息是我們被發現了,請自救,那么生成的密碼將是

在加密過程的不同點,密碼使用與其中一行不同的字母表。每個點使用的字母取決于重復的關鍵字。

又例如:

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

欄目分類
最近更新