c - 通过 C 中的文件使用 crypt 函数进行身份验证(段错误)

标签 c linux encryption cryptography password-encryption

我有下面的代码,我首先尝试在情况 1 中:注册一个新密码并将其写入文件,这有效,我遇到的问题是在情况 2 中:我正在尝试使用户提供密码以通过 crypt 函数对其进行加密,然后使用先前文件中的所有加密密码对其进行身份验证。但是当我编译这个时,我收到一个错误“Segmentation Fault”。在我看来,问题出在 log_password 和加密消息的转换中。任何帮助都会很棒。

#define _GNU_SOURCE
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <crypt.h>
#include <string.h>
#include <sys/stat.h>


int
main(void)
{

FILE *f=fopen("shadow.txt","a+");  

  char * line=NULL;
  unsigned long seed[2];
  char *log_password,salt[] = "$1$........";
  const char *const seedchars =
    "./0123456789ABCDEFGHIJKLMNOPQRST"
    "UVWXYZabcdefghijklmnopqrstuvwxyz";



  char *password,*pass;
  int i,ans;

  /* Generate a (not very) random seed.
     You should do it better than this... */
  seed[0] = time(NULL);
  seed[1] = getpid() ^ (seed[0] >> 14 & 0x30000);

  /* Turn it into printable characters from ‘seedchars’. */
  for (i = 0; i < 8; i++)
    salt[3+i] = seedchars[(seed[i/5] >> (i%5)*6) & 0x3f];


  printf("Press 1 for Register.\n");
  printf("Press 2 for Login.\n");
  printf("Press 3 for Exit.\n");
  scanf("%d",&ans);
  switch(ans)
  {
    case 1: 

            password = crypt(getpass("Password:"), salt);
            fprintf(f,"%s \n",password);
            printf("Succesfull Register in file\n");
            fclose(f);
            break;


    case 2: 


            fgets(pass,34,f);
            log_password =  crypt(getpass("Login Password:"), pass);
            int ok;
            ok = strcmp (log_password, pass) == 0;
            puts(ok ? "Access granted." : "Access denied.");
            return ok ? 0 : 1;
            break;

    case 3: 
            printf("Bye\n");
            exit(1);
            break;

    default: 
            printf("Try Again.\n");
            break;
  }


  return 0;
}

最佳答案

答案是我忘了分配内存...

#define pass_size 1000
 pass=calloc(pass_size,sizeof(char));

关于c - 通过 C 中的文件使用 crypt 函数进行身份验证(段错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50181038/

相关文章:

c# - 将字符串从 C# 传递到 C .dll - 获取额外字符

c# - 类型转换无法正常工作(arduino IDE)

c - 当未连接的顶点使用权重矩阵的值为 -1 时,C 中的 Dijkstra 算法

Php file_get_contents 和 curl_exec 不能处理外部文件

c - 预期为 ‘voidpc’ 但参数的类型为 ‘double’

c - 为什么即使在非规范模式下我仍然需要按 'Enter"才能让输入被读取和输出?

php - 仅从 cli 调用未定义的函数 oci_connect(在 html 中工作正常)

c# - 输入不是有效的 Base64 字符串,因为它包含一个非 base 64 字符,超过两个填充字符

c# - 加密加密数据

security - RSA 加密 AES key 的强度