Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* compiles with:
- gcc -O1 -Wall -Wextra -std=c99 -lssl -lcrypto -lcrypt mkpasswd.c -o mkpasswd
- On RedHat/CentOS it requires openssl-devel and gcc
- */
- #define _XOPEN_SOURCE 500
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- #include <unistd.h>
- #include <string.h>
- #include <openssl/rand.h>
- #include <openssl/err.h>
- #include <openssl/bio.h>
- #include <openssl/evp.h>
- #define MY_ENTROPY_BITS 512
- #define SALT_BITS 128
- #define CRYPT_PASS_SUFFIX "$6$"
- int b64_op(const void *in, int in_len, char *out, int out_len, int op) {
- int ret = 0;
- BIO *b64 = BIO_new(BIO_f_base64());
- BIO *bio = BIO_new(BIO_s_mem());
- BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
- BIO_push(b64, bio);
- if (!op) {
- ret = BIO_write(b64, in, in_len);
- BIO_flush(b64);
- if (ret > 0) {
- ret = BIO_read(bio, out, out_len);
- }
- } else {
- ret = BIO_write(bio, in, in_len);
- BIO_flush(bio);
- if (ret) {
- ret = BIO_read(b64, out, out_len);
- }
- }
- BIO_free(b64);
- BIO_free(bio);
- return ret;
- }
- int main() {
- uint8_t salt_bytes=SALT_BITS >> 3;
- uint8_t entropy_bytes=MY_ENTROPY_BITS >> 3;
- uint8_t salt_buffer[salt_bytes];
- uint8_t i,salt_len;
- char *gen_salt,*password,*salt;
- printf("Waiting for enough entropy to be available\n");
- int rc = RAND_load_file("/dev/random", entropy_bytes);
- if (rc != entropy_bytes) {
- printf("Error collecting random bytes\n");
- return -1;
- }
- rc = RAND_bytes(salt_buffer, salt_bytes);
- unsigned long err = ERR_get_error();
- if (rc != 1) {
- printf("Error generating salt bytes\n");
- return err;
- }
- gen_salt=(char *)calloc(salt_bytes+1,sizeof(char));
- if (!gen_salt) {
- perror("calloc");
- return 1;
- }
- rc=b64_op(salt_buffer,salt_bytes,gen_salt,salt_bytes,0);
- for (i=0;i<salt_bytes;i++)
- if ((gen_salt[i]=='+')||(gen_salt[i]=='=')) gen_salt[i]='.';
- salt_len=strlen(CRYPT_PASS_SUFFIX)+strlen(gen_salt);
- salt=(char *)calloc(salt_len+1,1);
- if (!salt) {
- perror("calloc");
- free(gen_salt);
- return 1;
- }
- snprintf(salt,salt_len,"%s%s",CRYPT_PASS_SUFFIX,salt);
- password = getpass("Enter your password: ");
- if (!password) {
- perror("getpass");
- free(gen_salt);
- free(salt);
- return 1;
- }
- char *sha512_pass=crypt(password,salt);
- free(gen_salt);
- free(salt);
- if (!sha512_pass) {
- perror("crypt");
- return 1;
- }
- printf("SHA512 password hash: %s\n",sha512_pass);
- return 0;
- }
Add Comment
Please, Sign In to add comment