jakubjosef
12/2/2016 - 11:03 AM

Jenkins password hashing & encoding

Jenkins password hashing & encoding

import bcrypt
import math
import re
import sys
import base64
from hashlib import sha256
from Crypto.Cipher import AES

MAGIC = "::::MAGIC::::"


def hash_password(password):
    if isinstance(password, str):
        return bcrypt.hashpw(password, bcrypt.gensalt(prefix=b"2a"))


def encode_password(password):
    master_key = open(sys.argv[1]).read()
    hudson_secret_key = open(sys.argv[2], 'rb').read()
    hashed_master_key = sha256(master_key).digest()[:16]
    o = AES.new(hashed_master_key, AES.MODE_ECB)
    x = o.decrypt(hudson_secret_key)
    assert MAGIC in x

    k = x[:-16]
    k = k[:16]
    target_length = int(math.ceil(float(len(password + MAGIC)) / 16) * 16)
    password_extended = password + MAGIC + "".join(
        [chr(11) for i in range(0, target_length - len(password + MAGIC))])
    o = AES.new(k, AES.MODE_ECB)
    x = o.encrypt(password_extended)
    return base64.encodestring(x)


def decode_password(encoded_password):
    master_key = open(sys.argv[1]).read()
    hudson_secret_key = open(sys.argv[2], 'rb').read()
    hashed_master_key = sha256(master_key).digest()[:16]
    o = AES.new(hashed_master_key, AES.MODE_ECB)
    x = o.decrypt(hudson_secret_key)
    assert MAGIC in x

    k = x[:-16]
    k = k[:16]
    p = base64.decodestring(encoded_password)
    o = AES.new(k, AES.MODE_ECB)
    x = o.decrypt(p)
    assert MAGIC in x
    return re.findall('(.*)' + MAGIC, x)[0]