You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.6 KiB
Bash

#!/usr/bin/env bash
# grab parameters, trim whitespaces
length="${*// }";
# look for easy mode "-e"
if [[ "$length" =~ ^-e$ ]]; then
passw=$(cat /dev/urandom | tr -cd 'a-z0-9' | head -c 32);
echo $passw | tr -d '\n' | xclip -selection c;
echo $passw
exit 0
elif [[ "$length" =~ ^-e=([0-9]+)$ ]]; then
# get length from regex
len=${BASH_REMATCH[1]};
passw=$(cat /dev/urandom | tr -cd 'a-z0-9' | head -c "$len");
echo $passw | tr -d '\n' | xclip -selection c;
echo $passw
exit 0
# look for -b=bytes
elif [[ "$length" =~ ^-b=([0-9]+)$ ]]; then
# set bytes
bytes=${BASH_REMATCH[1]};
# set length
let length=4*bytes/3+1;
# instead of ceiling the function, we just floor it and add 1, because the output length was specified in bytes
else
if [[ -z "$length" ]]; then
# if no parameters were given, the default is used
length=32
bytes=24
else
if ! [[ "$length" =~ ^[0-9]+$ ]]; then
echo -e "\e[91mError: '$length' is not a number!\e[0m";
exit 100;
fi
# calculate the bytes from the length
let bytes=30*length/4;
# ceil the result using python
bytes=$(python -c "from math import ceil; print ceil($bytes/10.0)" | tr -d '.0');
fi
fi
# generate the password
password=$(dd if=/dev/urandom bs=1 count="$bytes" 2>/dev/null | base64);
# idk why but they keep adding a newline after every 76th character, compensate for that!
let length=length+length/77;
# cut it and echo it
echo "${password:0:$length}" | tr -d '\n';
# we removed the newlines from the middle of the password adn from the end, add the one at the end back
echo "";
# copy the password to clipboard
echo "${password:0:$length}" | tr -d '\n' | xclip -selection c;
exit 0;