exiqe
exiqe

Reputation: 11

String to unsigned char

How do I make myself enter data into a string through cin, and not in program code ("message," "pwd")?

I need to make a transformation from string to unsigned char, but I don't know how. The code itself is an attempt to implement RC4

#include <iostream>
#include <string.h>
using namespace std;

void rc4(unsigned char * ByteInput, unsigned char * pwd,
           unsigned char * &ByteOutput){
    unsigned char * temp;
    int i,j=0,t,tmp,tmp2,s[256], k[256];
    for (tmp=0;tmp<256;tmp++){
        s[tmp]=tmp;
        k[tmp]=pwd[(tmp % strlen((char *)pwd))];
    }
        for (i=0;i<256;i++){
        j = (j + s[i] + k[i]) % 256;
        tmp=s[i];
        s[i]=s[j];
        s[j]=tmp;
    }
temp = new unsigned char [ (int)strlen((char *)ByteInput)  + 1 ] ;
    i=j=0;
    for (tmp=0;tmp<(int)strlen((char *)ByteInput);tmp++){
        i = (i + 1) % 256;
        j = (j + s[i]) % 256;
        tmp2=s[i];
        s[i]=s[j];
        s[j]=tmp2;
        t = (s[i] + s[j]) % 256;
if (s[t]==ByteInput[tmp])
    temp[tmp]=ByteInput[tmp];
else
    temp[tmp]=s[t]^ByteInput[tmp];
    }
temp[tmp]='\0';
ByteOutput=temp;
}

int main()
{
    unsigned char * message;
    unsigned char * pwd;
    unsigned char * encrypted;
    unsigned char * decrypted;
    message=(unsigned char *)"Hello world!";
    pwd=(unsigned char *)"abc";
    rc4(message,pwd,encrypted);
    rc4(encrypted,pwd,decrypted);
    cout<<"Test"<<endl<<endl;
    cout<<"Message: "<<message<<endl;
    cout<<"Password: "<<pwd<<endl;
    cout<<"Message encrypted: "<<encrypted<<endl;
    cout<<"Message decrypted: "<<decrypted<<endl;
    return 0;
}

Upvotes: 0

Views: 520

Answers (1)

Waqar
Waqar

Reputation: 9331

std::string has a .c_str() member function which returns const char * to the internal string. You can use reinterpret_cast to cast that to const unsigned char*. Example:

#include <string> // string not string.h

std::string message;
std::getline (std::cin, message);

const unsigned char* msg = reinterpret_cast<const unsigned char*>(message.c_str());

Upvotes: 1

Related Questions