Skip to content

Instantly share code, notes, and snippets.

@pablotron
Created July 26, 2020 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablotron/94abcc09b5b18dfb523eb171722f1dda to your computer and use it in GitHub Desktop.
Save pablotron/94abcc09b5b18dfb523eb171722f1dda to your computer and use it in GitHub Desktop.
generate ambiguous passwords
// osiekhan-pwgen: generate password from the following set of
// characters: "S5Ii1l|!0O:;,.`'" (excluding double quotes).
//
// Pass positive integer as the first parameter to specify length
// (defaults to 64 characters if unspecified).
//
// Example:
// > cc -O3 -W -Wall -Wextra -pedantic -std=c11 -o osiekhan-pwgen{,.c}
// > ./osiekhan-pwgen
// l||!.O';:;;i,51'S!:S..l;1S'0O`,.I'5'S,!,;SI`!Oil'S:llO;i:5!5lS5l
//
#include <unistd.h>
#include <stdio.h> // fputs()
#include <stdlib.h> // EXIT_SUCCESS
#include <stdint.h> // uint8_t
#include <string.h> // atoi()
#include <err.h> // err()
// alphabet (length must be power of two)
const char A[] =
"S5Ii1l|!0O:;,.`'";
// subtract two to exclude trailing null and get mask
#define AM (sizeof(A) - 2)
static void get_random_bytes(uint8_t * const dst, const size_t len) {
// open /dev/urandom
FILE *fh = fopen("/dev/urandom", "rb");
if (!fh) {
err(EXIT_FAILURE, "fopen()");
}
// read bytes
if (!fread(dst, len, 1, fh)) {
err(EXIT_FAILURE, "fread()");
}
// close handle
fclose(fh);
}
int main(int argc, char *argv[]) {
const int len = (argc > 1) ? atoi(argv[1]) : 64;
if (len < 1) {
errx(EXIT_FAILURE, "len < 1");
}
// alloc source buffer
uint8_t * const src = malloc(len);
if (!src) {
err(EXIT_FAILURE, "src malloc()");
}
// alloc destination buffer
char * const dst = malloc(len + 1);
if (!dst) {
err(EXIT_FAILURE, "dst malloc()");
}
// fill src buf with random bytes
get_random_bytes(src, len);
// fill dst buf
for (int i = 0; i < len; i++) {
dst[i] = A[src[i] & AM];
}
dst[len] = '\0';
fputs(dst, stdout);
fputc('\n', stdout);
// return success
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment