Function to do decryption - c++

I need help with function string decryptedpassword() which is a part of a program to decrypt a password. I have to utilize const VOWELS to identify presence of vowels and insert 0 before and e after each vowel dynamically.
The main goal of program is to make an authentication system that begin with some initial arguments containing his or her credentials to be validated by the program.
These arguments are stated in the command line and should consist of two values, one for username and the other for password. Fortunately, the client has already specified that Kalle will use the following credentials:
Username: Kalle
Password: bAnanASplit
These arguments are passed to main(..) which in turn hands them over to mainArgumentsParser(..), a function devoted to the process of parsing out values. You are free to study how this is done but may not modify any of the code you find in these functions. The parser will return a string value containing user
credentials in the form username,password, or simply ”fail” to inform main(..) that too few arguments were provided.
The string of credentials are then passed to authenticateUser(..) which will need to separate the username from password and store them in separate strings. As can be seen in the function definition, there already exists two string constants.
const string USERNAME = "Kalle";
const string PASSWORD = "i0J0u0j0u0J0Zys0r0{";
#include "Prototypes.h"
using std::string;
using std::stringstream;
using std::cout;
using std::endl;
// If argument less than 3 so print fail.
string mainArgumentParser(int argc, char* argv[]) {
if (argc < 3)
return "fail";
std::stringstream ss;
ss << argv[1] << "," << argv[2];
return ss.str();
}
//bool function to separate username and password and validate them.
bool authenticateUser(string value)
{
const string USERNAME = "Kalle";
const string PASSWORD = "i0J0u0j0u0J0Zys0r0{";
bool authPassed = false;
string username = value.substr(0, 5);
size_t pos = value.find(",");
string pass = value.substr(pos + 1);
if (username == USERNAME && decryptPassword(pass) == PASSWORD )
{
authPassed = true;
}
return authPassed;
}
// bool to detremine if the number is even or not.
bool even(int x)
{
return x % 2 == 0;
}
//function to decrypt the paasword and return the result to validate the authentication.
string decryptPassword(string password)
{
const int ROT7 = 7, ROT9 = 9;
const string VOWELS = "AEIOUYaeiouy";
string decryptedpass;
for (size_t i = 0; i < password.length(); i++) {
if (even(i)) {
decryptedpass += password[i] + ROT7;
}
else {
decryptedpass += password[i] + ROT9;
}
decryptedpass += '0';
}
return decryptedpass;
}

Related

How to access variable from class array object in function?

I am creating a Meet In The Middle cryptanalysis way to find the keys for a double caesar cipher.
I created a class Table where it holds each 26 possibilites of the cipher text along with the associated key used to get the cipher text.
Next I have a function findKeyPair that takes the second encrypted plain text and decrypts testing each key and searches the class table array object I made for matching cipher text. If there is a match the findKeyPair function sets a 2 element array keySolutions with the first element being the first key and the second element being the second key.
Then it should display the 2 keys used in the double caesar cipher.
The problem I am having is in the findKeyPair function. Whenever I use my getText() and getKey() function in findKeyPair the data returned seems blank. I have tried passing the point and by reference, but it is already an array so I don't understand where the problem is coming from.
This is my project so far, so if you want to run it you can:
`
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
class Table {
private:
string cipherText;
int key_l;
public:
Table() : cipherText(""), key_l(0) {}
void putEntry(string plainText, int key);
string getText();
int getKey();
void printEntry();
};
string caesarCipher(string plainText, int key);
void findKeyPair(Table table[], string cipherText, int keySolutions[]);
int main()
{
Table table[26];
int keySolutions[2] = {0,0};
string knownPlainText = "Hello World";
int key1 = 4; int key2 = 13;
string cipherText = caesarCipher(knownPlainText, key1);
cipherText = caesarCipher(cipherText, key2);
findKeyPair(table, cipherText, keySolutions);
cout << "Key 1 = " << keySolutions[0] << "\nKey 2 = " << keySolutions[1] << endl;
return 0;
}
string caesarCipher(string plainText, int key)
{
string result = "";
for (int i = 0; i < plainText.length(); i++) {
if (plainText[i] == 32)
result += char(plainText[i]);
else if (isupper(plainText[i]))
result += char(int(plainText[i] + key - 65) % 26 + 65);
else
result += char(int(plainText[i] + key - 97) % 26 + 97);
}
return result;
}
void findKeyPair(Table table[], string cipherText, int keySolutions[])
{
string middleText = "";
string temp = "";
int key = 0;
for (int i = 0; i < 26; i++)
{
key = 26 - i;
middleText = caesarCipher(cipherText, key);
for (int j = 0; j < 26; j++)
{
temp = table[j].getText();
if (middleText.compare(temp) == 0)
{
keySolutions[0] = table[j].getKey();
keySolutions[1] = key;
}
}
}
}
void Table::putEntry(string plainText, int key)
{
cipherText = caesarCipher(plainText, key);
key_l = key;
}
string Table::getText()
{
return cipherText;
}
int Table::getKey()
{
return key_l;
}
void Table::printEntry()
{
cout << cipherText << endl;
}
`
I have tryed passing the Table table object array to the findKeyPair function by reference and the pointer. But no matter what the findKeyPair function can't access cipherText from the class Table when I use getText() function.

