Skip to content

added playfair cipher in Go lang #493

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 27, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
Simulation of Lamport's Logical Clock Syncronization
Sample Output Simulation : https://www.showterm.io/556636ec7caa4687680c0
References : Distributed systems: Principles and Paradigms, Andrew S. Tanenbaum

The program takes the following input :
nProcesses : total no. of processes in the system
nIterations : no. of counter/clock iterations for which the output is generated
clockConstant : the constant rate by which counter/clock is incremented on each tick

Output :
The program randomly generates a message between any two distinct processes in the system on every 3rd iteration. The message is added to a message queue and read by the recipient on the next iteration. Based on the timestamp at which the message was sent and current time on the receiver, clock time of receiver is adjusted if timestamp of message is >= receiver time else left the same. >= because it will take a finite amount of time to send the message always.
*/

package main

import (
"fmt" //for println,scanf
"math/rand" //for random number generator
"time" //for sleep
)

func main() {
var nProcesses, nIterations int // Number of processes, Number of iterations
fmt.Printf("Enter number of Processes and iterations you want to simulate : ")
_, err := fmt.Scanf("%d %d", &nProcesses, &nIterations) // _ is blank identifier
if err != nil {
fmt.Println("Error : " + err.Error())
}
clockTable := [][]int{} //table to store final counter/logical clock values
var clockConstants []int //slice to store values by which clock are incremented on each iteration
clockConstants = make([]int, nProcesses, nProcesses)

fmt.Printf("Enter the clock constants for each process : ") //user input for clock constants
for i := 0; i < nProcesses; i++ {
_, err := fmt.Scanf("%d", &clockConstants[i])
if err != nil {
fmt.Println("Error : " + err.Error())
}
}

var initClock []int
initClock = make([]int, nProcesses, nProcesses)
clockTable = append(clockTable, initClock)
var msgQueue []int //used to queue messages between processes.

//Print 1st iteration
for i := 0; i < nProcesses; i++ {
fmt.Printf(" P%d", i)
}
fmt.Println()
for j := 1; j <= nProcesses; j++ {
fmt.Printf("%4d", clockTable[0][j-1])
}
fmt.Println()

//Print other iterations
for i := 1; i < nIterations; i++ { //first iteration already passed so start from 2nd

time.Sleep(2000 * time.Millisecond) //sleep to slow the program down

var temp []int
temp = make([]int, nProcesses, nProcesses)
for j := 1; j <= nProcesses; j++ {
temp[j-1] = clockTable[i-1][j-1] + clockConstants[j-1]
}
clockTable = append(clockTable, temp)
/* generate messages to be sent in every 3rd iteration */
if (i+1)%3 == 0 {
var senderID, receiverID int
r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
senderID = r.Intn(nProcesses)
receiverID = r.Intn(nProcesses)
/*if receiver turns out to be same as sender, find new receiver*/
for receiverID == senderID {
receiverID = r.Intn(nProcesses)
}
msgQueue = append(msgQueue, senderID, receiverID) // add message to queue
fmt.Printf("Message sent by P%d to P%d at time t=%d at P1.\n", senderID, receiverID, clockTable[i-1][senderID])
}
for j := 0; j < nProcesses; j++ { //display clock values
fmt.Printf("%4d", clockTable[i][j])
}
fmt.Println()

for len(msgQueue) >= 2 {
var senderID, receiverID int = msgQueue[0], msgQueue[1]
var sendTime, recTime int = clockTable[i-1][senderID], clockTable[i][receiverID]
if clockTable[i-1][senderID] >= clockTable[i][receiverID] {
fmt.Printf("Message received by P%d at time=%d. Since %d <= %d , we adjust time from %d to %d.\n", receiverID, recTime, recTime, sendTime, recTime, (sendTime + 1))
for j := 0; j < nProcesses; j++ {
fmt.Printf("%4d", clockTable[i][j])
}
fmt.Printf(" -->") //display changed clock values
clockTable[i][receiverID] = clockTable[i-1][senderID] + 1
for j := 0; j < nProcesses; j++ {
fmt.Printf("%4d", clockTable[i][j])
}
fmt.Printf("\n")

} else {
fmt.Printf("Message received by P%d at time=%d. Since %d >= %d , no time adjustment needed.\n", receiverID, recTime, recTime, sendTime)
for j := 0; j < nProcesses; j++ {
fmt.Printf("%4d", clockTable[i][j])
}
fmt.Printf(" =") //display clock values without change
for j := 0; j < nProcesses; j++ {
fmt.Printf("%4d", clockTable[i][j])
}
fmt.Printf("\n")
}
msgQueue = append(msgQueue[:0], msgQueue[2:]...) //remove sender and receiver from msg queue
time.Sleep(2000 * time.Millisecond)
}
}
}
182 changes: 182 additions & 0 deletions Playfair_Cipher/Go/sjs7007/playfair.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/*

This is an implementation of the playfair cipher for encryption and decryption.

Input :
key : which is a lowercase string
msg : the message to be encrypted which is again a lower case string

Output :
Encrypted Message
Decryption of the encrypted message using the cipher

References : https://en.wikipedia.org/wiki/Playfair_cipher

Sample Output :
go run playfair.go

Enter the key with no spaces : mykey
Enter the message to be encrypted with no spaces : thisismymessage
Input : thisismymessage
Encrypted Msg : ponqnqykyaxetefa
Decrypted Msg : thisismymesxsage
*/

