Task: Playfair cipher


C++: #include <iostream>
#include <string>

using namespace std;

class playfair
{
public:
    void doIt( string k, string t, bool ij, bool e )
    {
	createGrid( k, ij ); getTextReady( t, ij, e );
	if( e ) doIt( 1 ); else doIt( -1 );
	display();
    }

private:
    void doIt( int dir )
    {
	int a, b, c, d; string ntxt;
	for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
	{
	    if( getCharPos( *ti++, a, b ) )
		if( getCharPos( *ti, c, d ) )
		{
		    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
		    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
		    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
		}
	}
	_txt = ntxt;
    }

    void display()
    {
	cout << "\n\n OUTPUT:\n=========" << endl;
	string::iterator si = _txt.begin(); int cnt = 0;
	while( si != _txt.end() )
	{
	    cout << *si; si++; cout << *si << " "; si++;
	    if( ++cnt >= 26 ) cout << endl, cnt = 0;
	}
	cout << endl << endl;
    }

    char getChar( int a, int b )
    {
	return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
    }

    bool getCharPos( char l, int &a, int &b )
    {
	for( int y = 0; y < 5; y++ )
	    for( int x = 0; x < 5; x++ )
		if( _m[y][x] == l )
		{ a = x; b = y; return true; }

	return false;
    }

    void getTextReady( string t, bool ij, bool e )
    {
	for( string::iterator si = t.begin(); si != t.end(); si++ )
	{
	    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
	    if( *si == 'J' && ij ) *si = 'I';
	    else if( *si == 'Q' && !ij ) continue;
	    _txt += *si;
	}
	if( e )
	{
	    string ntxt = ""; size_t len = _txt.length();
	    for( size_t x = 0; x < len; x += 2 )
	    {
		ntxt += _txt[x];
		if( x + 1 < len )
		{
		    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
		    ntxt += _txt[x + 1];
		}
	    }
	    _txt = ntxt;
	}
	if( _txt.length() & 1 ) _txt += 'X';
    }

    void createGrid( string k, bool ij )
    {
	if( k.length() < 1 ) k = "KEYWORD"; 
	k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
	for( string::iterator si = k.begin(); si != k.end(); si++ )
	{
	    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
	    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
	    if( nk.find( *si ) == -1 ) nk += *si;
	}
	copy( nk.begin(), nk.end(), &_m[0][0] );
    }

    string _txt; char _m[5][5];
};

int main( int argc, char* argv[] )
{
    string key, i, txt; bool ij, e;
    cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
    cout << "Enter a en/decryption key: "; getline( cin, key ); 
    cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
    cout << "Enter the text: "; getline( cin, txt ); 
    playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}



Go: package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

type playfairOption int

const (
    noQ playfairOption = iota
    iEqualsJ
)

type playfair struct {
    keyword string
    pfo     playfairOption
    table   [5][5]byte
}

func (p *playfair) init() {
    
    var used [26]bool 
    if p.pfo == noQ {
        used[16] = true 
    } else {
        used[9] = true 
    }
    alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
        c := alphabet[k]
        if c < 'A' || c > 'Z' {
            continue
        }
        d := int(c - 65)
        if !used[d] {
            p.table[i][j] = c
            used[d] = true
            j++
            if j == 5 {
                i++
                if i == 5 {
                    break 
                }
                j = 0
            }
        }
    }
}

func (p *playfair) getCleanText(plainText string) string {
    
    plainText = strings.ToUpper(plainText)
    
    var cleanText strings.Builder
    
    prevByte := byte('\000')
    for i := 0; i < len(plainText); i++ {
        nextByte := plainText[i]
        
        
        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
            continue
        }
        
        if nextByte == 'J' && p.pfo == iEqualsJ {
            nextByte = 'I'
        }
        if nextByte != prevByte {
            cleanText.WriteByte(nextByte)
        } else {
            cleanText.WriteByte('X')
            cleanText.WriteByte(nextByte)
        }
        prevByte = nextByte
    }
    l := cleanText.Len()
    if l%2 == 1 {
        
        if cleanText.String()[l-1] != 'X' {
            cleanText.WriteByte('X')
        } else {
            cleanText.WriteByte('Z')
        }
    }
    return cleanText.String()
}

func (p *playfair) findByte(c byte) (int, int) {
    for i := 0; i < 5; i++ {
        for j := 0; j < 5; j++ {
            if p.table[i][j] == c {
                return i, j
            }
        }
    }
    return -1, -1
}

func (p *playfair) encode(plainText string) string {
    cleanText := p.getCleanText(plainText)
    var cipherText strings.Builder
    l := len(cleanText)
    for i := 0; i < l; i += 2 {
        row1, col1 := p.findByte(cleanText[i])
        row2, col2 := p.findByte(cleanText[i+1])
        switch {
        case row1 == row2:
            cipherText.WriteByte(p.table[row1][(col1+1)%5])
            cipherText.WriteByte(p.table[row2][(col2+1)%5])
        case col1 == col2:
            cipherText.WriteByte(p.table[(row1+1)%5][col1])
            cipherText.WriteByte(p.table[(row2+1)%5][col2])
        default:
            cipherText.WriteByte(p.table[row1][col2])
            cipherText.WriteByte(p.table[row2][col1])
        }
        if i < l-1 {
            cipherText.WriteByte(' ')
        }
    }
    return cipherText.String()
}

func (p *playfair) decode(cipherText string) string {
    var decodedText strings.Builder
    l := len(cipherText)
    
    for i := 0; i < l; i += 3 {
        row1, col1 := p.findByte(cipherText[i])
        row2, col2 := p.findByte(cipherText[i+1])
        switch {
        case row1 == row2:
            temp := 4
            if col1 > 0 {
                temp = col1 - 1
            }
            decodedText.WriteByte(p.table[row1][temp])
            temp = 4
            if col2 > 0 {
                temp = col2 - 1
            }
            decodedText.WriteByte(p.table[row2][temp])
        case col1 == col2:
            temp := 4
            if row1 > 0 {
                temp = row1 - 1
            }
            decodedText.WriteByte(p.table[temp][col1])
            temp = 4
            if row2 > 0 {
                temp = row2 - 1
            }
            decodedText.WriteByte(p.table[temp][col2])
        default:
            decodedText.WriteByte(p.table[row1][col2])
            decodedText.WriteByte(p.table[row2][col1])
        }
        if i < l-1 {
            decodedText.WriteByte(' ')
        }
    }
    return decodedText.String()
}

func (p *playfair) printTable() {
    fmt.Println("The table to be used is :\n")
    for i := 0; i < 5; i++ {
        for j := 0; j < 5; j++ {
            fmt.Printf("%c ", p.table[i][j])
        }
        fmt.Println()
    }
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Print("Enter Playfair keyword : ")
    scanner.Scan()
    keyword := scanner.Text()
    var ignoreQ string
    for ignoreQ != "y" && ignoreQ != "n" {
        fmt.Print("Ignore Q when building table  y/n : ")
        scanner.Scan()
        ignoreQ = strings.ToLower(scanner.Text())
    }
    pfo := noQ
    if ignoreQ == "n" {
        pfo = iEqualsJ
    }
    var table [5][5]byte
    pf := &playfair{keyword, pfo, table}
    pf.init()
    pf.printTable()
    fmt.Print("\nEnter plain text : ")
    scanner.Scan()
    plainText := scanner.Text()
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
        return
    }
    encodedText := pf.encode(plainText)
    fmt.Println("\nEncoded text is :", encodedText)
    decodedText := pf.decode(encodedText)
    fmt.Println("Deccoded text is :", decodedText)
}