Vigenère cipher 维吉尼亚加密算法
- 维吉尼亚加密算法是凯撒加密算法的变种。
- 凯撒算法:
- 之前讲的凯撒算法例子是把字符串中的每个字母都向后移动了 3 位。
- 假设 A=0,B=1 … Z=25。那么,我们就用 D=3 来表示向后移动 3 位。

- 维吉尼亚加密算法使用的是密钥(keyword)
- 假设密钥是:GOLANG

习题
- 编写一个程序来解密下面第一行的文字:
- 它的密钥就是 GOLANG
- 所有字母都是大写的英文字母

package mainimport "fmt"func main() { cipherText := "CSOITEUIWUIZNSROCNKFD" keyword := "GOLANG" message := "" keyIndex := 0 for i := 0; i < len(cipherText); i++ { c := cipherText[i] - 'A' k := keyword[keyIndex] - 'A' c = (c-k+26)%26 + 'A' message += string(c) keyIndex++ keyIndex %= len(keyword) } fmt.Println(message)}
- 编写一个程序:
- 使用维吉尼亚加密算法来加密信息。
- 密钥为 GOLANG
- 可能用到的函数:
- strings.Replace
- strings.ToUpper
package mainimport ( "fmt" "strings")func main() { message := "your message goes here" keyword := "GOLANG" keyIndex := 0 cipherText := "" message = strings.ToUpper(strings.Replace(message, " ", "", -1)) for i := 0; i < len(message); i++ { c := message[i] if c >= 'A' && c <= 'Z' { c -= 'A' k := keyword[keyIndex] - 'A' c = (c+k)%26 + 'A' keyIndex++ keyIndex %= len(keyword) } cipherText += string(c) } fmt.Println(cipherText)}