package main

import "fmt"
import "strings"
//import "math"

func main() {
var key = ""
fmt.Printf("Enter the key with no spaces : ")
_, err := fmt.Scanf("%s", &key) // _ is blank identifier
if err != nil {
fmt.Println("Error : " + err.Error())
}

var inputMsg = ""
fmt.Printf("Enter the message to be encrypted with no spaces : ")
_, err = fmt.Scanf("%s", &inputMsg) // _ is blank identifier
if err != nil {
fmt.Println("Error : " + err.Error())
}

var mat = ""
for i:=0 ; i<=25;i++ {
key = key + string(97+i)
}
for i := 0; i < len(key); i++ {
//fmt.Println(string(key[i])=="a")
var tmp = string(key[i])
if(tmp=="j") {
tmp="i"
}
if(!strings.Contains(mat,tmp)) {
mat = mat + tmp
}
}
//fmt.Println(mat)
playFairMatrix := [5][5]string{}
var count = 0
for i:=0 ; i<5;i++ {
for j:=0 ; j<5 ; j++ {
playFairMatrix[i][j]=string(mat[count])
count++
}
}
// fmt.Println(playFairMatrix)
var encrypted = encryptMsg(playFairMatrix,inputMsg)
var decrypted = decryptMsg(playFairMatrix,encrypted)
fmt.Printf("Input : %s\n",inputMsg)
fmt.Printf("Encrypted Msg : %s\n",encrypted)
fmt.Printf("Decrypted Msg : %s\n",decrypted)
}

func encryptMsg(playFairMatrix [5][5]string,input string) string {
var x= ""
for i:=0 ; i<len(input);i++ {
var ch1=string(input[i])
var ch2=string("z")
if(i+1!=len(input)) {
if(input[i+1]==input[i]) {
ch2=string("x")
} else {
ch2=string(input[i+1])
i++
}
}
//fmt.Print(ch1)
//fmt.Println(ch2)
var r1,r2,c1,c2 int
for i:=0 ; i<5;i++ {
for j:=0;j<5;j++ {
if(playFairMatrix[i][j]==ch1) {
r1=i
c1=j
}
}
}

for i:=0 ; i<5;i++ {
for j:=0;j<5;j++ {
if(playFairMatrix[i][j]==ch2) {
r2=i
c2=j
}
}
}
//case 1 : same row
if(r1==r2) {
x = x + string(playFairMatrix[r1][(c1+1)%5])
x = x + string(playFairMatrix[r1][(c2+1)%5])
} else if (c1==c2) { //case 2 : same column
x = x + string(playFairMatrix[(r1+1)%5][c1])
x = x + string(playFairMatrix[(r2+1)%5][c1])
} else { //case 3 :
x = x + string(playFairMatrix[r1][c2])
x = x + string(playFairMatrix[r2][c1])
}
}
//fmt.Println(x)
return x
}

func decryptMsg(playFairMatrix [5][5]string,input string) string {
var x= ""
for i:=0 ; i<len(input);i=i+2 {
var ch1=string(input[i])
var ch2=string(input[i+1])
//fmt.Print(ch1)
//fmt.Println(ch2)
var r1,r2,c1,c2 int
for i:=0 ; i<5;i++ {
for j:=0;j<5;j++ {
if(playFairMatrix[i][j]==ch1) {
r1=i
c1=j
}
}
}

for i:=0 ; i<5;i++ {
for j:=0;j<5;j++ {
if(playFairMatrix[i][j]==ch2) {
r2=i
c2=j
}
}
}

//case 1 : same row
if(r1==r2) {
var tmp = (c1-1)%5
if(tmp<0) {
tmp=4
}
x = x + string(playFairMatrix[r1][tmp])
tmp = (c2-1)%5
if(tmp<0) {
tmp=4
}
x = x + string(playFairMatrix[r1][tmp])
} else if (c1==c2) { //case 2 : same column
var tmp = (r1-1)%5
if(tmp<0) {
tmp=4
}
x = x + string(playFairMatrix[tmp][c1])
tmp = (r2-1)%5
if(tmp<0) {
tmp=4
}
x = x + string(playFairMatrix[tmp][c1])
} else { //case 3 :
x = x + string(playFairMatrix[r1][c2])
x = x + string(playFairMatrix[r2][c1])
}
}
//fmt.Println(x)
return x
}