Skip to content

Instantly share code, notes, and snippets.

@OdyX
Created April 1, 2020 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OdyX/1513aacee2ca010dcf954d62af776469 to your computer and use it in GitHub Desktop.
Save OdyX/1513aacee2ca010dcf954d62af776469 to your computer and use it in GitHub Desktop.
Solr: Compute a valid BasicAuth string for a given password. Python reimplementation of org.apache.solr.security.Sha256AuthenticationProvider.getSaltedHashedValue
#!/usr/bin/env python3
from base64 import b64encode, b64decode
from hashlib import sha256
from os import urandom
from sys import argv
def solrBasicAuthHash(password: str, salt: bytes):
"""
Python translation of
https://github.com/apache/lucene-solr/blob/master/solr/core/src/java/org/apache/solr/security/Sha256AuthenticationProvider.java#L112
"""
# Compute the SHA256 of (salt+password)
m = sha256()
m.update(salt)
m.update(password.encode("utf-8"))
# Compute the SHA256 of the previous
# The solr hash is in fact sha256(sha256(salt+password))
return sha256(m.digest()).digest()
def solrBasicAuthString(password: str, salt: bytes):
"""
Return the full hash + salt as solr expects it
"""
hashed = solrBasicAuthHash(password, salt)
b64hashed = b64encode(hashed)
b64salt = b64encode(salt)
return f"{str(b64hashed, 'ascii')} {str(b64salt, 'ascii')}"
def genSolrBasicAuth(password: str, saltlength: int = 32):
salt = urandom(saltlength)
return solrBasicAuthString(password, salt)
# From the solr documentation: test the SolrRocks password
# Given this password / salt combination
password = "SolrRocks"
salt = b"5\xd7{,\xab\xd5\x04\x06\x99 ]\x10\x01X\xb5z@\x9f\x00\x95\xeb\xd4a\x9f.\xd4T^\x18+\x17\xc7"
# Test that the salt gives what we expect once base64-encoded
b64salt = b64encode(salt)
assert b64salt == b"Ndd7LKvVBAaZIF0QAVi1ekCfAJXr1GGfLtRUXhgrF8c=", b64salt
# Hash the password "solr-style"
hashed = solrBasicAuthHash(password, salt)
b64hashed = b64encode(hashed)
assert b64hashed == b"IV0EHq1OnNrj6gvRCwvFwTrZ1+z1oBbnQdiVC3otuq0=", b64hashed
# Compute the full solr BasicAuth String for that pair
basicAuthString = solrBasicAuthString(password, salt)
assert (
basicAuthString
== "IV0EHq1OnNrj6gvRCwvFwTrZ1+z1oBbnQdiVC3otuq0= Ndd7LKvVBAaZIF0QAVi1ekCfAJXr1GGfLtRUXhgrF8c="
), basicAuthString
assert len(argv) == 2
print(genSolrBasicAuth(argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment