Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Programming Challenge #10: Fun with cryptography
New Posts  All Forums:Forum Nav:

Programming Challenge #10: Fun with cryptography - Page 3

post #21 of 36
Two one-liner solutions here.

Note: I used the 'input' variable just to keep the lines readable. The input values could just as easily be put in line.
Also: If programming languages were characters in some kind of fighting game, everyone would play as C# because LINQ would be OP as hell.

One-liner medium challenge: word 20 = Pan Source code, written in C# (Click to show)
Code:
var mediumresult = new string(input.Split('-').Select(s => (char)(int.Parse(s, NumberStyles.HexNumber) - 1)).ToArray());

One-liner hard challenge: word 20 = Oh Source code, written in C# (Click to show)
Code:
var hardresult = new string(Regex.Matches(input, "..").Cast<Match>().Select((s, i) => (char)(int.Parse(s.Value, NumberStyles.HexNumber) - (int)"Plan9"[i % 5])).ToArray());


EDIT: Actually this is a better one-line solution for the hard. The line is a bit longer, but it doesn't use RegEx and does less casting, so it executes 3x faster:
I give myself bonus points for optimizing my code. tongue.gif

One-liner hard challenge: word 20 = Oh Improved Source code, written in C# (Click to show)
Code:
var hardresult = new string(Enumerable.Range(0, input.Length / 2).Select(i => input.Substring(i * 2, 2)).Select((s, i) => (char)(int.Parse(s, NumberStyles.HexNumber) - (int)"Plan9"[i % 5])).ToArray());

Quote:
Originally Posted by hajile View Post

(it's my mistyping while learning the colmak keyboard)

+Rep for that. I made the switch over a year ago. Totally worth it. The teething period is tough, you have to force yourself through it. Just stick with it and profit my friend.
Edited by wedge - 4/14/14 at 8:48am
Death Star
(21 items)
 
Darksaber
(11 items)
 
 
CPUMotherboardGraphicsRAM
Athlon II x2 245 Asus M3A78 Radeon HD6570 1GB Mushkin Silverline 2GB DDR2  
Hard DriveOptical DriveOSMonitor
OCZ Vertex 2 120GB Samsung Blu-Ray Windows 7 Samsung 46" DLP 
PowerCaseOther
Silverstone Strider Essentials 400W Silverstone Milo ML03B Hauppage WinTV 1250 
  hide details  
Reply
Death Star
(21 items)
 
Darksaber
(11 items)
 
 
CPUMotherboardGraphicsRAM
Athlon II x2 245 Asus M3A78 Radeon HD6570 1GB Mushkin Silverline 2GB DDR2  
Hard DriveOptical DriveOSMonitor
OCZ Vertex 2 120GB Samsung Blu-Ray Windows 7 Samsung 46" DLP 
PowerCaseOther
Silverstone Strider Essentials 400W Silverstone Milo ML03B Hauppage WinTV 1250 
  hide details  
Reply
post #22 of 36
Thanks to codepad.org, I've done the Vigenere part completely by using my phone only smile.gif
Here we go: Source written in C, Vigenere (Click to show)
Code:
// Vigenere.c
// Tomo70 :)

#include "stdio.h";
#include "string.h";
char* str="THisISaPlainTeXt";

char* encrypt(char* key, char* buff)
{
    int c, e, i=0, ik=0, k;
    while(1)
    {
        c=buff[i];
        if(c==0)
            break;
        k=key[ik++];
        if(k==0)
          {  k=key[0];
              ik=1; }
        e=(c|32)-97+(k|32);
        if (e>122)
            e-=26;
        buff[i++]=e;
    }
    return buff;
}


char* decrypt(char* key, char* buff)
{
    int c, e, i=0, ik=0, k;
    while(1)
    {
        c=buff[i];
        if(c==0)
            break;
        k=key[ik++];
        if(k==0)
          {  k=key[0];
              ik=1; }
        e=(c|32)+97-(k|32);
        if (e<97)
            e+=26;
        buff[i++]=e;
    }
    return buff;
}


int main()
{
    char *buffer = malloc(200);

    strcpy(buffer, str);

    printf("%s\r\n", buffer);
    printf("%s\r\n", encrypt("mykey", buffer));
    printf("%s\r\n", decrypt("mYkeY", buffer));

    printf("%s\r\n", decrypt("mykEy", encrypt("myKey", buffer)));

    free(buffer);
    return 0;
}
post #23 of 36
Quote:
Originally Posted by Plan9 View Post

Most languages have in built libraries for converting characters to integers (since strings are just byte arrays at the lowest level). In PHP, you'd want ord() and chr():
http://www.php.net/manual/en/function.ord.php

Thanks Plan9, I have not had much experience with them and I did see where others had used those. I will definitely read up on them for the next one. smile.gif
Main Rig
(13 items)
 
BOINC
(15 items)
 
E5-26XX V2 2P
(12 items)
 
CPUMotherboardGraphicsGraphics
Intel 3770K MSI Z77 MPower MSI R7970 Lightning MSI R7950 Twin Frozr 
RAMHard DriveCoolingOS
G. Skill Trident seagate Baracuda Custom Liquid windows 7 64bit 
MonitorKeyboardPowerCase
ASUS VE248 Microsoft Wireless Corsair HX1000 Cosmos S 
Mouse
Microsoft Wireless 
CPUMotherboardGraphicsGraphics
Q9550 2.83Ghz @ 4.0Ghz 1.328v Gigabyte EP45T-DS3R Ati Radeon hd 6970 Sapphire HD 7970 
RAMHard DriveOptical DriveCooling
Corsair XMS3 seagate Baracuda LG Blu-Ray RW rosewill air cooler 
OSMonitorKeyboardPower
Windows Pro 64-Bit none Micosoft Wireless OCZ 1000w 
CaseMouse
Antec 900 Microsoft Wireless 
CPUCPUMotherboardGraphics
Xeon E5-26XX V2 2.3-2.7Ghz 10core/20 thread Xeon E5-26XX V2 2.3-2.7Ghz 10core/20 thread SuperMicro x9DAi EVGA GTX 580 
RAMRAMHard DriveCooling
G.SKILL Ripjaws X Series 8GB (4 x 2GB) 240-Pin ... G.SKILL Ripjaws X Series 8GB (4 x 2GB) 240-Pin ... Patriot 16gb Flash drive Hyper 212+ evo 
CoolingOSPowerCase
Hyper 212+ evo Ubuntu 12.04 OCZ Z series 1000w gold Fractal design define xl 
  hide details  
Reply
Main Rig
(13 items)
 
BOINC
(15 items)
 
E5-26XX V2 2P
(12 items)
 
CPUMotherboardGraphicsGraphics
Intel 3770K MSI Z77 MPower MSI R7970 Lightning MSI R7950 Twin Frozr 
RAMHard DriveCoolingOS
G. Skill Trident seagate Baracuda Custom Liquid windows 7 64bit 
MonitorKeyboardPowerCase
ASUS VE248 Microsoft Wireless Corsair HX1000 Cosmos S 
Mouse
Microsoft Wireless 
CPUMotherboardGraphicsGraphics
Q9550 2.83Ghz @ 4.0Ghz 1.328v Gigabyte EP45T-DS3R Ati Radeon hd 6970 Sapphire HD 7970 
RAMHard DriveOptical DriveCooling
Corsair XMS3 seagate Baracuda LG Blu-Ray RW rosewill air cooler 
OSMonitorKeyboardPower
Windows Pro 64-Bit none Micosoft Wireless OCZ 1000w 
CaseMouse
Antec 900 Microsoft Wireless 
CPUCPUMotherboardGraphics
Xeon E5-26XX V2 2.3-2.7Ghz 10core/20 thread Xeon E5-26XX V2 2.3-2.7Ghz 10core/20 thread SuperMicro x9DAi EVGA GTX 580 
RAMRAMHard DriveCooling
G.SKILL Ripjaws X Series 8GB (4 x 2GB) 240-Pin ... G.SKILL Ripjaws X Series 8GB (4 x 2GB) 240-Pin ... Patriot 16gb Flash drive Hyper 212+ evo 
CoolingOSPowerCase
Hyper 212+ evo Ubuntu 12.04 OCZ Z series 1000w gold Fractal design define xl 
  hide details  
Reply
post #24 of 36
(The file handling functions in the code are because I'm storing the text in an input file, a little more versatile that way but probably unnecessary unless more ciphertexts are inbound tongue.gif )

Easy challenge, source code in C:
C code underneath (Click to show)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Compiled using gcc in Linux

int main(int argc, char *argv[])
{
  FILE *fp;
  char infile[80] = "";
  int c;

  strcpy(infile, argv[1]);

  fp = fopen(infile, "r");

    while ((c = getc(fp)) != EOF)
        putchar(c-1); // Output not sanitized, will probably do strange things if the ASCII text accidentally includes control characters
    fclose(fp);
    printf("\n\n");
}

The result:
First word (Click to show)
Far

Medium challenge, source code in C:
C code underneath (Click to show)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// Compiled using gcc in Linux

int string_to_array(const char *str, int *output)
{
    int *out = output;
    for (; *str; str++) {
        if (isxdigit(*str & 0xff)) {
            char ch = tolower(*str & 0xff);
            *out++ = (ch >= 'a' && ch <= 'z') ? ch - 'a' + 10 : ch - '0';
        }
    }
    return out - output;
}

int main(int argc, char *argv[])
{
  FILE *fp;
  char infile[80] = "";
  char buff[2] = "";
  char i;
  int output;
  int numc[2];
  int index = 0;
  int j;

  strcpy(infile, argv[1]);

  fp = fopen(infile, "r");

  while ((i = getc(fp)) != EOF)
    {
      if(i != '-')
        {
          buff[index] = i;
          index++;
        } else  {
          index = 0;
          j = string_to_array(buff, numc);
          output = numc[0]*16 + numc[1] - 1;
          putchar(output); // Again, not sanitized so could do strange things
      }
    }
  fclose(fp);
  printf("\n");
}

The result:
Last word (Click to show)
brick

The hard challenge was indeed hard, because I kept getting junk before I realized the nature of the ciphertext.
C code underneath (Click to show)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// Compiled using gcc in Linux

int string_to_array(const char *str, int *output)
{
    int *out = output;
    for (; *str; str++) {
        if (isxdigit(*str & 0xff)) {
            char ch = tolower(*str & 0xff);
            *out++ = (ch >= 'a' && ch <= 'z') ? ch - 'a' + 10 : ch - '0';
        }
    }
    return out - output;
}

int main(int argc, char *argv[])
{
  FILE *fp;
  char infile[80] = "";
  char buff[2] = "";
  char key[] = "Plan9";
  char i;
  int output;
  int shift = 0;
  int numc[2];
  int index1 = 0;
  int index2 = 0;
  int j;

  strcpy(infile, argv[1]);

  fp = fopen(infile, "r");

  while ((i = getc(fp)) != EOF)
    {
      buff[index1++] = i;
      if (index1 ==  2)
        {
          index1 = 0;
          j = string_to_array(buff, numc);
          output = numc[0]*16 + numc[1];
          shift = (int)key[index2++];
          j = (char)(output-shift);
          putchar(j); // Again, not sanitized so could do strange things
        }
      if (index2 > 4) { index2 = 0; }
    }
  fclose(fp);
  printf("\n");
}

The result:
Fifteenth word (Click to show)
petunias

Wheeeeeew! I'm not gonna try the more complicated challenges. tongue.gif
Edited by Quantum Reality - 4/19/14 at 2:37am
4690K System
(12 items)
 
HTPC
(9 items)
 
HP dv6 laptop
(13 items)
 
CPUMotherboardGraphicsRAM
Core i5 4690K ASRock Z97 Extreme4 XFX Radeon 7950 32 GB DDR3-2133 
Hard DriveOptical DriveCoolingOS
Samsung 850 EVO SSD Samsung DVD/CD-writer Corsair Hydro H60 Windows 7 
MonitorMonitorPowerCase
ASUS PA248Q Dell U2412M XFX 850W Black Edition XXX Fractal Design Arc Midi 2 
CPUMotherboardGraphicsRAM
Pentium Dual Core E6700 MSI G41M-P33 Combo ATI HD4350 Kingston ValueRAM DDR3-1333 
RAMHard DriveOSMonitor
Kingston ValueRAM DDR3-1333 WD Caviar Blue Windows 7 64-bit Sony 32" TV set 
Case
Apex TX-381 
CPUGraphicsRAMHard Drive
Core i5 430M GT230M (1 Gb dedicated) 8 GB DDR3-1066 640 GB 
OSMonitor
Windows 7 Home Premium (64-bit) 15.6" 
  hide details  
Reply
4690K System
(12 items)
 
HTPC
(9 items)
 
HP dv6 laptop
(13 items)
 
CPUMotherboardGraphicsRAM
Core i5 4690K ASRock Z97 Extreme4 XFX Radeon 7950 32 GB DDR3-2133 
Hard DriveOptical DriveCoolingOS
Samsung 850 EVO SSD Samsung DVD/CD-writer Corsair Hydro H60 Windows 7 
MonitorMonitorPowerCase
ASUS PA248Q Dell U2412M XFX 850W Black Edition XXX Fractal Design Arc Midi 2 
CPUMotherboardGraphicsRAM
Pentium Dual Core E6700 MSI G41M-P33 Combo ATI HD4350 Kingston ValueRAM DDR3-1333 
RAMHard DriveOSMonitor
Kingston ValueRAM DDR3-1333 WD Caviar Blue Windows 7 64-bit Sony 32" TV set 
Case
Apex TX-381 
CPUGraphicsRAMHard Drive
Core i5 430M GT230M (1 Gb dedicated) 8 GB DDR3-1066 640 GB 
OSMonitor
Windows 7 Home Premium (64-bit) 15.6" 
  hide details  
Reply
post #25 of 36
Made a GUI around it, here is relevant code.
6th last word "watches" Easy challenge, C# (Click to show)
Code:
StringBuilder sb = new StringBuilder();
            foreach (char c in BeforeConv)
            {
                sb.Append((char)((short)c - 1));
            }
            AfterConv = sb.ToString();

6th last word "wrapped" Medium challenge, C# (Click to show)
Code:
            StringBuilder sb = new StringBuilder();
            string input = BeforeConv.Replace("-", "").ToUpper();
            int length = input.Length;
            for (int i = 0; i < length - 1; i += 2)
            {
                int dec = Convert.ToInt32(input.Substring(i,2), 16)-1;
                sb.Append(Char.ConvertFromUtf32(dec));
            }
            AfterConv = sb.ToString();

5th last word "Universe": Medium challenge, C# (Click to show)
Code:
            StringBuilder sb = new StringBuilder();
            string plan9 = "Plan9";
            int length = BeforeConv.Length;
            for (int i = 0; i < length - 1; i += 2)
            {
                int dec = Convert.ToInt32(BeforeConv.Substring(i, 2),16) - Convert.ToInt32(plan9[i/2 % 5]);
                sb.Append(Char.ConvertFromUtf32(dec));
            }
            AfterConv = sb.ToString();

Even with looking at the other's their code last one still took me 20 minutes -,-. Took me way too long to realise i had to do i/2 instead of i.
Edited by Sisaroth - 4/19/14 at 2:43am
2013
(11 items)
 
  
CPUMotherboardGraphicsRAM
Intel Core i7 2700k GIGABYTE GA-Z77-D3H Sapphire HD 7870 XT Boost G.SKILL 1866 Sniper 2x4 GB 
Hard DriveHard DriveOSMonitor
Samsung 840 Basic Crucial MX200 Windows 10 HP IPS 23-inch 1080p 
PowerCaseMouse
Be quiet! BN144 System Power 7 500W NZXT Tempest 210 Zowie FK1 
  hide details  
Reply
2013
(11 items)
 
  
CPUMotherboardGraphicsRAM
Intel Core i7 2700k GIGABYTE GA-Z77-D3H Sapphire HD 7870 XT Boost G.SKILL 1866 Sniper 2x4 GB 
Hard DriveHard DriveOSMonitor
Samsung 840 Basic Crucial MX200 Windows 10 HP IPS 23-inch 1080p 
PowerCaseMouse
Be quiet! BN144 System Power 7 500W NZXT Tempest 210 Zowie FK1 
  hide details  
Reply
post #26 of 36
I decided to take a shot at the Polybius Square, this time in Visual Studio 2010 in C++ as a Win32 console application.
Source code, written in C plus plus (Click to show)
Code:
// Polybius.cpp : Encrypt text using the Polybius cipher.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
        char polybius[5][5] = {{'a', 'b', 'c', 'd', 'e'},
                                                   {'f', 'g', 'h', 'i', 'k'},
                                                   {'l', 'm', 'n', 'o', 'p'},
                                                   {'q', 'r', 's', 't', 'u'},
                                                   {'v', 'w', 'x', 'y', 'z'}};

        string line;
        char plaintext;
        int i, j, k, z;
        ifstream myfile;
        myfile.open(argv[1], ios::in);
        if (myfile.is_open())
                {
                        while ( getline (myfile,line) )
                                {
                                        z = line.length();
                                        for(i = 0; i < z; i++)
                                                {
                                                        plaintext = tolower(line[i]);
                                                        // Try to reasonably sanitize the input so the Polybius Square doesn't do funny things.
                                                        if (isalpha(plaintext))
                                                                {       
                                                                        if (plaintext == 'j') { plaintext = 'i'; }
                                                                        for (j = 0; j < 5; j++)
                                                                                {
                                                                                        for(k = 0; k < 5; k++)
                                                                                                {
                                                                                                        if(plaintext == polybius[k][j]) { break; }
                                                                                                }
                                                                                        if(plaintext == polybius[k][j]) { break; }
                                                                                }
                                                                        cout << k+1 << j+1 << "-" ;
                                                                }
                                                        if (plaintext == ' ') { cout << "00-"; }
                                                        // Unfortunately while this makes the output "cleaner" it also makes the cryptanalysis way easier,
                                                        // since it's such an obvious outlier
                                                }
                                        cout << endl;
                                }
                }
    myfile.close();
        return 0;
}

The input:
Code:
1cypher0
CYPHER
CYPHER cypher
abcdefghijklmnopqrstuvwxyz

The output:
Code:
13-54-35-23-15-42-
13-54-35-23-15-42-
13-54-35-23-15-42-00-13-54-35-23-15-42-
11-12-13-14-15-21-22-23-24-24-25-31-32-33-34-35-41-42-43-44-45-51-52-53-54-55-

(I have yet to figure out an elegant solution to avoid trailing dashes at the end of a line frown.gif )

Next step will of course be the DEcryption end of this. smile.gif
Edited by Quantum Reality - 4/19/14 at 5:35pm
4690K System
(12 items)
 
HTPC
(9 items)
 
HP dv6 laptop
(13 items)
 
CPUMotherboardGraphicsRAM
Core i5 4690K ASRock Z97 Extreme4 XFX Radeon 7950 32 GB DDR3-2133 
Hard DriveOptical DriveCoolingOS
Samsung 850 EVO SSD Samsung DVD/CD-writer Corsair Hydro H60 Windows 7 
MonitorMonitorPowerCase
ASUS PA248Q Dell U2412M XFX 850W Black Edition XXX Fractal Design Arc Midi 2 
CPUMotherboardGraphicsRAM
Pentium Dual Core E6700 MSI G41M-P33 Combo ATI HD4350 Kingston ValueRAM DDR3-1333 
RAMHard DriveOSMonitor
Kingston ValueRAM DDR3-1333 WD Caviar Blue Windows 7 64-bit Sony 32" TV set 
Case
Apex TX-381 
CPUGraphicsRAMHard Drive
Core i5 430M GT230M (1 Gb dedicated) 8 GB DDR3-1066 640 GB 
OSMonitor
Windows 7 Home Premium (64-bit) 15.6" 
  hide details  
Reply
4690K System
(12 items)
 
HTPC
(9 items)
 
HP dv6 laptop
(13 items)
 
CPUMotherboardGraphicsRAM
Core i5 4690K ASRock Z97 Extreme4 XFX Radeon 7950 32 GB DDR3-2133 
Hard DriveOptical DriveCoolingOS
Samsung 850 EVO SSD Samsung DVD/CD-writer Corsair Hydro H60 Windows 7 
MonitorMonitorPowerCase
ASUS PA248Q Dell U2412M XFX 850W Black Edition XXX Fractal Design Arc Midi 2 
CPUMotherboardGraphicsRAM
Pentium Dual Core E6700 MSI G41M-P33 Combo ATI HD4350 Kingston ValueRAM DDR3-1333 
RAMHard DriveOSMonitor
Kingston ValueRAM DDR3-1333 WD Caviar Blue Windows 7 64-bit Sony 32" TV set 
Case
Apex TX-381 
CPUGraphicsRAMHard Drive
Core i5 430M GT230M (1 Gb dedicated) 8 GB DDR3-1066 640 GB 
OSMonitor
Windows 7 Home Premium (64-bit) 15.6" 
  hide details  
Reply
post #27 of 36
@quantum reality
to get rid of the trailing hyphen:
if there is another character after the current one, then add a hyphen
else, don't add a hyphen
post #28 of 36
Looks like this (mostly) works:
Code:
if (plaintext == ' ') { cout << "-00"; }
if ((line[i+1] != '\n') && (line[i+1] != '\n') && isalpha(line[i+1])) { cout << "-"; }

Don't know a more elegant way to do it.
Code:
-13-54-35-23-15-42
13-54-35-23-15-42
13-54-35-23-15-42-00-13-54-35-23-15-42
11-12-13-14-15-21-22-23-24-24-25-31-32-33-34-35-41-42-43-44-45-51-52-53-54-55

EDIT:

In the course of changing the code to output random nonsense on any non-alpha character I was able to come up with a more elegant solution. smile.gif Unfortunately the compiler does give a warning about the random seed:
Code:
1>Polybius.cpp(25): warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
Modified Code (Click to show)
Code:
// Polybius.cpp : Encrypt text using the Polybius cipher.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <ctime>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
        char polybius[5][5] = {{'a', 'b', 'c', 'd', 'e'},
                                                   {'f', 'g', 'h', 'i', 'k'},
                                                   {'l', 'm', 'n', 'o', 'p'},
                                                   {'q', 'r', 's', 't', 'u'},
                                                   {'v', 'w', 'x', 'y', 'z'}};

        string line;
        char plaintext;
        int i, j, k, z;
        ifstream myfile;
        myfile.open(argv[1], ios::in);
        srand(time(NULL)); // Reasonably good random seed
        if (myfile.is_open())
                {
                        while ( getline (myfile,line) )
                                {
                                        z = line.length();
                                        for(i = 0; i < z; i++)
                                                {
                                                        plaintext = tolower(line[i]);
                                                        // Try to reasonably sanitize the input so the Polybius Square doesn't do funny things.
                                                        if (isalpha(plaintext))
                                                                {       
                                                                        if (plaintext == 'j') { plaintext = 'i'; }
                                                                        for (j = 0; j < 5; j++)
                                                                                {
                                                                                        for(k = 0; k < 5; k++)
                                                                                                {
                                                                                                        if(plaintext == polybius[k][j]) { break; }
                                                                                                }
                                                                                        if(plaintext == polybius[k][j]) { break; }
                                                                                }
                                                                        cout << k+1 << j+1;
                                                                } else {
                                                                        // Try to make it a little less obvious that nonalpha characters are being transformed
                                                                        cout << rand() % 5 + 1;
                                                                        cout << rand() % 5 + 1;
                                                                }
                                                        
                                                        if (isalpha(line[i+1]) || isdigit(line[i+1]) || (line[i+1] == ' ')) { cout << "-"; }
                                                }
                                        cout << endl;
                                }
                }
        myfile.close();
        return 0;
}

