Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash substring weirdness

Tags:

substring

bash

Here is a fragment of a password generator:

# ...
ascstring='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHILKLMNOPQRSTUVWXYZ!#$%&()*+-;   <=>?@^_`{|}~'
asclen=${#ascstring} # modulo ascstring
#...
r=$(openssl rand 100000 | sha1sum) # generates 40 hex sequence
#...
for i in {0..38..2}
do
    v=${r:i:2} ; echo -n ${ascstring:$[ 0x$v % $asclen]:1}
done
echo
# ...

It uses various definitions of ascstring but the one shown causes a problem occasionally. Mostly it's okay:

$ ./password-gen.sh 
`?OCw&a|746|SRm8b&c=

$ ./password-gen.sh 
eE?R%3NdUjSpd<)wPuBV

$ ./password-gen.sh 
0X8)p8hPobt$x@iGy?!I

$ ./password-gen.sh 
P7LD;p<^lX1d87;{V4S$

But occasionally:

$ ./password-gen.sh 
5w@$ypassword-gen.sh@)A|l`06B(50f7

If I remove the * from ascstring this never seems to happen. I wonder what's going on and how I can get around this problem (without reducing the entropy)?

Thanks.

like image 318
Thorsen Avatar asked Jul 12 '26 02:07

Thorsen


1 Answers

You should quote the string to echo:

...
echo -n "${ascstring:$[ 0x$v % $asclen]:1}"
like image 139
Xiè Jìléi Avatar answered Jul 14 '26 21:07

Xiè Jìléi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!