这是我第一次用C编写代码。我对sha512有问题。结果与其他语言(php、python)不一样。
我的目标是使用 sha512 来加密字符串循环更多次。但是第一次和第二次用python或php是一样的,但是从第三次开始,就不一样了。
结果图像:
在 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/