Skip to content

Instantly share code, notes, and snippets.

@boltronics
Last active August 29, 2015 14:20
Show Gist options
  • Save boltronics/4c5bdf4a8e848c9897b8 to your computer and use it in GitHub Desktop.
Save boltronics/4c5bdf4a8e848c9897b8 to your computer and use it in GitHub Desktop.
Make Me A Password
#!/usr/bin/env bash
#
# Copyright (C) 2012-2014 Jason A. Donenfeld <Jason@zx2c4.com>
# Copyright (C) 2015 SitePoint Pty Ltd.
#
# This file is licensed under the GPLv2+.
#
# Make Me A Password
#
# Generate a random password and copy it to the clipboard. Some code
# lifted from pass, "the standard unix password manager".
#
declare -r password="$(apg -n 1 -d -a 1 -m ${1-64} -x ${2-90})"
declare -ri clip_time=45
declare sleep_argv0
declare before
declare now
declare copy_cmd
declare copy_cmd_args
declare paste_cmd
declare paste_cmd_args
function check_cmd()
{
if ! which "${1}" >/dev/null
then
echo "Error: '${1}' not found in path." 1>&2
exit 1
fi
}
if [[ "${OSTYPE}" == "darwin"* ]]
then
copy_cmd="pbcopy"
copy_cmd_args=""
paste_cmd="pbpaste"
paste_cmd_args=""
else
copy_cmd="xclip"
copy_cmd_args="-selection clipboard"
paste_cmd="xclip"
paste_cmd_args="-o -selection clipboard"
fi
check_cmd apg
check_cmd "${copy_cmd}"
check_cmd "${paste_cmd}"
# This base64 business is because bash cannot store binary data in a shell
# variable. Specifically, it cannot store nulls nor (non-trivally) store
# trailing new lines.
sleep_argv0="password store sleep on display $DISPLAY"
pkill -f "^$sleep_argv0" 2>/dev/null && sleep 0.5
before="$(${paste_cmd} ${paste_cmd_args} 2>/dev/null | base64)"
echo -n "${password}" | ${copy_cmd} ${copy_cmd_args} || \
die "Error: Could not copy data to the clipboard"
(
( exec -a "$sleep_argv0" sleep "${clip_time}" )
now="$(${paste_cmd} ${paste_cmd_args} | base64)"
[[ $now != $(echo -n "${password}" | base64) ]] && before="$now"
echo "$before" | base64 -d | ${copy_cmd} ${copy_cmd_args}
) 2>/dev/null & disown
echo -n "Generated password copied to clipboard. "
echo "Will clear in ${clip_time} seconds."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment