How to get a random string of 32 hexadecimal digits through command line?

后端 未结 5 635
暗喜
暗喜 2021-01-31 14:00

I\'d like to put together a command that will print out a string of 32 hexadecimal digits. I\'ve got a Python script that works:

python -c \'import random ; prin         


        
相关标签:
5条回答
  • 2021-01-31 14:39

    There three ways that I know of:

    #!/bin/bash
    
    n=16 
    
    # Read n bytes from urandom (in hex):
    xxd -l "$n" -p                    /dev/urandom | tr -d " \n" ; echo
    od  -vN "$n" -An -tx1             /dev/urandom | tr -d " \n" ; echo
    hexdump -vn "$n" -e ' /1 "%02x"'  /dev/urandom ; echo
    

    Use one, comment out the other two.

    0 讨论(0)
  • 2021-01-31 14:43

    Here are a few more options, all of which have the nice property of providing an obvious and easy way to directly select the length of the output string. In all the cases below, changing the '32' to your desired string length is all you need to do.

    #works in bash and busybox, but not in ksh
    tr -dc 'A-F0-9' < /dev/urandom | head -c32
    
    #works in bash and ksh, but not in busybox
    tr -dc 'A-F0-9' < /dev/urandom | dd status=none bs=1 count=32
    
    #works in bash, ksh, AND busybox! w00t!
    tr -dc 'A-F0-9' < /dev/urandom | dd bs=1 count=32 2>/dev/null
    

    EDIT: Tested in different shells.

    0 讨论(0)
  • 2021-01-31 14:46

    If you have hexdump then:

    hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/random
    

    should do the job.

    Explanation:

    • -n 16 to consume 16 bytes of input (32 hex digits = 16 bytes).
    • 4/4 "%08X" to iterate four times, consume 4 bytes per iteration and print the corresponding 32 bits value as 8 hex digits, with leading zeros, if needed.
    • 1 "\n" to end with a single newline.

    Note: this solution uses /dev/random but it could as well use /dev/urandom. The choice between the two is a complex question and out of the scope of this answer. If you are not sure, have a look maybe at this other question.

    0 讨论(0)
  • 2021-01-31 15:03

    Try:

    xxd -u -l 16 -p /dev/urandom
    

    Example output:

    C298212CD8B55F2E193FFA16165E95E3
    

    And to convert it back to binary:

    echo -n C298212CD8B55F2E193FFA16165E95E3 | xxd -r -p
    
    0 讨论(0)
  • 2021-01-31 15:04

    If you are looking for a single command and have openssl installed, see below. Generate random 16 bytes (32 hex symbols) and encode in hex (also -base64 is supported).

    openssl rand -hex 16
    
    0 讨论(0)
提交回复
热议问题