I can't find an example of encrypting a string with "SHA-512" in C. Can someone help me with some code or a link. Thank you in advance.
Asked
Active
Viewed 2.0k times
-2
-
7SHA 512 is not an encryption algorithm. Rather it's used for hashing. Where are you stuck? What are you really trying to do? – Mike Dinescu Jul 03 '13 at 19:19
-
See [here](http://stackoverflow.com/questions/12772102/how-to-convert-openssl-sha-512-hash-to-gmp-number-to-use-in-rsa-encryption-metho) on SO. – kgdesouz Jul 03 '13 at 19:20
3 Answers
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.

Iharob Al Asimi
- 52,653
- 6
- 59
- 97

Adam Rosenfield
- 390,455
- 97
- 512
- 589
-
1Helpful answer! However, I think you need to do sizeof(data)-1 to exclude the terminating null character. – JustinB Feb 16 '14 at 20:53
-
2
-
7
If you want to store passwords using SHA-512, please consider using a "salt" value to make rainbow-table attacks harder. Example, "12345678" would be a random string. "$6$" marks SHA-512:
#include <crypt.h>
#include <stdio.h>
int main() {
char *hash = crypt("secret", "$6$12345678$");
printf("hashed=%s\n", hash);
}

lathspell
- 3,040
- 1
- 30
- 49
-
Thank u for the answer, i've found an SHA1 code, ans i used it, it's better than MD5 and still strong too. i will use salts values with the passwords and store the hashes in a file, only the super user can access that file. If i'm wrong correct me . – badr assa Jul 07 '13 at 00:51
-
`char *hash = crypt("secret", "$6$12345678");` This seems to be missing a '$' at the end of the salt. Format: `$6$
$ – GoinOff Oct 19 '20 at 13:31`. That is also what I've seen in many other examples. -
Thanks for pointing out, I edited the example. Both produce the same result in Linux, though. – lathspell Oct 19 '20 at 13:49
6
You can use GLib for this matter, be aware of G_CHECKSUM_SHA512, it might require you to install a newer version of GLib, visit: 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;
}
compile
$ gcc -o sha512 sha512.c `pkg-config --cflags --libs glib-2.0`

yeyo
- 2,954
- 2
- 29
- 40