Created
April 8, 2017 16:01
-
-
Save sergiks/adc4cc0914236ca30c76e14ba4772427 to your computer and use it in GitHub Desktop.
Rail Fence (zigzag) cipher JavaScript implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Rail Fence (zigzag) cipher JavaScript implementation. | |
* https://en.wikipedia.org/wiki/Rail_fence_cipher | |
*/ | |
(function (root, factory) { | |
if (typeof define === 'function' && define.amd) { | |
define([], factory); | |
} else if (typeof module === 'object' && module.exports) { | |
module.exports = factory(); | |
} else { | |
root.zigzag = factory(); | |
} | |
}(this, function () { | |
function makeMap( len, n) { | |
var i, pip, period = 2 * (n - 1); | |
var rows = Array.apply( null, Array( n)).map( function(){ return []}); // array of arrays | |
for( i = 0; i < len; i++) { | |
pip = i % period; | |
r = pip < (n - 1) ? pip : period - pip; | |
rows[ r].push( i); | |
} | |
return Array.concat.apply(null,rows); | |
} | |
function decrypt( text, n) { | |
var i, len = text.length, mapped = makeMap(len,n), result = ""; | |
return text.split('').reduce(function(p,c,i,a){ return p + a[mapped.indexOf(i)]},''); | |
for( i = 0; i < len; i++) result += text.substr( mapped.indexOf( i), 1); | |
return result; | |
} | |
function encrypt( text, n) { | |
var i, len = text.length, mapped = makeMap(len,n), result = ""; | |
for( i = 0; i < len; i++) result += text.substr( mapped[ i], 1); | |
return result; | |
} | |
return { | |
encrypt: encrypt | |
,decrypt: decrypt | |
}; | |
})); | |
var src = "этоттекстзашифрован"; | |
var enc = "экинтесшфаоттарвтзо"; | |
zigzag.decrypt(enc,4); | |
zigzag.encrypt(src,4); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment