Paradoxis
Paradoxis

Reputation: 4708

crypt(3) causing segmentation fault

I am trying to make a small program that opens a file, reads every line, hashes that line using the crypt(3) algorithm, and then write that back to an output file.

However, whenever I try using the crypt() method, it causes a segment fault. Could anyone tell me what I'm doing wrong? Thank you.

Command I'm using to compile the code:

g++ hasher.cpp -o hasher -lcrypt

My code:

#include <iostream> // User I/O
#include <fstream>  // File I/O
#include <vector>   // String array
#include <cstdlib>  // Exit method
#include <crypt.h>  // Crypt(3)

// Input & Output file names
std::string input_file;
std::string output_file;

// Plaintext & Hashed passwords
std::vector<std::string> passwords;


// Read input and output files
void read_file_names()
{

    std::cout << "Input:  ";
    std::getline(std::cin, input_file);

    std::cout << "Output: ";
    std::getline(std::cin, output_file);
}

// Load passwords from input file
void load_passwords()
{
    // Line / Hash declarations
    std::string line;
    std::string hash;

    // Declare files
    std::ifstream f_input;
    std::ifstream f_output;

    // Open files
    f_input.open(input_file.c_str());


    // Check if file can be opened
    if (!f_input) {
        std::cout << "Failed to open " << input_file << " for reading." << std::endl;
        std::exit(1);
    }

    // Read all lines from file
    while(getline(f_input, line))
    {
        // This line causes a segmentation fault
        // I have no idea why
        hash = crypt(line.c_str(), "");
        std::cout << "Hashed [" << hash << "] " << line << std::endl;
    }
}

// Main entry point of the app
int main()
{
    read_file_names();
    load_passwords();
    return 0;
}

Upvotes: 0

Views: 253

Answers (1)

MerajA
MerajA

Reputation: 194

The second parameter to the call to crypt() (the salt) takes a string. You should pass a string having a minimum of 2 characters for it to work on (as in the manual). eg: crypt(line.c_str(), "Any string here");

Upvotes: 1

Related Questions