def basic_assertions(self, cdir, cert, key, cacert=None): ''' test basic certificate assumptions Args: cdir (s_certdir.CertDir): certdir object cert (crypto.X509): Cert to test key (crypto.PKey): Key for the certification cacert (crypto.X509): Corresponding CA cert (optional) ''' self.nn(cert) self.nn(key) # Make sure the certs were generated with the expected number of bits self.eq(cert.get_pubkey().bits(), cdir.crypto_numbits) self.eq(key.bits(), cdir.crypto_numbits) # Make sure the certs were generated with the correct version number self.eq(cert.get_version(), 2) # ensure we can sign / verify data with our keypair buf = b'The quick brown fox jumps over the lazy dog.' sig = crypto.sign(key, buf, 'sha256') sig2 = crypto.sign(key, buf + b'wut', 'sha256') self.none(crypto.verify(cert, sig, buf, 'sha256')) self.raises(crypto.Error, crypto.verify, cert, sig2, buf, 'sha256') # ensure that a ssl context using both cert/key match sslcontext = SSL.Context(SSL.TLSv1_2_METHOD) sslcontext.use_certificate(cert) sslcontext.use_privatekey(key) self.none(sslcontext.check_privatekey()) if cacert: # Make sure the cert was signed by the CA self.eq(cert.get_issuer().der(), cacert.get_subject().der()) store = crypto.X509Store() ctx = crypto.X509StoreContext(store, cert) # OpenSSL should NOT be able to verify the certificate if its CA is not loaded store.add_cert(cert) self.raises(crypto.X509StoreContextError, ctx.verify_certificate) # unable to get local issuer certificate # Generate a separate CA that did not sign the certificate try: cdir.genCaCert('otherca') except s_exc.DupFileName: pass # OpenSSL should NOT be able to verify the certificate if its CA is not loaded store.add_cert(cdir.getCaCert('otherca')) self.raises(crypto.X509StoreContextError, ctx.verify_certificate) # unable to get local issuer certificate # OpenSSL should be able to verify the certificate, once its CA is loaded store.add_cert(cacert) self.none(ctx.verify_certificate()) # valid
def sign_tag(certificado, **kwargs): pkcs12 = crypto.load_pkcs12(certificado.pfx, certificado.password) key = pkcs12.get_privatekey() if 'nfse' in kwargs: for item in kwargs['nfse']['lista_rps']: signed = crypto.sign(key, item['assinatura'], 'SHA1') item['assinatura'] = b64encode(signed) if 'cancelamento' in kwargs: signed = crypto.sign(key, kwargs['cancelamento']['assinatura'], 'SHA1') kwargs['cancelamento']['assinatura'] = b64encode(signed)
def create_signature(self, digest): pk_string = open(self.transaction.channel.key_file.path, 'rt').read() key = load_privatekey(FILETYPE_PEM, pk_string) signed = crypto.sign(key, str(digest), 'sha1') b21 = b64encode(signed) return b21
def create_wls_response(raven_ver='2', raven_status='200', raven_msg='', raven_issue=datetime.utcnow().strftime( '%Y%m%dT%H%M%SZ' ), raven_id='1347296083-8278-2', raven_url=EXAMPLE_RAVEN_RETURN_URL, raven_principal=RAVEN_TEST_USER, raven_auth='pwd', raven_sso='', raven_life='36000', raven_params='', raven_kid='901', raven_key_pem=GOOD_PRIV_KEY_PEM): """Creates a valid WLS Response as the Raven test server would using keys from https://raven.cam.ac.uk/project/keys/demo_server/ """ raven_pkey = load_privatekey(FILETYPE_PEM, raven_key_pem) trans_table = maketrans("+/=", "-._") # This is the data which is signed by Raven with their private key # Note data consists of full payload with exception of kid and sig # source: http://raven.cam.ac.uk/project/waa2wls-protocol.txt wls_response_data = [raven_ver, raven_status, raven_msg, raven_issue, raven_id, raven_url, raven_principal, raven_auth, raven_sso, raven_life, raven_params] data = '!'.join(wls_response_data) raven_sig = b64encode(sign(raven_pkey, data, 'sha1')) # Full WLS-Response also includes the Raven-variant b64encoded sig # and the requisite Key ID which has been used for the signing # process wls_response_data.append(raven_kid) wls_response_data.append(str(raven_sig).translate(trans_table)) return '!'.join(wls_response_data)
def _ConstructJwtCredential(json_keyfile, audience): with open(json_keyfile, 'r') as json_keyfile_obj: client_credentials = json.load(json_keyfile_obj) pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, client_credentials['private_key']) jwt_header = { "alg": "RS256", "typ": "JWT", "kid": client_credentials['private_key_id'] } # Use time 1 minute before now to avoid clock skew with Google servers current_time = int(time.time()) - 60 jwt_payload = { "iss": client_credentials['client_email'], "sub": client_credentials['client_email'], "aud": audience, "iat": current_time, "exp": current_time + 3600 } jwt_header_base64 = base64.urlsafe_b64encode(json.dumps(jwt_header, separators=(',', ':')).encode('utf-8')).decode().strip('=') jwt_payload_base64 = base64.urlsafe_b64encode(json.dumps(jwt_payload, separators=(',', ':')).encode('utf-8')).decode().strip('=') jwt_base_string = jwt_header_base64 + '.' + jwt_payload_base64 jwt_signature = base64.urlsafe_b64encode(crypto.sign(pkey, jwt_base_string, "sha256")).decode().strip('=') jwt = jwt_base_string + '.' + jwt_signature return client.AccessTokenCredentials(jwt, _DEFAULT_USER_AGENT)
def alipay_fuwu(self, **post): """ 支付宝服务窗开发者模式验证和消息接受地址 """ # 将post来的参数排除掉sign后作为待签名参数 sign_params_dic = {} for post_key, post_val in post.items(): if not post_key=='sign': sign_params_dic[post_key] = post_val.decode('utf8') # 待签名参数按key值排序,组合成query字符串 _, sign_query_str = util.params_filter(sign_params_dic) # 使用支付宝公钥签名验签 sign_verify = RSA.load_pub_key('addons-extra/wxsite/static/alipay_rsa_public_key.pem').verify(sign_query_str, post['sign']) # sign_by_ali_pub64 = sign_by_ali_pub.encode('base64') if sign_verify: # 待签名字符串:公钥+success str_to_sign_by_private = '<biz_content>MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9vK4cSuzfGJKMJ/XQ82SMxRjbVussG+sI4lrgJLa7cbHZ19+zZRy9IyMYyvpD/gm4blgha0iOhRxPuxmvLHcNerG2u9q+X18NeJ0bLHxZRpPhOXMzgBDp78LDG1m7NtNW5Poat2JZyxSCTBbs1x3Tk9NUVr8mHLpriFO1ik4EEwIDAQAB</biz_content><success>true</success>' # 加载私钥进行签名 rsa_private_key = load_privatekey(FILETYPE_PEM, open('addons-extra/wxsite/static/rsa_private_key.pem').read()) rsa_private_sign = sign(rsa_private_key, str_to_sign_by_private, 'sha1') rsa_private_sign = base64.b64encode(rsa_private_sign) # 拼接返回给支付宝的xml内容 response_xml = '<?xml version="1.0" encoding="GBK"?><alipay><response>'+str_to_sign_by_private+'</response><sign>'+rsa_private_sign+'</sign><sign_type>RSA</sign_type></alipay>' return response_xml.encode('gbk') else: return 'fail'.encode('gbk')
def cert_auth(self, path=None, payload='', method=None): ''' Perform APIC signature-based authentication, not the expected SSL client certificate authentication. ''' if method is None: method = self.params['method'].upper() # NOTE: ACI documentation incorrectly uses complete URL if path is None: path = self.path path = '/' + path.lstrip('/') if payload is None: payload = '' # Use the private key basename (without extension) as certificate_name if self.params['certificate_name'] is None: self.params['certificate_name'] = os.path.basename(os.path.splitext(self.params['private_key'])[0]) try: sig_key = load_privatekey(FILETYPE_PEM, open(self.params['private_key'], 'r').read()) except: self.module.fail_json(msg='Cannot load private key %s' % self.params['private_key']) # NOTE: ACI documentation incorrectly adds a space between method and path sig_request = method + path + payload sig_signature = base64.b64encode(sign(sig_key, sig_request, 'sha256')) sig_dn = 'uni/userext/user-%s/usercert-%s' % (self.params['username'], self.params['certificate_name']) self.headers['Cookie'] = 'APIC-Certificate-Algorithm=v1.0; ' +\ 'APIC-Certificate-DN=%s; ' % sig_dn +\ 'APIC-Certificate-Fingerprint=fingerprint; ' +\ 'APIC-Request-Signature=%s' % sig_signature
def _get_signature_bytes(credentials, string_to_sign): """Uses crypto attributes of credentials to sign a string/bytes. :type credentials: :class:`service_account.ServiceAccountCredentials`, :class:`_GAECreds` :param credentials: The credentials used for signing text (typically involves the creation of a PKey). :type string_to_sign: string :param string_to_sign: The string to be signed by the credentials. :rtype: bytes :returns: Signed bytes produced by the credentials. :raises: `EnvironmentError` if `crypto` did not import successfully. """ if isinstance(credentials, _GAECreds): _, signed_bytes = app_identity.sign_blob(string_to_sign) return signed_bytes else: # Sign the string with the PKey. pkey = _get_pem_key(credentials) if not isinstance(string_to_sign, six.binary_type): string_to_sign = string_to_sign.encode('utf-8') if crypto is None: raise EnvironmentError( 'pyOpenSSL must be installed to sign content using a ' 'private key') return crypto.sign(pkey, string_to_sign, 'SHA256')
def SignWithKey(self, key_data): if key_data is None: # We'll cheat, and say this means "get rid of the signature" if SIGNATURE_KEY in self._dict: self._dict.pop(SIGNATURE_KEY) else: import OpenSSL.crypto as Crypto from base64 import b64encode as base64 # If it's a PKey, we don't need to load it if isinstance(key_data, Crypto.PKey): key = key_data else: # Load the key. This is most likely to fail. key = Crypto.load_privatekey(Crypto.FILETYPE_PEM, key_data) # Generate a canonical representation of the manifest temp = self.dict() if SIGNATURE_KEY in temp: temp.pop(SIGNATURE_KEY) tstr = MakeString(temp) # Sign it. signed_value = base64(Crypto.sign(key, tstr, "sha256")) # And now set the signature self._dict[SIGNATURE_KEY] = signed_value return
def sign(self, data, digest): """sign string containing data.""" try: return crypto.sign(self._key, data, digest) except crypto.Error, exc: raise SecurityError, SecurityError( "Unable to sign data: %r" % (exc, )), sys.exc_info()[2]
def sign_by_soft(private_key, sign_digest, digest_method='sha1'): ''' @private_key: the private_key get from PKCS12 pem @sign_digest: the hash value of urlencoded string @digest_method: the unionpay using sha1 digest string ''' return crypto.sign(private_key, sign_digest, digest_method)
def validate_key_cert(key_file, cert_file): try: error_key_name = "private key" error_filename = key_file key_str = open(key_file, "r").read() key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_str) error_key_name = "certficate" error_filename = cert_file cert_str = open(cert_file, "r").read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str) except IOError as ioe: raise RuntimeError(_("There is a problem with your %s " "%s. Please verify it. Error: %s") % (error_key_name, error_filename, ioe)) except crypto.Error as ce: raise RuntimeError(_("There is a problem with your %s " "%s. Please verify it. OpenSSL error: %s") % (error_key_name, error_filename, ce)) try: data = str(uuid.uuid4()) digest = "sha1" out = crypto.sign(key, data, digest) crypto.verify(cert, out, data, digest) except crypto.Error as ce: raise RuntimeError(_("There is a problem with your key pair. " "Please verify that cert %s and key %s " "belong together. OpenSSL error %s") % (cert_file, key_file, ce))
def main(insecure, server): """ main insecure Controls whether the client should not verify the remote servers SSL cert server Remote server name """ key = crypto.load_privatekey(crypto.FILETYPE_PEM, open(DEFAULT_KEY).read()) data = {} data['cert'] = open(DEFAULT_CERT).read() m = md5() m.update(str(time())) data['nonce'] = b64encode(m.digest()) data['signature'] = b64encode(crypto.sign(key, data['nonce'], DIGEST)) data['action'] = 'get_pub_config' url = 'https://' + server + '/esgf-nm/api' verify = not insecure res = None try: res = requests.post(url, data=data, verify=verify) except Exception as e: print e exit(-1) arr = [] try: arr = json.loads(res.text) except Exception as e: print "ERROR!" print print res.text print print e exit(-1) outstr = '\n'+'\n'.join(map(lambda x: ' | '.join(x), arr) )+'\n' pub_cfg_file = "/esg/config/esgcet/esg.ini" rcp = RawConfigParser() rcp.readfp(open(pub_cfg_file)) rcp.add_section('config:cmip6') rcp.set('config:cmip6', 'pid_credentials', outstr) rcp.write(open(pub_cfg_file, 'w')) print "Retrieval of credentials and write to esg.ini complete."
def ssl_sign(data, private_key): """ Sign some data using OpenSSL, and the application's certificate @return the base64 encodeded signature """ key = ossl.load_privatekey(ossl.FILETYPE_PEM, private_key) return base64.b64encode(ossl.sign(key, data, 'sha256'))
def _sign(self, data): """ Sign some data using OpenSSL, and the application's certificate @return the base64 encodeded signature """ self._ensure_keys() key = ossl.load_privatekey(ossl.FILETYPE_PEM, self.privateKey) return base64.b64encode(ossl.sign(key, data, 'sha256'))
def Wrap(self, instr): inbytes = instr.encode('utf8') return { 'cert': self._cert_str, 'other_certs': self._other_cert_strs, 'sig': codecs.encode(crypto.sign(self._key, inbytes, 'sha256'), 'hex').decode('ascii'), 'inner': instr, }
def sign_data(js_data): if None == js_data: return None conf_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) s_hash = base64.b64encode(hashlib.md5(json.dumps(js_data)).digest()) pk_prikey = ct.load_privatekey(ct.FILETYPE_PEM, open(os.path.join(conf_dir,'rfd.pem')).read()) s_res = s_json + ',' + base64.b64encode(ct.sign(pk_prikey, s_hash, 'sha1')) return s_res
def create_signature(meta_data_folder, pkey): manifest_file = os.path.join(meta_data_folder, MANIFEST_FILE) with open(os.path.join(meta_data_folder, SIGNATURE_FILE), 'wb') as sf: checksum = file_checksum(hashlib.sha256, manifest_file).encode('utf-8') if pkey: sf.write(crypto.sign(pkey, checksum, 'sha256')) else: sf.write(checksum)
def sign_data(cls, js_data, s_pk_file): if None == js_data: return None s_json = json.dumps(js_data, separators=(',', ':')) s_hash = base64.b64encode(hashlib.md5(s_json).digest()) pk_prikey = ct.load_privatekey(ct.FILETYPE_PEM, open(s_pk_file).read()) s_res = s_json + ',' + base64.b64encode(ct.sign(pk_prikey, s_hash, 'sha1')) return s_res
def sign(key_data, data): """ use rsa 256 to sign data :param key_data: private key content, must be PKCS#1 PEM-encoded :param data: data to sign :return: signed data """ private_key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_data) return base64.b64encode(crypto.sign(private_key, data.encode('utf-8'), 'sha256')).decode()
def populate(): timestamp = int(time.time()) hostname = socket.gethostname() uid = os.getuid() content = '%s:%s:%s' % (timestamp, hostname, uid) priv_key = load_privatekey(FILETYPE_PEM, open(PRIV_KEY_FILE).read()) sig = base64.b64encode(sign(priv_key, content, "sha1")) return '%s:%s' % (content, sig)
def test_sign(self): """ signMessage behaves like OpenSSL.crypto.sign """ pkey = self.pkey a = sign(pkey, "message", "sha1") r = signMessage("message", pkey) self.assertEquals(type(a), type(r)) self.assertEquals(a, r)
def validate_key_cert(key_file, cert_file): try: error_key_name = "private key" error_filename = key_file with open(key_file, "r") as keyfile: key_str = keyfile.read() key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_str) error_key_name = "certificate" error_filename = cert_file with open(cert_file, "r") as certfile: cert_str = certfile.read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str) except IOError as ioe: raise RuntimeError( _( "There is a problem with your %(error_key_name)s " "%(error_filename)s. Please verify it." " Error: %(ioe)s" ) % {"error_key_name": error_key_name, "error_filename": error_filename, "ioe": ioe} ) except crypto.Error as ce: raise RuntimeError( _( "There is a problem with your %(error_key_name)s " "%(error_filename)s. Please verify it. OpenSSL" " error: %(ce)s" ) % {"error_key_name": error_key_name, "error_filename": error_filename, "ce": ce} ) try: data = str(uuid.uuid4()) digest = CONF.digest_algorithm if digest == "sha1": LOG.warn( "The FIPS (FEDERAL INFORMATION PROCESSING STANDARDS)" " state that the SHA-1 is not suitable for" " general-purpose digital signature applications (as" " specified in FIPS 186-3) that require 112 bits of" " security. The default value is sha1 in Kilo for a" " smooth upgrade process, and it will be updated" " with sha256 in next release(L)." ) out = crypto.sign(key, data, digest) crypto.verify(cert, out, data, digest) except crypto.Error as ce: raise RuntimeError( _( "There is a problem with your key pair. " "Please verify that cert %(cert_file)s and " "key %(key_file)s belong together. OpenSSL " "error %(ce)s" ) % {"cert_file": cert_file, "key_file": key_file, "ce": ce} )
def assina_texto(self, texto): # # Carrega o arquivo do certificado # pkcs12 = crypto.load_pkcs12(open(self.arquivo, 'rb').read(), self.senha) assinatura = crypto.sign(pkcs12.get_privatekey(), texto, 'sha1') return base64.encode(assinatura)
def _prep_x509_header(self, method, url, data=None): """ This function returns a dictionary containing the authentication signature for a given request based on the private key and certificate name given to the session object. If the session object is using normal (user/pass) authentication an empty dictionary is returned. To calculate the signature the request is calculated on a string with format: '<HTTP-METHOD><URL><PAYLOAD>' > Note, the URL *does not* include the DNS/IP of the APIC """ if not self.cert_auth: return {} # for appcenter_user with subscription enabled and currently logged_in # no need to build x509 header since authentication is using token if self.appcenter_user and self._subscription_enabled and self._logged_in: return {} if not self.session: self.session = requests.Session() if self.appcenter_user: cert_dn = 'uni/userext/appuser-{0}/usercert-{1}'.format(self.uid, self.cert_name) else: cert_dn = 'uni/userext/user-{0}/usercert-{1}'.format(self.uid, self.cert_name) url = unquote(url) logging.debug(( "Preparing certificate based authentication with:" "\n Cert DN: {}" "\n Key file: {} " "\n Request: {} {}" "\n Data: {}").format( cert_dn, self.key, method, url, data) ) payload = '{}{}'.format(method, url) if data: payload += data signature = base64.b64encode(sign(self._x509Key, payload, 'sha256')) cookie = {'APIC-Request-Signature': signature, 'APIC-Certificate-Algorithm': 'v1.0', 'APIC-Certificate-Fingerprint': 'fingerprint', 'APIC-Certificate-DN': cert_dn} logging.debug('Authentication cookie %s' % cookie) return cookie
def signMessage(message, key): """ Produces a signature using a private key. @param message: string of data to sign @param key: instance of OpenSSL.crypto.PKey """ return sign(key, message, "sha1")
def test_verify_badcert(self): """ if the cert doesn't belong with the signature verifySignature returns False """ cert = self.cert _, cert2 = create_self_signed_cert() data = "data" signature = sign(self.pkey, data, "sha1") self.assertFalse(verifySignature(signature, data, cert2))
def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ return crypto.sign(self._key, message, 'sha256')
def test(): # 没有找到openssl的公钥加载和校验方式,所以使用rsa 的公钥和校验方式 with open(config.public_key_file) as f: pub_key = rsa.PublicKey.load_pkcs1_openssl_pem(f.read()) with open(config.private_key_file) as f: priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read()) ret_sign = crypto.sign(priv_key, config.test_data, 'sha1') # 这里的摘要算法为小写,且没有分隔符,这和rsa模块不同 rsa.verify(config.test_data, ret_sign, pub_key)
def save_integrity(self, fdst, fsrc): md = hashlib.sha256() buf = fsrc.read(self.BLOCKSIZE) while len(buf) > 0: md.update(buf) fdst.write(buf) buf = fsrc.read(self.BLOCKSIZE) signature = co.sign(self.server_key, md.hexdigest(), 'sha256') fdst.close() return signature
def sign(action, method, headers, data): # Installation requests are not signed if method.startswith("v1/installation"): return # device-server and session-server use the installation token # Other endpoints use a session token if not (method.startswith("v1/device-server") or method.startswith("v1/session-server")): headers['X-Bunq-Client-Authentication'] = get_session_token() return headers['X-Bunq-Client-Authentication'] = get_installation_token() # Device-server and session-server must be signed private_key = get_private_key() sig = crypto.sign(private_key, data, 'sha256') sig_str = base64.b64encode(sig).decode("utf-8") headers['X-Bunq-Client-Signature'] = sig_str
def assemble_cloudfront_request(resource, key, access_id, expires): """Assemble a CloudFront request.""" # Format a request policy for the resource request_policy = { "Statement": [{"Resource": resource, "Condition": {"DateLessThan": {"AWS:EpochTime": expires}}}] } request_policy = json.dumps(request_policy).replace(' ', '') # Sign and encode request policy signature = base64.b64encode(sign(key, request_policy, 'RSA-SHA1')) # Replace unsafe characters signature = signature.translate(maketrans('+=/', '-_~')) # Format the final request URL cloudfront_request = ("{0}?Expires={1}&Signature={2}&Key-Pair-Id={3}" .format(resource, expires, signature, access_id)) return cloudfront_request
def _x509Prep(self, rootApi, req, data): if rootApi._x509Key is None: return payload = '{}{}'.format(req.method, req.url.replace(rootApi._url, '')) payload = unquote(payload) if data is not None: payload += data signature = base64.b64encode(sign(rootApi._x509Key, payload, 'sha256')) if sys.version_info[0] >= 3: signature = signature.decode('ascii') cookie = ('APIC-Request-Signature={}; ' 'APIC-Certificate-Algorithm=v1.0; ' 'APIC-Certificate-Fingerprint=fingerprint; ' 'APIC-Certificate-DN={}').format(signature, rootApi._x509Dn) req.headers['Cookie'] = cookie
def _GenSignedUrl(key, client_id, method, md5, content_type, expiration, gcs_path): """Construct a string to sign with the provided key and returns \ the complete url.""" tosign = ('{0}\n{1}\n{2}\n{3}\n/{4}' .format(method, md5, content_type, expiration, gcs_path)) signature = base64.b64encode(sign(key, tosign, 'RSA-SHA256')) final_url = ('https://storage.googleapis.com/{0}?' 'GoogleAccessId={1}&Expires={2}&Signature={3}' .format(gcs_path, client_id, expiration, urllib.quote_plus(str(signature)))) return final_url
def login(self): """ Login into APIC using certificate and plugin key """ start_time = datetime.datetime.now() global auth_token user_cert, plugin_key = create_cert_session() app_token_payload = { "aaaAppToken": { "attributes": { "appName": "Cisco_AppIQ" } } } data = json.dumps(app_token_payload) pay_load = "POST" + urls.LOGIN_URL_SUFFIX + data private_key = load_privatekey(FILETYPE_PEM, plugin_key) signed_digest = sign(private_key, pay_load.encode(), 'sha256') signature = base64.b64encode(signed_digest).decode() token = "APIC-Request-Signature=" + signature + ";" token += "APIC-Certificate-Algorithm=v1.0;" token += "APIC-Certificate-Fingerprint=fingerprint;" token += "APIC-Certificate-DN=" + str(user_cert.dn) try: response = self.session.post(urls.LOGIN_URL.format( self.proto, self.apic_ip), data=data, headers={'Cookie': token}, timeout=10, verify=False) status_code = response.status_code if status_code == 200 or status_code == 201: auth = json.loads(response.text) auth_token = auth['imdata'][0]['aaaLogin']['attributes'][ 'token'] return auth_token else: return None except Exception as e: logger.exception('Unable to connect with APIC. Exception: ' + str(e)) return None finally: end_time = datetime.datetime.now() logger.info("Time for ACI login: " + str(end_time - start_time))
def validate_key_cert(key_file, cert_file): try: error_key_name = "private key" error_filename = key_file key_str = open(key_file, "r").read() key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_str) error_key_name = "certficate" error_filename = cert_file cert_str = open(cert_file, "r").read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str) except IOError as ioe: raise RuntimeError( _("There is a problem with your %(error_key_name)s " "%(error_filename)s. Please verify it." " Error: %(ioe)s") % { 'error_key_name': error_key_name, 'error_filename': error_filename, 'ioe': ioe }) except crypto.Error as ce: raise RuntimeError( _("There is a problem with your %(error_key_name)s " "%(error_filename)s. Please verify it. OpenSSL" " error: %(ce)s") % { 'error_key_name': error_key_name, 'error_filename': error_filename, 'ce': ce }) try: data = str(uuid.uuid4()) digest = "sha1" out = crypto.sign(key, data, digest) crypto.verify(cert, out, data, digest) except crypto.Error as ce: raise RuntimeError( _("There is a problem with your key pair. " "Please verify that cert %(cert_file)s and " "key %(key_file)s belong together. OpenSSL " "error %(ce)s") % { 'cert_file': cert_file, 'key_file': key_file, 'ce': ce })
def make_license(private_key_string, product_code, name): private_key = crypto.load_privatekey(crypto.FILETYPE_PEM, private_key_string) signature = crypto.sign(private_key, make_license_source(product_code, name), 'sha1') # Use sha1 instead of dss1 to avoid 'ValueError("No such digest method")' encoded_signature = base64.b32encode(signature) # Replace 'O' with 8, 'I' with 9 # See http://members.shaw.ca/akochoi-old/blog/2004/11-07/index.html encoded_signature = encoded_signature.replace('O', '8').replace('I', '9') # Remove equal signs encoded_signature = encoded_signature.replace('=', '') # Insert a dash every 5 characters encoded_signature = '-'.join([ encoded_signature[i:i + 5] for i in range(0, len(encoded_signature), 5) ]) return encoded_signature
def generate_jwt(): headers = '{"typ":"JWT","alg":"RS256"}' jwt_header = base64.b64encode(str.encode(headers)).decode('utf-8').replace( '=', '').replace('/+', '_-').replace('+', '-').replace('\n', '') payload = '{"iat":%s,"exp":%s,"sub":"api_key_jwt","iss":"external","jti":"%s"}' % ( int(time.time()), int(time.time()) + 30, get_random_string(size=12)) jwt_payload = base64.b64encode( str.encode(payload)).decode('utf-8').replace('=', '').replace( '/+', '_-').replace('+', '-').replace('\n', '') _jwt_sign = '%s.%s' % (jwt_header, jwt_payload) _jwt_sign = crypto.sign(pkey, _jwt_sign, 'sha256') jwt_sign = base64.b64encode(_jwt_sign).decode('utf-8').replace( '=', '').replace('/+', '_-').replace('+', '-').replace('\n', '') return '%s.%s.%s' % (jwt_header, jwt_payload, jwt_sign)
def __JWS_SEND(self, url, header_info, payload): payload = _b64e(json.dumps(payload)) while True: header_info['nonce'] = self.__tlocal.nonce if 'nonce' in dir( self.__tlocal) else requests.get( CA + "/acme/new-nonce", timeout=self.__t).headers['Replay-Nonce'] headerInfo = _b64e(json.dumps(header_info)) signature = _b64e( crypto.sign(self.__crypto_privkey, "%s.%s" % (headerInfo, payload), "sha256")) data = { "protected": headerInfo, "payload": payload, "signature": signature } rVal = requests.post( url, json=data, headers={"Content-Type": "application/jose+json"}, timeout=self.__t) #check HTTP Layer before checking Application variables self.__tlocal.nonce = rVal.headers["Replay-Nonce"] #if rVal.status_code == 429: #if request rate-limited # tSleep = RAND(); # print rVal.content; # print "Too many requests, retrying in %.2f" % tSleep; # time.sleep(tSleep); # continue; #Continue to application (boulder) ###Validate boulder response if 'error:badNonce' in rVal.content: print "badNonce obtained for %s, retrying.." % header_info[ 'nonce'] time.sleep(1) elif rVal.status_code == 500: print "BOULDER INTERNAL ERROR (%s):\n%s" % (url, rVal.content) time.sleep(1) else: return rVal
def _send_signed_request(url, payload): payload64 = base64_enc(json.dumps(payload).encode('utf8')) protected = copy.deepcopy(header) protected["nonce"] = urlopen(CA + "/directory").headers['Replay-Nonce'] protected64 = base64_enc(json.dumps(protected).encode('utf8')) out = crypto.sign(account_key, '.'.join([protected64, payload64]), 'sha256') data = json.dumps({ "header": header, "protected": protected64, "payload": payload64, "signature": base64_enc(out), }) try: resp = urlopen(url, data.encode('utf8')) return resp.getcode(), resp.read() except IOError as e: return getattr(e, "code", None), getattr(e, "read", e.__str__)()
def SignAsciiCRL(tbs_inner_txt, signer=CA): tbs_txt = 'SEQUENCE {\n%s\n}' % tbs_inner_txt tbs_der = Ascii2Der(tbs_txt) signature = crypto.sign(signer['pkey'], tbs_der, 'sha256') crl_text = ''' SEQUENCE { %s SEQUENCE { # sha256WithRSAEncryption OBJECT_IDENTIFIER { 1.2.840.113549.1.1.11 } NULL {} } BIT_STRING { `00%s` } } ''' % (tbs_txt, signature.encode('hex')) CRL = Ascii2Der(crl_text) return CRL
def sign_verify_own_cert(): crt_bin = open( '/home/stetsenko/ksolutions/firstcard/core/certs/yandexmoney/Piastrix.cer', "rb").read() pkey = open( '/home/stetsenko/ksolutions/firstcard/core/certs/yandexmoney/ym_private.key.insecure', "rb").read() pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, pkey) sgn = crypto.sign(pkey, message, 'sha1') sign = base64.b64encode(sgn).decode('utf-8') print(sign) # строка схожа с той, что signature print(signature) crt = crypto.load_certificate(crypto.FILETYPE_PEM, crt_bin) # аналог к openssl_verify, взято с http://www.php2python.com/wiki/function.openssl-verify/ # если not verify - бросит ошибку crypto.verify(crt, base64.b64decode(sign.encode('utf-8')), message, 'sha1')
def sign_full_xml(self, message, privkey, cert, uri, type='libro'): doc = etree.fromstring(message) string = etree.tostring(doc[0]) mess = etree.tostring(etree.fromstring(string), method="c14n") digest = base64.b64encode(self.digest(mess)) reference_uri='#'+uri signed_info = Element("SignedInfo") c14n_method = SubElement(signed_info, "CanonicalizationMethod", Algorithm='http://www.w3.org/TR/2001/REC-xml-c14n-20010315') sign_method = SubElement(signed_info, "SignatureMethod", Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1') reference = SubElement(signed_info, "Reference", URI=reference_uri) transforms = SubElement(reference, "Transforms") SubElement(transforms, "Transform", Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315") digest_method = SubElement(reference, "DigestMethod", Algorithm="http://www.w3.org/2000/09/xmldsig#sha1") digest_value = SubElement(reference, "DigestValue") digest_value.text = digest signed_info_c14n = etree.tostring(signed_info,method="c14n",exclusive=False,with_comments=False,inclusive_ns_prefixes=None) att = 'xmlns="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' #@TODO Find better way to add xmlns:xsi attrib signed_info_c14n = signed_info_c14n.decode().replace("<SignedInfo>", "<SignedInfo %s>" % att ) xmlns = 'http://www.w3.org/2000/09/xmldsig#' sig_root = Element("Signature",attrib={'xmlns':xmlns}) sig_root.append(etree.fromstring(signed_info_c14n)) signature_value = SubElement(sig_root, "SignatureValue") key = crypto.load_privatekey(type_,privkey.encode('ascii')) signature = crypto.sign(key,signed_info_c14n,'sha1') signature_value.text =textwrap.fill(base64.b64encode(signature).decode(),64) key_info = SubElement(sig_root, "KeyInfo") key_value = SubElement(key_info, "KeyValue") rsa_key_value = SubElement(key_value, "RSAKeyValue") modulus = SubElement(rsa_key_value, "Modulus") key = load_pem_private_key(privkey.encode('ascii'),password=None, backend=default_backend()) longs = self.env['account.invoice'].long_to_bytes(key.public_key().public_numbers().n) modulus.text = textwrap.fill(base64.b64encode(longs).decode(),64) exponent = SubElement(rsa_key_value, "Exponent") longs = self.env['account.invoice'].long_to_bytes(key.public_key().public_numbers().e) exponent.text = self.ensure_str(base64.b64encode(longs)) x509_data = SubElement(key_info, "X509Data") x509_certificate = SubElement(x509_data, "X509Certificate") x509_certificate.text = '\n'+textwrap.fill(cert,64) msg = etree.tostring(sig_root) msg = msg if self.xml_validator(msg, 'sig') else '' fulldoc = message.replace('</LibroGuia>','%s\n</LibroGuia>' % msg.decode()) fulldoc = fulldoc if self.xml_validator(fulldoc, type) else '' return fulldoc
def gen_signed_url(gcs_path): """Construct a string to sign with the provided key and returns \ the complete url.""" expiration = (datetime.datetime.now() + datetime.timedelta(minutes=15)) expiration = int(time.mktime(expiration.timetuple())) key, client_id = read_json_keystore() canonicalized_resource = '{}'.format(gcs_path) tosign = ('{}\n{}\n{}\n{}\n{}'.format('GET', '', '', expiration, canonicalized_resource)) signature = base64.b64encode(sign(key, tosign, 'RSA-SHA256')) final_url = ('https://storage.googleapis.com{}?' 'GoogleAccessId={}&Expires={}&Signature={}'.format( gcs_path, client_id, expiration, quote_plus(str(signature)))) return final_url
def generate_bank_valid_answer_from_page_content(self, content): content = str(content) basket_id = re.search(r"PBX_CMD\" value=\"(\d*)\"", content).group(1) amount = re.search(r"PBX_TOTAL\" value=\"(\d*)\"", content).group(1) query = "Amount=%s&BasketID=%s&Auto=42&Error=00000" % (amount, basket_id) with open("./eboutic/tests/private_key.pem") as f: PRIVKEY = f.read() with open("./eboutic/tests/public_key.pem") as f: settings.SITH_EBOUTIC_PUB_KEY = f.read() privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, PRIVKEY) sig = crypto.sign(privkey, query, "sha1") b64sig = base64.b64encode(sig).decode("ascii") url = reverse("eboutic:etransation_autoanswer") + "?%s&Sig=%s" % ( query, urllib.parse.quote_plus(b64sig), ) response = self.client.get(url) return response
def sign(action, method, headers, data): # Installation requests are not signed if method.startswith("v1/installation"): return # device-server and session-server use the installation token # Other endpoints use a session token if (method.startswith("v1/device-server") or method.startswith("v1/session-server")): headers['X-Bunq-Client-Authentication'] = get_installation_token() else: headers['X-Bunq-Client-Authentication'] = get_session_token() ciphertext = action + " /" + method + "\n" for name in sorted(headers.keys()): ciphertext += name + ": " + headers[name] + "\n" ciphertext += "\n" + data private_key = get_private_key() sig = crypto.sign(private_key, ciphertext, 'sha256') sig_str = base64.b64encode(sig).decode("utf-8") headers['X-Bunq-Client-Signature'] = sig_str
async def get_flag(store: Storage, host: str, flag_id, flag: str, vuln) -> NoReturn: if flag not in store.users: verdict(CHECKER_ERROR, "Bad flag", "Flag was never stored") user = store.users[flag] reader, writer = await timed(open_connection(host, PORT)) greet = await timed(reader.readline()) if greet != b"name\n": mumble(f"Bad greeting: {greet}") writer.write(user.name + b"\n") resp = await timed(reader.readline()) if resp != b"exchange\n": mumble(f"Bad auth request: {resp}") bitsize = 256 str_len = bitsize // 4 + 2 client_eph: int server_eph: int client_eph = randbits(bitsize) client_eph_str = hex(client_eph).encode() writer.write(client_eph_str + b"\n") resp = await timed(reader.readline()) if resp == b"too short\n" or resp == b"not a number\n": mumble("Server dal yobu") try: server_eph = int(resp.strip(), 16) except ValueError: mumble(f"Not a number: {resp}") data = hex(server_eph * client_eph).encode() key = crypto.load_privatekey(crypto.FILETYPE_PEM, user.private_key) signature = crypto.sign(key, data, "sha256") writer.write(b64encode(signature) + b"\n") resp = await timed(reader.readline()) if resp != b"ok\n": mumble("Failed to verify") writer.write(b"get\n") store_flag = await timed(reader.readline()) if store_flag.strip().decode() != flag: corrupt(f"Bad flag: {store_flag} vs {flag} for user {user.name}") verdict_ok()
def send_message(message): global certificate, key with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST_USER, PORT_USER)) print("sending signed message") # sign the message with your private key signature = crypto.sign(key, message.encode("utf-8"), "sha256") # send message s.sendall(message.encode("utf-8")) print(s.recv(128).decode("utf-8")) #send signature s.sendall(signature) print(s.recv(128).decode("utf-8")) #send certificate s.sendall(crypto.dump_certificate(crypto.FILETYPE_PEM, certificate)) print(s.recv(128).decode("utf-8"))
def signContent(signImagePath): try: # Now the real world use case; use certificate to verify signature f = open(KEY_FILE) pv_buf = f.read() f.close() priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, pv_buf) # # sign and verify PASS msg=hash_file(signImagePath) sig = crypto.sign(priv_key, msg, 'sha256')#signed the image open(signaturePath, 'a').close() f = open(signaturePath, 'wb') f.write(sig) f.close() except: print("File path may not be correct")
def AciPost(apic, username, privateKey, method, path, payload): cert = username + '.crt' headers = {} sigContent = method + path + payload sigKey = load_privatekey(FILETYPE_PEM, privateKey) sigSignature = base64.b64encode(sign(sigKey, sigContent, 'sha256')).decode('utf-8') sigDn = 'uni/userext/user-%s/usercert-%s' % (username, cert) headers['Cookie'] = 'APIC-Certificate-Algorithm=v1.0; ' +\ 'APIC-Certificate-DN=%s; ' % sigDn +\ 'APIC-Certificate-Fingerprint=fingerprint; ' +\ 'APIC-Request-Signature=%s' % (sigSignature) url = 'https://' + apic + path logger.info(headers['Cookie']) if 'GET' in method: req = requests.get(url, headers=headers, verify=False) elif 'POST' in method: logger.info("POSTing to APIC url %s data %s" % (url, payload)) req = requests.post(url, data=payload, headers=headers, verify=False) return (req.text)
def requestJWS(self, url, payload=None): if not self.nonce: self.newNonce() protected = {"alg": "RS256", "url": url} if url in [self.directory['newAccount'], self.directory['revokeCert']]: protected["jwk"] = self.jws_jwk else: self.createAccount() protected['kid'] = self.account_url protected["nonce"] = self.nonce request = { "protected": base64url(protected), "payload": base64url(payload) if payload != None else "" } request['signature'] = base64url( crypto.sign(self.account_key, (request['protected'] + '.' + request['payload']).encode('utf-8'), 'sha256')) return self.request(url, json.dumps(request), {"Content-Type": "application/jose+json"})
def _prep_x509_header(self, method, url, data=None): """ This function returns a dictionary containing the authentication signature for a given request based on the private key and certificate name given to the session object. If the session object is using normal (user/pass) authentication an empty dictionary is returned. To calculate the signature the request is calculated on a string with format: '<HTTP-METHOD><URL><PAYLOAD>' > Note, the URL *does not* include the DNS/IP of the APIC """ if not self.cert_auth: return {} logging.debug( "Preparing certificate based authentication with cert name {} \ key file {} for request {} {} with data {}".format( self.cert_name, self.key, method, url, data)) if not self.session: self.session = requests.Session() cert_dn = 'uni/userext/user-{0}/usercert-{1}'.format( self.uid, self.cert_name) payload = '{}{}'.format(method, url) if data: payload += data logging.debug('Payload: ', payload) signature = base64.b64encode(sign(self._x509Key, payload, 'sha256')) cookie = { 'APIC-Request-Signature': signature, 'APIC-Certificate-Algorithm': 'v1.0', 'APIC-Certificate-Fingerprint': 'fingerprint', 'APIC-Certificate-DN': cert_dn } logging.debug('Authentication cookie', cookie) return cookie
def getSignitureLocally(pathOfImageToSign, privateKeyPath, digestMethod): """ sign the given image by using openssl :param pathOfImageToSign: :param privateKeyPath: :param digestMethod: :return: """ with open(privateKeyPath, "rb") as f: pKeyBuffer = f.read() pKey = crypto.load_privatekey(crypto.FILETYPE_PEM, pKeyBuffer) with open(pathOfImageToSign, "rb") as f: imageBuffer = f.read() signature = crypto.sign(pkey=pKey, data=imageBuffer, digest=digestMethod) return signature
def __sendSignedRequest(self, url, payload): payload = _b64e(json.dumps(payload)) header_info = copy.deepcopy(self.__header) # retrieve nonce. 1 request = 1 unique nonce header_info["nonce"] = requests.get( CA + "/directory", timeout=self.__t).headers['Replay-Nonce'] header_info = _b64e(json.dumps(header_info)) signature = _b64e( crypto.sign(self.__crypto_privkey, "%s.%s" % (header_info, payload), "sha256")) data = { "header": self.__header, "protected": header_info, "payload": payload, "signature": signature } print json.dumps(data, indent=4) response = requests.post(url, json=data, timeout=self.__t) print response.headers return response.status_code, response.headers, response.content
def _prep_x509_header(self, method, url, data=None): """ This function returns a dictionary containing the authentication signature for a given request based on the private key and certificate name given to the session object. If the session object is using normal (user/pass) authentication an empty dictionary is returned. To calculate the signature the request is calculated on a string with format: '<HTTP-METHOD><URL><PAYLOAD>' Note, the URL *does not* include the DNS/IP of the APIC """ if not self.cert_auth: return {} # for appcenter_user, once a token is acquired and logged they are logged in, # no need to build x509 header since authentication is using token if self.appcenter_user and self._logged_in: return {} if not self.session: self.session = requests.Session() if self.appcenter_user: cert_dn = 'uni/userext/appuser-{0}/usercert-{1}'.format( self.uid, self.cert_name) else: cert_dn = 'uni/userext/user-{0}/usercert-{1}'.format( self.uid, self.cert_name) url = unquote(url) #logger.debug("Perparing cert, dn:%s, key:%s, request: %s %s, data: %s", cert_dn, # self.key, method, url, data) payload = "%s%s" % (method, url) if data is not None: payload += data signature = base64.b64encode(sign(self._x509Key, payload, 'sha256')) cookie = { 'APIC-Request-Signature': signature, 'APIC-Certificate-Algorithm': 'v1.0', 'APIC-Certificate-Fingerprint': 'fingerprint', 'APIC-Certificate-DN': cert_dn } #logger.debug('Authentication cookie %s', cookie) return cookie
def requestAppToken(): session = requests.session() try: from OpenSSL.crypto import FILETYPE_PEM, load_privatekey, sign except: logging.info("=== could not import openssl crypto ===") ### Login Using RequestAppToken ### uri = "/api/requestAppToken.json" app_token_payload = {"aaaAppToken": {"attributes": {"appName": APP_USER}}} data = json.dumps(app_token_payload) payLoad = "POST" + uri + data p_key = '' with open(KEY_FILE_PATH, "r") as file: p_key = file.read() p_key = load_privatekey(FILETYPE_PEM, p_key) signedDigest = sign(p_key, payLoad.encode(), 'sha256') signature = base64.b64encode(signedDigest).decode() cookie = "APIC-Request-Signature=" + signature + ";" cookie += "APIC-Certificate-Algorithm=v1.0;" cookie += "APIC-Certificate-Fingerprint=fingerprint;" cookie += "APIC-Certificate-DN=" + USER_CERT_DN reply = session.post("{}{}".format(APIC_URL, uri), data=data, headers={'Cookie': cookie}, verify=False) json_reply = json.loads(reply.text) logging.info("Reply of requestAppToken: {}".format(json_reply)) auth_token = json_reply['imdata'][0]['aaaLogin']['attributes']['token'] token_cookie = {} token_cookie['APIC-Cookie'] = auth_token return token_cookie
def SignWithKey(self, key_data): if key_data is None: # We'll cheat, and say this means "get rid of the signature" self._signature = None else: import OpenSSL.crypto as Crypto from base64 import b64encode as base64 # Load the key. This is most likely to fail. key = Crypto.load_privatekey(Crypto.FILETYPE_PEM, key_data) # Generate a canonical representation of the manifest temp = self.dict() if SIGNATURE_KEY in temp: temp.pop(SIGNATURE_KEY) tstr = MakeString(temp) # Sign it. signed_value = base64(Crypto.sign(key, tstr, "sha256")) # And now set the signature self._signature = signed_value return
def signService(): if request.method == 'POST': params = request.form else: params = request.args kv_array = [] for param in params: kv = '%s=%s' % (param, params[param]) kv_array.append(kv) content = "&".join(sorted(kv_array)) key = crypto.load_privatekey(crypto.FILETYPE_PEM, open("rsa_private_key.pem").read()) sign_string = crypto.sign(key, content, 'sha1') sign64 = base64.b64encode(sign_string) sign_encoded = quote(sign64) print "content: " + content print "sign: " + sign_encoded return sign_encoded
def priv_sign(signed, length): # 私钥签名验证auth载荷 #ID initiator 载荷 RealMessage1 = signed[:length] Nr = signed[length:length + 32] length += 32 sk_pi = signed[length:length + 32] length += 32 InitIDPayload = signed[length:len(signed)] MACedIDForI = a2b_hex( hmac.new(sk_pi, InitIDPayload, digestmod=hashlib.sha256).hexdigest()) #hash值 #整个IKE数据包 InitiatorSignedOctets = RealMessage1 + Nr + MACedIDForI #签名内容 key = load_privatekey(FILETYPE_PEM, open("/home/sjx/桌面/clientkey.pem").read(), '123456') AuthenticationPayloadOfInitiator = sign(key, InitiatorSignedOctets, 'sha256') # 签名值 return AuthenticationPayloadOfInitiator, InitiatorSignedOctets #####测试
def sign(private_key, data, digest=SHA256): ''' An internal helper method to sign the 'data' with the 'private_key'. @type private_key: C{str} @param private_key: The private key used to sign the 'data', in one of supported formats. @type data: C{str} @param data: The data that needs to be signed. @type digest: C{str} @param digest: Digest is a str naming a supported message digest type, for example 'sha256'. @rtype: C{str} @return: Signed string. ''' # Convert private key in arbitrary format into DER (DER is binary format # so we get rid of \n / \r\n differences, and line breaks in PEM). if isinstance(private_key, crypto.PKey): pkey = private_key else: pkey = _load_private_key(_extract_certificate(private_key)) return crypto.sign(pkey, data, digest)