Generate SHA1 THumbprint of the X509 Certificate
165571
public function getThumbprint()
    {
        $resource = openssl_x509_read($this->certificate);
        $thumbprint = null;
        $output = null;
        
        $result = openssl_x509_export($resource, $output);
        if ($result !== false) {
            $output = str_replace('-----BEGIN CERTIFICATE-----', '', $output);
            $output = str_replace('-----END CERTIFICATE-----', '', $output);
            $output = base64_decode($output);
            $thumbprint = sha1($output);
        }
        
        return $thumbprint;
    }
284789
private static @Nonnull File getFingerprintFile(@Nonnull byte[] md5sum) {
        assert md5sum.length==16;
        return new File( Jenkins.getInstance().getRootDir(),
            "fingerprints/"+ Util.toHexString(md5sum,0,1)+'/'+Util.toHexString(md5sum,1,1)+'/'+Util.toHexString(md5sum,2,md5sum.length-2)+".xml");
    }
966326
def generate_key(s, pattern="%s.txt"):
    
    h = hashlib.sha1()
    #h.update(s)
    h.update(s.encode('utf-8'))
    return pattern % h.hexdigest()
745812
def format_idp_cert_multi(self):
        
        if 'x509certMulti' in self.__idp:
            if 'signing' in self.__idp['x509certMulti']:
                for idx in range(len(self.__idp['x509certMulti']['signing'])):
                    self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['signing'][idx])

            if 'encryption' in self.__idp['x509certMulti']:
                for idx in range(len(self.__idp['x509certMulti']['encryption'])):
                    self.__idp['x509certMulti']['encryption'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['encryption'][idx])
1015389
function generateBKP (pkp) {
  const buffer = new Buffer(pkp, 'base64')
  const hash = crypto.createHash('sha1')
  hash.update(buffer)
  const sha1str = hash.digest('hex').toUpperCase()
  return sha1str.match(/(.{1,8})/g).join('-')
}
1180657
def process_js_certs(self, data, name, idx, sub_idx):
        
        from cryptography.x509.base import load_der_x509_certificate

        ret = []
        for crt_hex in data:
            try:
                bindata = base64.b64decode(crt_hex)
                x509 = load_der_x509_certificate(bindata, self.get_backend())

                self.num_ldiff_cert += 1
                sub = self.process_x509(x509, name=name, pem=False, source='ldiff-cert')
                ret.append(sub)

            except Exception as e:
                logger.debug('Error in line JSON cert file processing %s, idx %s, subidx %s : %s'
                             % (name, idx, sub_idx, e))
                self.trace_logger.log(e)
        return ret
51663
def _generate_password():
    
    uuid_str = six.text_type(uuid.uuid4()).encode("UTF-8")
    return hashlib.sha1(uuid_str).hexdigest()
1086240
def git_hash(blob):
    """"""
    head = str("blob " + str(len(blob)) + "\0").encode("utf-8")
    return sha1(head + blob).hexdigest()
940709
public String generateFingerprint(String hashFunction) {
		try {
			this.hashFunction = hashFunction;
			org.bouncycastle.crypto.tls.Certificate chain = TlsUtils.loadCertificateChain(certificateResources);
			Certificate certificate = chain.getCertificateAt(0);
			return TlsUtils.fingerprint(this.hashFunction, certificate);
		} catch (IOException e) {
			LOGGER.error("Could not get local fingerprint: "+ e.getMessage());
			return "";
		}
	}
931786
def _authenticate_scram_sha1(credentials, sock_info):
    """"""
    username = credentials.username
    password = credentials.password
    source = credentials.source

    # Make local
    _hmac = hmac.HMAC
    _sha1 = sha1

    user = username.encode("utf-8").replace(b"=", b"=3D").replace(b",", b"=2C")
    nonce = standard_b64encode(
        (("%s" % (SystemRandom().random(),))[2:]).encode("utf-8"))
    first_bare = b"n=" + user + b",r=" + nonce

    cmd = SON([('saslStart', 1),
               ('mechanism', 'SCRAM-SHA-1'),
               ('payload', Binary(b"n,," + first_bare)),
               ('autoAuthorize', 1)])
    res = sock_info.command(source, cmd)

    server_first = res['payload']
    parsed = _parse_scram_response(server_first)
    iterations = int(parsed[b'i'])
    salt = parsed[b's']
    rnonce = parsed[b'r']
    if not rnonce.startswith(nonce):
        raise OperationFailure("Server returned an invalid nonce.")

    without_proof = b"c=biws,r=" + rnonce
    salted_pass = _hi(_password_digest(username, password).encode("utf-8"),
                      standard_b64decode(salt),
                      iterations)
    client_key = _hmac(salted_pass, b"Client Key", _sha1).digest()
    stored_key = _sha1(client_key).digest()
    auth_msg = b",".join((first_bare, server_first, without_proof))
    client_sig = _hmac(stored_key, auth_msg, _sha1).digest()
    client_proof = b"p=" + standard_b64encode(_xor(client_key, client_sig))
    client_final = b",".join((without_proof, client_proof))

    server_key = _hmac(salted_pass, b"Server Key", _sha1).digest()
    server_sig = standard_b64encode(
        _hmac(server_key, auth_msg, _sha1).digest())

    cmd = SON([('saslContinue', 1),
               ('conversationId', res['conversationId']),
               ('payload', Binary(client_final))])
    res = sock_info.command(source, cmd)

    parsed = _parse_scram_response(res['payload'])
    if not compare_digest(parsed[b'v'], server_sig):
        raise OperationFailure("Server returned an invalid signature.")

    # Depending on how it's configured, Cyrus SASL (which the server uses)
    # requires a third empty challenge.
    if not res['done']:
        cmd = SON([('saslContinue', 1),
                   ('conversationId', res['conversationId']),
                   ('payload', Binary(b''))])
        res = sock_info.command(source, cmd)
        if not res['done']:
            raise OperationFailure('SASL conversation failed to complete.')
881665
def sign_digest(sock, keygrip, digest, sp=subprocess, environ=None):
    """"""
    hash_algo = 8  # SHA256
    assert len(digest) == 32

    assert communicate(sock, 'RESET').startswith(b'OK')

    ttyname = check_output(args=['tty'], sp=sp).strip()
    options = ['ttyname={}'.format(ttyname)]  # set TTY for passphrase entry

    display = (environ or os.environ).get('DISPLAY')
    if display is not None:
        options.append('display={}'.format(display))

    for opt in options:
        assert communicate(sock, 'OPTION {}'.format(opt)) == b'OK'

    assert communicate(sock, 'SIGKEY {}'.format(keygrip)) == b'OK'
    hex_digest = binascii.hexlify(digest).upper().decode('ascii')
    assert communicate(sock, 'SETHASH {} {}'.format(hash_algo,
                                                    hex_digest)) == b'OK'

    assert communicate(sock, 'SETKEYDESC '
                       'Sign+a+new+TREZOR-based+subkey') == b'OK'
    assert communicate(sock, 'PKSIGN') == b'OK'
    while True:
        line = recvline(sock).strip()
        if line.startswith(b'S PROGRESS'):
            continue
        else:
            break
    line = unescape(line)
    log.debug('unescaped: %r', line)
    prefix, sig = line.split(b' ', 1)
    if prefix != b'D':
        raise ValueError(prefix)

    sig, leftover = parse(sig)
    assert not leftover, leftover
    return parse_sig(sig)
837600
public synchronized PrivateKey getPrivateKeyForLocalCert(final X509Certificate cert)
	throws CertificateEncodingException, KeyStoreException, UnrecoverableKeyException,
	NoSuchAlgorithmException
	{
		String thumbprint = ThumbprintUtil.getThumbprint(cert);

		return (PrivateKey)_ks.getKey(thumbprint, _keypassword);
	}
130420
private static Object createKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
        Class keyGenClass = lookupKeyGenClass();
        Object keypair = ClassUtil.newInstance(keyGenClass, "RSA", "SHA1WithRSA");
        ClassUtil.applyMethod(keypair, "generate", 2048);
        return keypair;
    }
775938
def sha256_fingerprint_from_raw_ssh_pub_key(raw_key):
    
    digest = hashlib.sha256(raw_key).digest()
    h = base64.b64encode(digest).decode('utf-8')
    h = h.rstrip().rstrip('=')  # drop newline and possible base64 padding
    return 'SHA256:' + h
255026
def generate_cert(name):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': ''}
    cert = "{0}{1}.crt".format(get_certs_path(), name)
    key = "{0}{1}.key".format(get_certs_path(), name)

    # Checking if execution is needed.
    if os.path.isfile(cert) and os.path.isfile(key):
        ret['comment'] = 'No execution needed. Cert: {0} and key: {1} already generated.'.format(cert, key)
        return ret
    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Certificate and key generation would be executed'
        return ret

    # Executing the command.
    cert_save = __salt__['icinga2.generate_cert'](name)
    if not cert_save['retcode']:
        ret['comment'] = "Certificate and key generated"
        ret['changes']['cert'] = "Executed. Certificate saved: {0}".format(cert)
        ret['changes']['key'] = "Executed. Key saved: {0}".format(key)
    return ret
547815
def save_x509s(self, x509s):
        """"""

        for file_type in TLSFileType:
            if file_type.value in x509s:
                x509 = x509s[file_type.value]
                if file_type is not TLSFileType.CA:
                    # persist this key or cert to disk
                    tlsfile = getattr(self, file_type.value)
                    if tlsfile:
                        tlsfile.save(x509)
143552
def _pkcs1imify(self, data):
        
        SHA1_DIGESTINFO = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14'
        size = len(util.deflate_long(self.n, 0))
        filler = '\xff' * (size - len(SHA1_DIGESTINFO) - len(data) - 3)
        return '\x00\x01' + filler + '\x00' + SHA1_DIGESTINFO + data