Sample output:
Code:
55-13-54-35-23-15-42-44
13-54-35-23-15-42
13-54-35-23-15-42-24-13-54-35-23-15-42
11-12-13-14-15-21-22-23-24-24-25-31-32-33-34-35-41-42-43-44-45-51-52-53-54-55

biggrin.gif

And I wrote the corresponding DEcrypter, also a VS 2010 Win32 console app:
Source code, written in C plus plus (Click to show)
Code:
// Polybius-Decrypt.cpp : Decrypt Polybius encrypted text.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
        char polybius[5][5] = {{'a', 'b', 'c', 'd', 'e'},
                           {'f', 'g', 'h', 'i', 'k'},
                           {'l', 'm', 'n', 'o', 'p'},
                           {'q', 'r', 's', 't', 'u'},
                           {'v', 'w', 'x', 'y', 'z'}};

        string line;
        int ciphertext[2];
        int i = 0;
        int j;
        int row = 0;
        int column = 0;
        int z = 0;
        ifstream myfile;
        myfile.open(argv[1], ios::in);
    
    if (myfile.is_open())
                {
                        while (getline(myfile,line))
                                {
                                        z = line.length();
                                        j = 0;
                                        for (i = 0; i <= z; i++)
                                                {
                                                        if(isdigit(line[i]))
                                                                {
                                                                        ciphertext[j] = line[i] - '0';
                                                                        j++;
                                                                } else {
                                                                        j = 0;
                                                                        row = ciphertext[0] - 1;
                                                                        column = ciphertext[1] - 1;
                                                                        cout << polybius[row][column];
                                                                }
                                                }
                                        cout << endl;
                                }
                }
        myfile.close();
        return 0;
}

