File tree Expand file tree Collapse file tree 2 files changed +43
-1
lines changed Expand file tree Collapse file tree 2 files changed +43
-1
lines changed Original file line number Diff line number Diff line change @@ -8,6 +8,7 @@ mod hashing_traits;
8
8
mod kerninghan;
9
9
mod morse_code;
10
10
mod polybius;
11
+ mod rail_fence;
11
12
mod rot13;
12
13
mod salsa;
13
14
mod sha256;
@@ -17,7 +18,6 @@ mod theoretical_rot13;
17
18
mod transposition;
18
19
mod vigenere;
19
20
mod xor;
20
-
21
21
pub use self :: aes:: { aes_decrypt, aes_encrypt, AesKey } ;
22
22
pub use self :: another_rot13:: another_rot13;
23
23
pub use self :: base64:: { base64_decode, base64_encode} ;
@@ -29,6 +29,7 @@ pub use self::hashing_traits::HMAC;
29
29
pub use self :: kerninghan:: kerninghan;
30
30
pub use self :: morse_code:: { decode, encode} ;
31
31
pub use self :: polybius:: { decode_ascii, encode_ascii} ;
32
+ pub use self :: rail_fence:: { rail_fence_decrypt, rail_fence_encrypt} ;
32
33
pub use self :: rot13:: rot13;
33
34
pub use self :: salsa:: salsa20;
34
35
pub use self :: sha256:: SHA256 ;
Original file line number Diff line number Diff line change
1
+ // wiki: https://en.wikipedia.org/wiki/Rail_fence_cipher
2
+ pub fn rail_fence_encrypt ( plain_text : & str , key : usize ) -> String {
3
+ let mut cipher = vec ! [ Vec :: new( ) ; key] ;
4
+
5
+ for ( c, i) in plain_text. chars ( ) . zip ( zigzag ( key) ) {
6
+ cipher[ i] . push ( c) ;
7
+ }
8
+
9
+ return cipher. iter ( ) . flatten ( ) . collect :: < String > ( ) ;
10
+ }
11
+
12
+ pub fn rail_fence_decrypt ( cipher : & str , key : usize ) -> String {
13
+ let mut indices: Vec < _ > = zigzag ( key) . zip ( 1 ..) . take ( cipher. len ( ) ) . collect ( ) ;
14
+ indices. sort ( ) ;
15
+
16
+ let mut cipher_text: Vec < _ > = cipher
17
+ . chars ( )
18
+ . zip ( indices)
19
+ . map ( |( c, ( _, i) ) | ( i, c) )
20
+ . collect ( ) ;
21
+
22
+ cipher_text. sort ( ) ;
23
+ return cipher_text. iter ( ) . map ( |( _, c) | c) . collect ( ) ;
24
+ }
25
+
26
+ fn zigzag ( n : usize ) -> impl Iterator < Item = usize > {
27
+ ( 0 ..n - 1 ) . chain ( ( 1 ..n) . rev ( ) ) . cycle ( )
28
+ }
29
+
30
+ #[ cfg( test) ]
31
+ mod test {
32
+ use super :: * ;
33
+ #[ test]
34
+ fn rails_basic ( ) {
35
+ assert_eq ! ( rail_fence_encrypt( "attack at once" , 2 ) , "atc toctaka ne" ) ;
36
+ assert_eq ! ( rail_fence_decrypt( "atc toctaka ne" , 2 ) , "attack at once" ) ;
37
+
38
+ assert_eq ! ( rail_fence_encrypt( "rust is cool" , 3 ) , "r cuti olsso" ) ;
39
+ assert_eq ! ( rail_fence_decrypt( "r cuti olsso" , 3 ) , "rust is cool" ) ;
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments