github.com/rumhocker/blockbook@v0.3.2/build/scripts/rpcauth.py (about)

     1  #!/usr/bin/env python3
     2  # Copyright (c) 2015-2018 The Bitcoin Core developers
     3  # Distributed under the MIT software license, see the accompanying
     4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
     5  
     6  import sys
     7  import os
     8  from random import SystemRandom
     9  import base64
    10  import hmac
    11  
    12  def generate_salt():
    13      # This uses os.urandom() underneath
    14      cryptogen = SystemRandom()
    15  
    16      # Create 16 byte hex salt
    17      salt_sequence = [cryptogen.randrange(256) for _ in range(16)]
    18      return ''.join([format(r, 'x') for r in salt_sequence])
    19  
    20  def generate_password():
    21      """Create 32 byte b64 password"""
    22      return base64.urlsafe_b64encode(os.urandom(32)).decode('utf-8')
    23  
    24  def password_to_hmac(salt, password):
    25      m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), 'SHA256')
    26      return m.hexdigest()
    27  
    28  def main():
    29      if len(sys.argv) < 2:
    30          sys.stderr.write('Please include username (and an optional password, will generate one if not provided) as an argument.\n')
    31          sys.exit(0)
    32  
    33      username = sys.argv[1]
    34  
    35      salt = generate_salt()
    36      if len(sys.argv) > 2:
    37          password = sys.argv[2]
    38      else:
    39          password = generate_password()
    40      password_hmac = password_to_hmac(salt, password)
    41  
    42      print('String to be appended to bitcoin.conf:')
    43      print('rpcauth={0}:{1}${2}'.format(username, salt, password_hmac))
    44      print('Your password:\n{0}'.format(password))
    45  
    46  if __name__ == '__main__':
    47      main()