The above output decrypts to:
Code:
zcyphert
cypher
cyphericypher
abcdefghiiklmnopqrstuvwxyz

So the original text is not quite reconstructed, but good enough for anyone who nefariously cryptanalyzes it tongue.gif
Edited by Quantum Reality - 4/20/14 at 2:35am
4690K System
(12 items)
 
HTPC
(9 items)
 
HP dv6 laptop
(13 items)
 
CPUMotherboardGraphicsRAM
Core i5 4690K ASRock Z97 Extreme4 XFX Radeon 7950 32 GB DDR3-2133 
Hard DriveOptical DriveCoolingOS
Samsung 850 EVO SSD Samsung DVD/CD-writer Corsair Hydro H60 Windows 7 
MonitorMonitorPowerCase
ASUS PA248Q Dell U2412M XFX 850W Black Edition XXX Fractal Design Arc Midi 2 
CPUMotherboardGraphicsRAM
Pentium Dual Core E6700 MSI G41M-P33 Combo ATI HD4350 Kingston ValueRAM DDR3-1333 
RAMHard DriveOSMonitor
Kingston ValueRAM DDR3-1333 WD Caviar Blue Windows 7 64-bit Sony 32" TV set 
Case
Apex TX-381 
CPUGraphicsRAMHard Drive
Core i5 430M GT230M (1 Gb dedicated) 8 GB DDR3-1066 640 GB 
OSMonitor
Windows 7 Home Premium (64-bit) 15.6" 
  hide details  
