Skip to content

Commit b519bc2

Browse files
committed
Implement working railfence encryption
1 parent 9e4d71e commit b519bc2

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

codext/crypto/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from .bacon import *
55
from .barbie import *
66
from .citrix import *
7+
from .railfence import *
78
from .rot import *
89
from .scytale import *
910
from .shift import *

codext/crypto/railfence.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# -*- coding: UTF-8 -*-
2+
"""Rail Fence Cipher Codec - rail fence encoding.
3+
4+
This codec:
5+
- en/decodes strings from str to str
6+
- en/decodes strings from bytes to bytes
7+
- decodes file content to str (read)
8+
- encodes file content from str to bytes (write)
9+
"""
10+
11+
12+
13+
from ..__common__ import *
14+
15+
16+
__examples__ = {
17+
'enc(rail-5-3)': "it sss etiath "
18+
}
19+
20+
21+
22+
def __buildf(text, rails, offset = 0) :
23+
l, rail, dr = len(text), offset, 1
24+
f = [["#"] * l for i in range(rails)]
25+
for x in range(l) :
26+
f[rail][x] = text[x]
27+
if rail >= rails - 1:
28+
dr = -1
29+
elif rail <= 0:
30+
dr = 1
31+
rail += dr
32+
for elem in f :
33+
print(elem)
34+
return f
35+
36+
def railfence_encode(rails, offset = 0) :
37+
def encode(text, errors="strict") :
38+
print(len(text))
39+
40+
c,l = '', len(text)
41+
f = __buildf(text,rails,offset)
42+
for r in range(rails) :
43+
for x in range(l) :
44+
if f[r][x] != '#' :
45+
c += f[r][x]
46+
return c, l
47+
return encode
48+
49+
def railfence_decode(rails, offset = 0) :
50+
def decode(text, errors = 'strict') :
51+
f = __buildf("x" * len(text), rails, offset)
52+
plain, i = '', 0
53+
ra, l = range(rails), range(len(text))
54+
55+
#Put the characters in the right place
56+
for r in ra:
57+
for x in l :
58+
if f[r][x] == "x" :
59+
f[r][x] = text[i]
60+
i += 1
61+
#Read the characters in the right order
62+
for x in l :
63+
for r in ra:
64+
if f[r][x] != '#' :
65+
plain += f[r][x]
66+
67+
return plain, len(plain)
68+
69+
return decode
70+
71+
add("rail", railfence_encode, railfence_decode, r"rail-(\d+)\-(\d+)$")
72+
73+
#rail-(\d+)\-(\d+)
74+
#rail-(\d+)(\-*(\d+))

0 commit comments

Comments
 (0)