Returning cstring from function

Need to use cstrings for an assignment, so bear with me as I'm new to the concept.
The purpose of the assignment is to enter a password into a function, validate it against some criteria, then reverse the password and validate it again. There are three functions in total: one to get the password from the user, one for validation, and one to reverse what was entered.
Note: during the validation, each criteria not met has to be addressed in the invalid message returned to main.
Main:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <cctype>
#include <string>
using namespace std;
char* Get_Pass(char p_word[]);
char* Valid_Pass(char p_word[]);
//char* Reverse_Pass(char p_word[]);
int main()
{
const int SIZE = 31;
char password[SIZE];
char* rtn_stg = new char[SIZE];
char* rtn_ptr;
rtn_stg = Get_Pass(password);
rtn_ptr = rtn_stg;
cout << Valid_Pass(rtn_stg);
//cout << Reverse_Pass(rtn_string, SIZE);
delete[] rtn_ptr;
cout << "\n\n";
system("pause");
return 0;
}
The issue I'm experiencing is twofold; the first function works fine. If I disabled everything else and sent the result back to main, it would print what I entered. It's when passing the password into the second function for validation where it outputs garbage code, along with the message for the unmet criteria, for example:
"Enter password for verification: hello
════════════════════════════════════════════════════════════════════════════════
═══════════════════════════════════════════════²²²²▌▌▌▌▌·ò=uYPassword must be si
x characters long. Password must contain one digit."
Here's the function in question:
char* Valid_Pass(char p_word[])
{
int char_count = 0, digi_count = 0, up_count = 0, low_count = 0, index = 0;
char mess_1[] = "Password must be six characters long. ";
char mess_2[] = "Password must contain one digit. ";
char mess_3[] = "Password must contain one upper and lower case letter. ";
char mess_4[] = "Password valid.";
const int SIZE = strlen(mess_1) + strlen(mess_2) + strlen(mess_3) + 1;
char* out_message = new char[SIZE];
while (p_word[index] != '\0')
{
if (isalpha(p_word[index]))
char_count++;
if (isdigit(p_word[index]))
digi_count++;
if (isupper(p_word[index]))
up_count++;
if (islower(p_word[index]))
low_count++;
index++;
}
if (index < 6)
strcat(out_message, mess_1);
if (digi_count < 1)
strcat(out_message, mess_2);
if (up_count < 1 && low_count < 1)
strcat(out_message, mess_3);
//if(index )
//out_message = mess_4;
return out_message;
}
On top of that, upon execution, it triggers a break point at the "delete[] rtn_ptr".
Any insight into this would be appreciated. Like I said above, I'm new to cstrings and couldn't find an solution on here that addressed the problems I'm experiencing.
Thanks!
Your problem is caused by use of strcat with message_out as argument.
The arguments to strcat need to be null-terminated strings. In your case, you have allocated memory for message_out but you have not initialized it anything before the first call to strcat. As a consequence, your program has undefined behavior.
Make sure you initialize it to an empty string before using strcat.
out_message[0] = '\0';
if (index < 6)
strcat(out_message, mess_1);
if (digi_count < 1)
strcat(out_message, mess_2);
if (up_count < 1 && low_count < 1)
strcat(out_message, mess_3);

