php - C 中的 sha512 哈希结果与其他语言(php、python)不同

标签 php c sha512

这是我第一次用C编写代码。我对sha512有问题。结果与其他语言(php、python)不一样。

我的目标是使用 sha512 来加密字符串循环更多次。但是第一次和第二次用python或php是一样的,但是从第三次开始,就不一样了。

结果图像: enter image description here

在 Linux 上运行。

这是我的代码:

C

$ gcc test.c -lcrypto -o test

$ ./test

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

char *hash_sha512(char *data) {
  SHA512_CTX ctx;
  char *md = malloc(sizeof(char)*(SHA512_DIGEST_LENGTH+1));
  SHA512_Init(&ctx);
  SHA512_Update(&ctx, data, strlen(data));
  SHA512_Final(md, &ctx);
  md[SHA512_DIGEST_LENGTH] = '\0';

  return md;
}

int main(void) {

  char *str = hash_sha512("123456");
  FILE *fp;
  int count = 10;

  fp = fopen("/tmp/c.txt", "w+");
  do {
    fputs(str, fp);
    fputs("\n", fp);
    str = hash_sha512(str);
  } while (--count);

  fclose(fp);

  return 0;
}

PHP

<?php
$password='123456';
$hash = hash('sha512', $password, TRUE);
$i = 10;
do {
  file_put_contents('/tmp/php.txt',$hash . "\n", FILE_APPEND);
  $hash = hash('sha512', $hash, TRUE);
} while (--$i);

Python

#! /usr/bin/env python

import hashlib
password='123456'
count = 10
f = open('/tmp/python.txt','a')
pass_hash = hashlib.sha512(password).digest()
for _ in range(count):
    f.write(pass_hash)
    pass_hash = hashlib.sha512(pass_hash).digest()
f.close()

最佳答案

感谢@WhozCraig。

这是我的最终代码。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

int main(void) {
  char pwd[] = "123456";
  unsigned char digest[2][SHA512_DIGEST_LENGTH] = {{0}};
  SHA512((unsigned char*)pwd, strlen(pwd), digest[0]);

  unsigned int count = 1;
  for (; count<10; ++count) {
    SHA512(digest[(count-1)%2], SHA512_DIGEST_LENGTH, digest[count%2]);
  }

  unsigned char result[SHA512_DIGEST_LENGTH * 2 + 1];
  unsigned int i = 0;
  for(; i < SHA512_DIGEST_LENGTH; i++) {
    sprintf(&result[i*2], "%02x", digest[(count-1)%2][i]);
  }
  printf("The result is %s.\n", result);

  return 0;
}

关于php - C 中的 sha512 哈希结果与其他语言(php、python)不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29205608/

相关文章:

php - 简单的 PHP isset 测试

c++ - 知道为什么下面的代码片段打印 2 而不是 3

c - 带有字符类的 fscanf

c - C语言的MasterMind游戏

c++ - 使用 Crypto++ Base64 编码器时避免换行

java - RSA - 在 Android 中加密/在 PHP 中解密

php - 打印到纸上选择的数据

基于选定/默认下拉列表的 Php 查询并在同一页面上输出

带有加盐的 Java Sha-512 消息摘要不匹配 linux 影子文件散列密码

hash - sha512 可以保护您免受极其简单的密码的侵害吗?