1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Go】Goでシーザー暗号書いてみた

Last updated at Posted at 2025-01-03

概要

暗号技術入門 第3版で最初の方に出てくる暗号、シーザー暗号をGo実装してみた

サンプルコード

package main

import "fmt"

const (
	AlphabetSize = 26
	Shift        = 1
)

// シーザー暗号の実装
func caesarCipher(input string, shift int) string {
	// 「shift % AlphabetSize」・・・-25~25の範囲内の数値に変換
	// 「+ AlphabetSize」・・・-25~-1の値を0~25の範囲内の数値に変換。0~25だった数値は26~51となってしまう
	// 「% AlphabetSize」・・・26~51となってしまった数値を0~25の範囲内の数値に変換
	shift = (shift%AlphabetSize + AlphabetSize) % AlphabetSize // シフトを正の範囲に正規化

	var result []rune
	for _, char := range input {
		if char >= 'A' && char <= 'Z' { // 大文字の場合
			shifted := 'A' + (char-'A'+rune(shift))%AlphabetSize
			result = append(result, shifted)
		} else if char >= 'a' && char <= 'z' { // 小文字の場合
			shifted := 'a' + (char-'a'+rune(shift))%AlphabetSize
			result = append(result, shifted)
		} else {
			// アルファベット以外の文字はそのまま
			result = append(result, char)
		}
	}
	return string(result)
}

func main() {
	text := "Hello, world!"
	fmt.Printf("Original: %s\n", text)

	encrypted := caesarCipher(text, Shift) // 暗号化
	fmt.Printf("Encrypted: %s\n", encrypted)

	decrypted := caesarCipher(encrypted, -Shift) // 復号化
	fmt.Printf("Decrypted: %s\n", decrypted)
}

// 出力
// Original: Hello, world!
// Encrypted: Ifmmp, xpsme!
// Decrypted: Hello, world!
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?