[tpwd] Fix segfault when exactly one argument given
[tinyapps.git] / genpass.sh
blob321e419516e126521b9b23dcbdabdf6951ae91e9
1 #!/bin/sh
2 ##
3 ## Generates a random password (or some other key)
4 ## Copyright (c) 2005,2007 by Michal Nazarewicz (mina86/AT/mina86.com)
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
19 ## This is part of Tiny Applications Collection
20 ## -> http://tinyapps.sourceforge.net/
24 ## You can specify number of characters password should have as
25 ## a parameter, eg.;
26 ## ./getnpass 100
30 has_random() {
31 # shellcheck disable=SC2039
32 [ -n "$RANDOM" ] && [ "$RANDOM" -ne "$RANDOM" ]
36 if [ -r /dev/urandom ]; then
37 gen_stream () {
38 head -c 40 /dev/urandom
40 elif [ -r /dev/random ]; then
41 gen_stream () {
42 head -c 40 /dev/random
44 elif has_random; then
45 # shellcheck disable=SC2120
46 gen_stream () {
47 set -- 10
48 while [ "$1" -gt 0 ]; do
49 # shellcheck disable=SC2039
50 printf %04x "$RANDOM"
51 set -- $(( $1 - 1 ))
52 done
54 else
55 printf "%s: unable to collect random data\n" "${0##*/}" >&2
56 exit 1
60 got_command () { test -n "$(which "$1" 2>/dev/null)"; }
62 if got_command uuencode; then
63 gen_pass () {
64 printf %s "$(uuencode -m pass | tail -n +2 | head -n 1)"
66 elif got_command md5sum; then
67 gen_pass () {
68 P1=$(head -c 32 | md5sum | cut -c1-32)
69 P2=$(head -c 32 | md5sum | cut -c1-32)
70 printf %s "$P1" "$P2"
72 elif got_command sha1sum; then
73 gen_pass () {
74 P1=$(head -c 32 | sha1sum | cut -c1-32)
75 P2=$(head -c 32 | sha1sum | cut -c1-32)
76 printf %s "$P1" "$P2"
78 else
79 printf "%s: unable to generate random password\n" "${0##*/}" >&2
80 exit 1
85 len=${1:-64}
86 if [ "$len" -gt 0 ]; then
87 l=$len
88 while [ "$l" -gt 0 ]; do
89 # shellcheck disable=SC2119
90 gen_stream | gen_pass
91 l=$(( l - 64 ))
92 done | cut -c "1-$len"