STL map<String^, String^> thismap; why wont this work?

I am attempting to write a simple login form. I want to store the list of login accounts in a STL map.
when retrieving text values from text boxes on the form. The boxes return "String^"
So what I have is:
map <String^, String^> NamePassList;
typedef pair<String^, String^> StringPair;
string line, usrName, password;
usrName = password = "";
ifstream ifs("login.in");
if (ifs.is_open()){
while (!ifs.eof()){
getline(ifs,line);
bool endofusername = false;
for (int i = 0; i < line.length(); i++){
if (line[i] == ' '){
endofusername = true;
}
if (!endofusername){
usrName += line[i];
}
else{
password += line[i];
}
}
String ^ temp1 = gcnew String(usrName.c_str());
String ^ temp2 = gcnew String(password.c_str());
NamePassList.insert(StringPair(temp1, temp2));
}
ifs.close();
}
String ^ UserName = txtUserName->Text;
String ^ Password = txtPassword->Text;
map<String^, String^>::iterator nameItor;
nameItor = NamePassList.find(UserName);
if (nameItor->first == UserName){
if (nameItor->second == Password){
MessageBox::Show("Sucsess!", "log", MessageBoxButtons::OK);
}
else
MessageBox::Show("Fail!", "log", MessageBoxButtons::OK);
}
else
{
MessageBox::Show("Fail!", "log", MessageBoxButtons::OK);
}
when compiled the error i get of from the "map class" and utility.
This seams like the best way to do it, but everything I try gives me a new error.
Any help would be great!! thanks all.
To possibly reduce some errors, try and simplify your code using std::string.
Given the option not to use the managed String type, I'd opt for std::string. Since you're using std::string already, try that type for NamePassList. Also, typedef the map. Then for inserts, use value_type.
typedef map<string, string> StringMap;
StringMap NamePassList;
to insert:
StringMap::value_type vt(usrName, password);
StringMap::_Pairib pair = NamePassList->insert(vt);
if (pair.second == false)
{
... problems... key already exists ....
}
And also for the search:
StringMap::iterator iter = NamePassList.find(UserName);
if (iter != NamePassList.end())
{
...found...
}
You don't want to "use" the iter until you know it's valid by testing against end().

c++ implementation of string matching alg

