问题
I'm creating a program that takes a file as input & outputs the decrypted password of each line. The file contains three lines of encrypted passwords. I am guaranteed that the passwords decrypt to 4 letter words. Given that i have created an char[] of the letters. I'm having a problem reading the file line by line using LOW LEVEL IO and putting the resulting password in a new file. Any & all advice is appreciated!
Here is my code so far:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main(void)
{
int f = open("pass.txt", O_RDONLY);
if (f < 0)
return 0;
char buf[1024];
while (my_fgets(buf, sizeof(buf), f))
printf("%s\n", buf);
close(f);
const char *const pass = "$1$6gMKIopE$I.zkP2EvrXHDmApzYoV.B.";
char *result;
int ok;
char guess[] = {'a','a','a','a','\0'};
char ch1=guess[0], ch2=guess[1], ch3=guess[2], ch4=guess[3];
do{
for(ch1; ch1<='z';++ch1)
{
for(ch2='a';ch2<='z';++ch2)
{
for(ch3='a';ch3<='z';++ch3)
{
for(ch4='a';ch4<='z';++ch4)
{
result = crypt(guess, pass);
}
}
}
}
}while(strcmp(result, pass) != 0);
puts(guess);
return 0;
}
int my_fgets(char* buf, int len, int f)
{
for (int i = 0; i < len; i++,buf++)
{
int count = read(f, buf, 1);
if (!count || (buf[0] == '\n'))
{
buf[0] = 0;
return i;
}
}
return 0;
}
Text file:
$1$6gMKIopE$I.zkP2EvrXHDmApzYoV.B.
$1$pkMKIcvE$WQfqzTNmcQr7fqsNq7K2p0
$1$0lMKIuvE$7mOnlu6RZ/cUFRBidK7PK.
回答1:
The following block of code appears to be flawed:
while (my_fgets(buf, sizeof(buf), f))
printf("%s\n", buf);
What that does is preserve only the last line. The other lines are read and discarded.
Also, it's not clear how ch1
is supposed to be initialized to in each iteration of the do ... while
loop. You have it as:
for(ch1; ch1<='z';++ch1)
// ^^^
That doesn't initialize ch1
. It's an expression with no side effects.
I suggest putting most of the logic for password decryption in a function of its own and calling the function after reading every line.
void decryptPassword(char* buf)
{
printf("%s\n", buf);
const char *const pass = "$1$6gMKIopE$I.zkP2EvrXHDmApzYoV.B.";
char *result;
int ok;
char guess[] = {'a','a','a','a','\0'};
char ch1=guess[0], ch2=guess[1], ch3=guess[2], ch4=guess[3];
do{
for(ch1; ch1<='z';++ch1)
{
for(ch2='a';ch2<='z';++ch2)
{
for(ch3='a';ch3<='z';++ch3)
{
for(ch4='a';ch4<='z';++ch4)
{
result = crypt(guess, pass);
}
}
}
}
}while(strcmp(result, pass) != 0);
puts(guess);
}
int main(void)
{
int f = open("soc.in", O_RDONLY);
if (f < 0)
return 0;
char buf[1024];
while (my_fgets(buf, sizeof(buf), f))
decryptPassword(buf);
close(f);
return 0;
}
来源:https://stackoverflow.com/questions/30609950/very-simple-crypt-program-error