Home > Net >  Trying to convert unsigned int array to unsigned char array but get a weird output
Trying to convert unsigned int array to unsigned char array but get a weird output

Time:05-29

#include <iostream>
#include "cryptography.h"
#include "database.h"
#include <fstream>
#include <vector>
#include <cstring>

// Master key = 0x648821

std::string encrypt(std::string str, int key) {
    for (int i = 0; i < str.length(); i  ) {
        str[i]  = key;
    }
    return str;
}

std::string decrypt(std::string str, int key, int arraysize) {
    for (int i = 0; i < arraysize; i  ) {
        str[i] -= key;
    }
    return str;
}

int main() {
    std::vector<std::string> data = readFile("keys.txt");
    unsigned char key[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
    unsigned int temp[16];
    
    for (int i = 0; i < 16; i  ) {
        temp[i] = stoi(decrypt(data[i], 0x648821, 16));
        key[i] = temp[i];
        std::cout << key[i] << std::endl;
    }
}

I'm trying to get this code to output an unsigned char array of numbers used for keys in an AES128 encryption algorithm but it instead outputs a bunch of weird unicode characters (I'm using replit).

CodePudding user response:

Casts your key[i] into an int to prevent char to be printed as.. a char.

std::cout << (int)key[i] << std::endl;

or in a strict c syntax:

std::cout << static_cast<int>(key[i]) << std::endl;

CodePudding user response:

std::string encrypt(std::string str, int key) {
    ...
    str[i]  = key;

std::string is std::basic_string<char> so str[i] is a char. That can be either signed or unsigned. For signed char adding 0x648821 results in an int that then gets assigned to char causing integral conversion:

If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is implementation-defined (until C 20) the unique value of the destination type equal to the source value modulo 2^n.

So unless you add -std=c 20 or equivalent option you have to look up the compiler specifications of what that code means. Is that actually what you want to encrypt something?

I think it's worse in decrypt with unsigned char causing an integer underflow. But I'm too lazy to look at the integer promotion rules step by step to see if that is truly the case. So decrypt could be UB and not just IDB.

Debug your code and check that decrypt actually returns a sensible string that stoi() can understand. And then remove temp. Storing the value in an int array temporarily makes 0 difference, just assign the value to key directly.

  •  Tags:  
  • c
  • Related