I am implementing a String matching algorithm for a username database. My method takes an existing Username database and a new username that the person wants and it checks to see if the username is taken. if it is taken the method is supposed to return the username with a number that isn't taken in the database.
Example:
"Justin","Justin1", "Justin2", "Justin3"
Enter "Justin"
return: "Justin4" since Justin and Justin with the numbers 1 thru 3 are already taken.
I have already written this code in Java, and now I am writing it in C++ for practice. I have a few problems though:
How do you compare two strings? I have tried strcmp and a few others but I always get the error message: cannot convert std::string to const char* for argument 2.
how do you concatenate an int and a string? in java it was as simple as using the + operator.
In my main function, it says there is no matching function call for Username::NewMember(std::string, std::string). why does it not recognize newMember in main?
#include<iostream>
#include<string>
using namespace std;
class Username {
public:
string newMember(string existingNames, string newName){
bool found = false;
bool match = false;
string otherName = NULL;
for(int i = 0; i < sizeof(existingNames);i++){
if(strcmp(existingNames[i], newName) == 0){
found = true;
break;
}
}
if(found){
for(int x = 1; ; x++){
match = false;
for(int i = 0; i < sizeof(existingNames);i++){
if(strcmp(existingNames[i],(newName + x)) == 0){
match = true;
break;
}
}
if(!match){
otherName = newName + x;
break;
}
}
return otherName;
}
else return newName;
}
int main(){
string *userNames = new string[4];
userNames[0] = "Justin";
userNames[1] = "Justin1";
userNames[2] = "Justin2";
userNames[3] = "Justin3";
cout << newMember(userNames, "Justin") << endl;
delete[] userNames;
return 0;
}
}
Ok, there is some mistakes in your code :
If you want to compare two strings, simply use the operator== : string == string2
If you want to append an int to a string in C++ you can use streams :
#include <sstream>
std::ostringstream oss;
oss << "Justin" << 4;
std::cout << oss.str();
You are passing a string* to the function newMember but you prototype doesn't match that :
string *userNames = new string[4];
newMember(userNames, "Justin"); // Call
string newMember(string existingNames, string newName); // Protype
I think it should be : string newMember(string* existingNames, string newName); no ?
In the example, your main function is inside you class Username. It is not correct in C/C++. Unlike Java, the main function as to be in the global scope.
Finally you should use const-reference parameter because you don't need to modify the content of them and you need to copy them either :
string newMember(string* existingNames, const string& newName);
// ^^^^^ ^
Are you sure you need something allocated dynamically in the main function ?

Need to compare certain elements of string

Been working on this program which requires the use of a function that compares a string input by the user and gives the user the opportunity to leave the characters that he/she doesn't know out of the input, replacing them with * . The input represents a license-plate of a car that has 6 characters (for instance ABC123) and the user is allowed to leave any of those characters out (for instance AB** 23 or ** C12* etc.). So the function needs to return all objects that match the characters in the right position, but it cannot return if, say, A is in the right position but any of the other characters are not. The user is, however, allowed to only enter A* * * * *, for instance, and the function should return all objects that have A in the first position.
What I did was use a function to remove all the asterisks from the input string, then create sub-strings and send them to the function as a vector.
string removeAsterisk(string &rStr)// Function to remove asterisks from the string, if any.
{
stringstream strStream;
string delimiters = "*";
size_t current;
size_t next = -1;
do
{
current = next + 1;
next = rStr.find_first_of( delimiters, current );
strStream << rStr.substr( current, next - current ) << " ";
}
while (next != string::npos);
return strStream.str();
}
int main()
{
string newLicensePlateIn;
newLicensePlateIn = removeAsterisk(licensePlateIn);
string buf; // Have a buffer string
stringstream ss(newLicensePlateIn); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
myRegister.showAllLicense(tokens);
}
The class function that receives the vector currently looks something like this:
void VehicleRegister::showAllLicense(vector<string>& tokens)//NOT FUNCTIONAL
{
cout << "\nShowing all matching vehicles: " << endl;
for (int i = 0; i < nrOfVehicles; i++)
{
if(tokens[i].compare(vehicles[i]->getLicensePlate()) == 0)
{
cout << vehicles[i]->toString() << endl;
}
}
}
If anyone understand what I'm trying to do and might have some ideas, please feel free to reply, I would appreciate any advice.
Thanks for reading this/ A.
Just iterate through the characters, comparing one at a time. If either character is an asterisk, consider that a match, otherwise compare them for equality. For example:
bool LicensePlateMatch(std::string const & lhs, std::string const & rhs)
{
assert(lhs.size() == 6);
assert(rhs.size() == 6);
for (int i=0; i<6; ++i)
{
if (lhs[i] == '*' || rhs[i] == '*')
continue;
if (lhs[i] != rhs[i])
return false;
}
return true;
}
Actually, you don't have to restrict it to 6 characters. You may want to allow for vanity plates. In that case, just ensure both strings have the same length, then iterate through all the character positions instead of hardcoding 6 in there.