using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RailFence { class Program { public static string Encrypt(string plainText, int key) { int plainTextLength = plainText.Length; while (plainTextLength % key != 0) { plainText = plainText + " "; plainTextLength++; } int idx = plainTextLength / key; int counterPart = 0; string[] part = new string[idx]; for(int i = 0; i < plainTextLength; i = i + key) { part[counterPart] = plainText.Substring(i, key); counterPart++; } string enc = ""; string spos = " "; for (int k = 0; k < key; k++) { int step = key; if (step % 2 != 0) { if (k % 2 == 0) step++; else step--; } for (int x = k; x < idx; x = x + step) { spos = spos + x + " "; enc = enc + part[x]; } spos = " "; } return enc; } public static string Decrypt(string textoEncriptado, int key) { int textoEncriptadoLength = textoEncriptado.Length; int idx = textoEncriptadoLength / key; int counterPart = 0; string[] decPos = new string[idx]; string[] part = new string[idx]; for (int i = 0; i < textoEncriptadoLength; i = i + key) { part[counterPart] = textoEncriptado.Substring(i, key); counterPart++; } string dec = ""; int encCounter = 0; string spos = " "; for (int k = 0; k < key; k++) { int step = key; if (step % 2 != 0) { if (k % 2 == 0) step++; else step--; } for (int x = k; x < idx; x = x + step) { spos = spos + x + " ("+encCounter+")"; decPos[x] = part[encCounter]; encCounter++; } spos = " "; } for (int y = 0; y < idx; y++ ) { dec = dec + decPos[y]; } return dec; } static void Main(string[] args) { int key = 3; string plainText = "History has taught us: never underestimate the amount of money, time, " + "and effort someone will expend to thwart a security system. It's always " + "better to assume the worst. Assume your adversaries are better than they " + "are. Assume science and technology will soon be able to do things they " + "cannot yet. Give yourself a margin for error. Give yourself more security " + "than you need today. When the unexpected happens, you'll be glad you did. " + "--Bruce Schneier"; String textEncrypted = Encrypt(plainText, key); Console.WriteLine(textEncrypted+"\n"); String textDecrypted = Decrypt(textEncrypted, key); Console.WriteLine(textDecrypted); Console.ReadLine(); } } }