C++ version by RSpliet :
#include <string> #include <iostream> using namespace std; class crypt { private: void SwapCharacter(string &csString, int iPosA, int iPosB) { char ch1 = csString[iPosA]; char ch2 = csString[iPosB]; csString[iPosA] = ch2; csString[iPosB] = ch1; } int GetNextReturn(int iInitialIndex) { int num; do { ++iInitialIndex; num = 2; while (num < iInitialIndex && iInitialIndex % num != 0) ++num; } while (num != iInitialIndex); return iInitialIndex; } int GetPrimaryIndex(int iIndex) { int iInitialIndex = 1; for (int index = 1; index < iIndex; ++index) iInitialIndex = GetNextReturn(iInitialIndex); return iInitialIndex; } public: string Decrypt(string csString) { for (int index = csString.length() - 1; index >= 0; --index) { int iPosB = index; int iPosA = GetPrimaryIndex(index + 3) % csString.length(); SwapCharacter(csString, iPosA, iPosB); } return csString; } string Encrypt(string csString) { for (int index = 0; index < csString.length(); index++) { int iPosB = index; int iPosA = GetPrimaryIndex(index + 3) % csString.length(); SwapCharacter(csString, iPosA, iPosB); } return csString; } }; int main(int argc, char **argv) { crypt C; string cs = C.Encrypt("piehole"); string ds = C.Decrypt(cs); cout << cs << endl; cout << ds << endl; return 0; }
Go version by mrngm :
package main import ( "fmt" ) func Encrypt(s string) string { encLen := len(s) encBytes := []byte(s) for i := 0; i < encLen; i++ { oidx := offsetIndex(i + 3) newpos := oidx % encLen // fmt.Printf("i: %d (oidx: %d), newpos: %d\n", i, oidx, newpos) encBytes[newpos], encBytes[i] = encBytes[i], encBytes[newpos] } return string(encBytes) } func Decrypt(s string) string { decLen := len(s) decBytes := []byte(s) for i := decLen - 1; i >= 0; i-- { oidx := offsetIndex(i + 3) newpos := oidx % decLen // fmt.Printf("i: %d (oidx: %d), newpos: %d\n", i, oidx, newpos) decBytes[newpos], decBytes[i] = decBytes[i], decBytes[newpos]