-1

我找不到在 C 中使用“SHA-512”加密字符串的示例。有人可以帮助我提供一些代码或链接。先感谢您。

4

3 回答 3

15

SHA-512 is not an encryption algorithm, it is a cryptographic hash, which is completely different.

One library you can use to perform SHA hashes is OpenSSL. Here's an example of computing the raw SHA-512 hash of some data with OpenSSL:

#include <openssl/sha.h>
...
char data[] = "data to hash";
char hash[SHA512_DIGEST_LENGTH];
SHA512(data, sizeof(data) - 1, hash);

// 'hash' now contains the raw 64-byte binary hash.  If you want to print it out
// in a human-readable format, you'll need to convert it to hex, e.g.
于 2013-07-03T19:55:14.240 回答
7

如果您想使用 SHA-512 存储密码,请考虑使用“salt”值来使彩虹表攻击更加困难。例如,“12345678”将是一个随机字符串。“$6$” 标记 SHA-512:

#include <crypt.h>
#include <stdio.h>

int main() {
    char *hash = crypt("secret", "$6$12345678$");
    printf("hashed=%s\n", hash);
}
于 2013-07-05T08:19:22.443 回答
6

您可以使用 GLib,注意 G_CHECKSUM_SHA512,它可能需要您安装更新版本的 GLib,请访问:https ://developer.gnome.org/glib/stable/glib-Data-Checksums.html

#include <glib.h>
#include <string.h>

int
main(void)
{
        char   *string  = "Hello World";
        gchar  *sha512;

        sha512 = g_compute_checksum_for_string(G_CHECKSUM_SHA512, string, strlen(string));
        g_print("%s\n", sha512);
        g_free(sha512);
        return 0; 
}

编译

$ gcc -o sha512 sha512.c `pkg-config --cflags --libs glib-2.0`
于 2013-07-03T19:47:35.307 回答