Reply
4690K System
(12 items)
 
HTPC
(9 items)
 
HP dv6 laptop
(13 items)
 
CPUMotherboardGraphicsRAM
Core i5 4690K ASRock Z97 Extreme4 XFX Radeon 7950 32 GB DDR3-2133 
Hard DriveOptical DriveCoolingOS
Samsung 850 EVO SSD Samsung DVD/CD-writer Corsair Hydro H60 Windows 7 
MonitorMonitorPowerCase
ASUS PA248Q Dell U2412M XFX 850W Black Edition XXX Fractal Design Arc Midi 2 
CPUMotherboardGraphicsRAM
Pentium Dual Core E6700 MSI G41M-P33 Combo ATI HD4350 Kingston ValueRAM DDR3-1333 
RAMHard DriveOSMonitor
Kingston ValueRAM DDR3-1333 WD Caviar Blue Windows 7 64-bit Sony 32" TV set 
Case
Apex TX-381 
CPUGraphicsRAMHard Drive
Core i5 430M GT230M (1 Gb dedicated) 8 GB DDR3-1066 640 GB 
OSMonitor
Windows 7 Home Premium (64-bit) 15.6" 
  hide details  
Reply
post #29 of 36
Sorry for the double post, but I'm stuck on the random Polybius. It almost works, but not quite. frown.gif It's throwing 6's where it shouldn't be able to. (EDIT: about the only thing I can think of is that the VC++ compiler may be trying to unroll the loops when it shouldn't. EDIT 2: Disabling all optimizations doesn't fix the problem, so it's not a loop unrolling thing. EDIT 3: I have absolutely zero idea why this works, but look at the commented edits to my code below.)

Sample output (see above for test input I've been using):
Output Inside (Click to show)
Code:
Supply this Polybius to decrypt!

c t m w v
z p s e b
u o y g i
q r a d f
x h n k l

53-11-33-22-25-42-24-42
11-33-22-25-42-24
11-33-22-25-42-24-51-11-33-22-25-42-24
34-52-11-44-42-54-43-25-53-53-45-55-31-35-23-22-63-24-32-21-62-51-41-64-33-61
Source code in C plus plus (Click to show)
Code:
// RandomPolybius.cpp : Make a randomized Polybius square cipher

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <ctime>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
   // Initialize all variables
   string line;
   char plaintext;
   
   ifstream myfile;

   char polybius[5][5];
   char alphabet[] = "abcdefghiklmnopqrstuvwxyz";
   int i, j, k, z;
   int flags[25];
   memset(flags, 0, sizeof(flags));

   // Start by randomizing the Polybius.
   srand(time(NULL)); // Reasonably good random seed
   cout << "Supply this Polybius to decrypt!" << endl << endl;
   for(i = 0; i < 5; i++)
      {
         for (j = 0; j < 5; j++)
            {
               k = rand() % 25;
               if (flags[k] == 1)
                  {
                     do { k = rand() % 25; } while (flags[k] == 1); // Avoid duplicates
                  }
               if (flags[k] == 0) { polybius[i][j] = alphabet[k]; flags[k] = 1; }
               cout << polybius[i][j] << " ";
            }
         cout << endl;
      }
   cout << endl;

   myfile.open(argv[1], ios::in);
   
   if (myfile.is_open())
      {
         while (getline(myfile,line))
            {
               z = line.length();
               for(i = 0; i < z; i++)
                  {
                     plaintext = tolower(line[i]);
                     // Try to reasonably sanitize the input so the Polybius Square doesn't do funny things.
                     if (isalpha(plaintext))
                        {       
                           if (plaintext == 'j') { plaintext = 'i'; }
                           for (j = 0; j < 5; j++)
                              {
                                 for(k = 0; k < 5; k++)
                                    {
                                       if(plaintext == polybius[j][k]) { break; } // switching to [k][j] here makes it work
                                    }
                                 if(plaintext == polybius[j][k]) { break; } // Same here.
                              }
                           cout << k+1 << j+1;
                        } else {
                           // Try to make it a little less obvious that nonalpha characters are being transformed
                           cout << rand() % 5 + 1;
                           cout << rand() % 5 + 1;
                        }
                     if (isalpha(line[i+1]) || isdigit(line[i+1]) || (line[i+1] == ' ')) { cout << "-"; }
                  }
               cout << endl;
            }
      }
   myfile.close();
   return 0;
}

Edited by Quantum Reality - 4/20/14 at 5:39pm
4690K System
(12 items)
 
HTPC
(9 items)
 
HP dv6 laptop
(13 items)
 
CPUMotherboardGraphicsRAM
Core i5 4690K ASRock Z97 Extreme4 XFX Radeon 7950 32 GB DDR3-2133 
Hard DriveOptical DriveCoolingOS
Samsung 850 EVO SSD Samsung DVD/CD-writer Corsair Hydro H60 Windows 7 
MonitorMonitorPowerCase
ASUS PA248Q Dell U2412M XFX 850W Black Edition XXX Fractal Design Arc Midi 2 
CPUMotherboardGraphicsRAM
Pentium Dual Core E6700 MSI G41M-P33 Combo ATI HD4350 Kingston ValueRAM DDR3-1333 
RAMHard DriveOSMonitor
Kingston ValueRAM DDR3-1333 WD Caviar Blue Windows 7 64-bit Sony 32" TV set 
Case
Apex TX-381 
CPUGraphicsRAMHard Drive
Core i5 430M GT230M (1 Gb dedicated) 8 GB DDR3-1066 640 GB 
OSMonitor
Windows 7 Home Premium (64-bit) 15.6" 
  hide details  
Reply
4690K System
(12 items)
 
HTPC
(9 items)
 
HP dv6 laptop
(13 items)
 
CPUMotherboardGraphicsRAM
Core i5 4690K ASRock Z97 Extreme4 XFX Radeon 7950 32 GB DDR3-2133 
Hard DriveOptical DriveCoolingOS
Samsung 850 EVO SSD Samsung DVD/CD-writer Corsair Hydro H60 Windows 7 
MonitorMonitorPowerCase
ASUS PA248Q Dell U2412M XFX 850W Black Edition XXX Fractal Design Arc Midi 2 
CPUMotherboardGraphicsRAM
Pentium Dual Core E6700 MSI G41M-P33 Combo ATI HD4350 Kingston ValueRAM DDR3-1333 
RAMHard DriveOSMonitor
Kingston ValueRAM DDR3-1333 WD Caviar Blue Windows 7 64-bit Sony 32" TV set 
Case
Apex TX-381 
CPUGraphicsRAMHard Drive
Core i5 430M GT230M (1 Gb dedicated) 8 GB DDR3-1066 640 GB 
OSMonitor
Windows 7 Home Premium (64-bit) 15.6" 
  hide details  
Reply
post #30 of 36
Hard challenge: word 4 = only Source code, written in Python 2.7 (Click to show)
Sort of a one-liner, depends on an import. It can be independent, but that would make it a little uglier.

I was expecting XOR which threw me off a little frown.gif
Code:
print "".join([chr(ord(cipher) - ord(key)) for cipher, key in zip("93e1d3d7a8c5dfcde759b5dad0e3a0b89881e2a1b58cd0dca5c98cd5d6a2bed381e2a1b1e081e59ebee081e2a1c2dbd6d5a170e0c9d359bdd5cfd259bfd281e2a1b58cc3ddb0bc8cd0d459c0d1d5e3a7b9cdd48e9ac38ccae259b6d1cdda59c7cdd48e88b88ccfdd6570dad0e259b1d3c2d7a77e8caecfa7c98cd1d3a8c0d8c68ea1b1e2c68eacc0d1c4e3a5b1e0c6d259c4d4c2e259b9d281e59e70d7cfd3b070d1d9cf9cc4d8da8eb0b8e581e2a1b58cc3ddb0bc8cd0d459c0d1d5e3a7b9cdd48ea1b1d081e2a1bfe1c8d6ad70e0c9cfad70e3c68eb0bfe1cdd259bbdad0e559b18ccdddad70d9d0e09e70cdc3ddaec48cd5d69e70dac2e2aec2d181dd9f70e0c9d359a5dacae49ec2dfc68eadb8cdcf8eb0b58cc5dd59bedbd89c".decode("hex"), itertools.cycle("Plan9"))])

Edited by Coma - 4/20/14 at 4:49pm
Akiyama Mio
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6420 @ stock, 0.98v Asus P5N-E SLI Gainward GTX 460 1GB @ 800/1600/1900 2x2GB Kingston @ 800MHz 5-5-5-15 2T 
Hard DriveOptical DriveOSMonitor
WD 250GB, 320GB SATA/3, 16MB Cache, Seagate 1TB LG GSA-H62N 18x SATA Ubuntu 9.10 x86 & Win7 x86 Asus VW222U 
KeyboardPowerCase
Logitech Classic Corsair 650HX NZXT Apollo Black 
  hide details  
Reply
Akiyama Mio
(13 items)
 
  
CPUMotherboardGraphicsRAM
E6420 @ stock, 0.98v Asus P5N-E SLI Gainward GTX 460 1GB @ 800/1600/1900 2x2GB Kingston @ 800MHz 5-5-5-15 2T 
Hard DriveOptical DriveOSMonitor
WD 250GB, 320GB SATA/3, 16MB Cache, Seagate 1TB LG GSA-H62N 18x SATA Ubuntu 9.10 x86 & Win7 x86 Asus VW222U 
KeyboardPowerCase
Logitech Classic Corsair 650HX NZXT Apollo Black 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Programming Challenge #10: Fun with cryptography