シーザー暗号 (Caesar cipher)
シフト暗号

プログラム

頻度分析を行って暗号文から平文を復元する例
1
-- If you want to use it type something like:
2
-- let tmp = encode 3 "Zombies ate my brains"
3
-- crack tmp
4
5
import Data.Char
6
7
helper = zip ['a'..'z'] [0..25]
8
9
let2num::Char -> Int
10
let2num c = head [ b | (a,b) <- helper, a==c]
11
num2let d = head [ a | (a,b) <- helper, b==(d `mod` length helper)]
12
13
shift num c = if isLower c == False
14
then c
15
else num2let( (let2num c) + num )
16
17
encode::Int->String->String
18
encode num = map (shift num)
19
decode num = map (shift ((length helper) - num))
20
21
lowers s = fromIntegral (length (filter isLower s ) )
22
count c s = fromIntegral (length (filter(==c) s) )
23
percent a b = (a/b)*100
24
25
freq::String->[Float]
26
freq s = [percent (count a s) (lowers s) | a<-['a'..'z']]
27
28
rotate::Int->String->String
29
rotate d s = (drop d s) ++ (take d s)
30
31
chisqr::[Float]->[Float]->Float
32
chisqr os es = sum [(a-b)^2/b | (a,b) <- zip os es]
33
34
position x xs = head [ b | (a,b) <- zip xs [0..(length xs -1)], a==x ]
35
36
freqArray s = [chisqr (freq (decode a s)) table | a <- [0..25]]
37
38
crack s = decode (position (minimum (freqArray s)) (freqArray s)) s
39
40
table::[Float]
41
table = [8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0,
42
0.2, 0.8, 4.0, 2.4, 6.7, 7.5, 1.9, 0.1, 6.0,
43
6.3, 9.1, 2.8, 1.0, 2.4, 0.2, 2.0, 0.1]
Copied!

参考リソース

Last modified 2yr ago