def load_verifying_key(verifying_key, crypto_backend=default_backend()): """ Optional: crypto backend object from the "cryptography" python library """ if isinstance(verifying_key, EllipticCurvePublicKey): return verifying_key elif isinstance(verifying_key, (str, unicode)): if is_hex(verifying_key): try: public_key_pem = ECPublicKey(verifying_key).to_pem() except: pass else: try: return load_pem_public_key( public_key_pem, backend=crypto_backend) except Exception as e: traceback.print_exc() raise InvalidPublicKeyError() try: return load_der_public_key( verifying_key, backend=crypto_backend) except: raise InvalidPublicKeyError() else: try: return load_pem_public_key( verifying_key, backend=crypto_backend) except Exception as e: raise InvalidPublicKeyError() else: raise ValueError('Verifying key must be in string or unicode format.')
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
def sns_certificate(sns_privatekey, sns_publickey): one_day = datetime.timedelta(1, 0, 0) private_key = load_pem_private_key( sns_privatekey, password=None, backend=default_backend() ) public_key = load_pem_public_key(sns_publickey, backend=default_backend()) builder = x509.CertificateBuilder() builder = builder.subject_name( x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "sns.amazonaws.com")]) ) builder = builder.issuer_name( x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "sns.amazonaws.com")]) ) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + one_day) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(public_key) builder = builder.add_extension( x509.SubjectAlternativeName([x509.DNSName("sns.amazonaws.com")]), critical=False ) builder = builder.add_extension( x509.BasicConstraints(ca=False, path_length=None), critical=True ) cert = builder.sign( private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend() ) return cert.public_bytes(Encoding.PEM)
def oracle_get_metadata(): public_key_pem = settings.app.oracle_public_key private_key_pem = settings.app.oracle_private_key public_key = load_pem_public_key( public_key_pem.encode(), default_backend()) fingerprint = hashlib.md5() fingerprint.update(public_key.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo, )) fingerprint = fingerprint.hexdigest() fingerprint = ':'.join(fingerprint[i:i + 2] for i in range(0, 32, 2)) output = subprocess.check_output(['oci-metadata', '--json']) metadata = json.loads(output) return { 'user_ocid': settings.app.oracle_user_ocid, 'private_key': private_key_pem, 'fingerprint': fingerprint, 'region_name': metadata['instance']['canonicalRegionName'], 'tenancy_ocid': metadata['instance']['compartmentId'], 'compartment_ocid': metadata['instance']['compartmentId'], 'vnic_ocid': metadata['vnics'][0]['vnicId'], }
def travis_encrypt(self, token_to_encrypt): """ return encrypted version of token_to_encrypt """ # token_to_encrypt has to be string # if's not, assume it's unicode and enconde in utf-8 if isinstance(token_to_encrypt, unicode): token_string = token_to_encrypt.encode('utf-8') else: token_string = token_to_encrypt repo_public_key_text = self.public_key_for_travis_repo() pubkey = repo_public_key_text.encode('utf-8') if 'BEGIN PUBLIC KEY' in pubkey: repo_public_key = serialization.load_pem_public_key(pubkey, backend=default_backend()) elif 'BEGIN RSA PUBLIC KEY' in pubkey: # http://stackoverflow.com/a/32804289 b64data = '\n'.join(pubkey.splitlines()[1:-1]) derdata = base64.b64decode(b64data) repo_public_key = serialization.load_der_public_key(derdata, default_backend()) else: raise Exception ('cannot parse repo public key') ciphertext = repo_public_key.encrypt( token_string, padding.PKCS1v15() ) return base64.b64encode(ciphertext)
def generate_certificate_signing_request( ctx, slot, pin, public_key, csr_output, subject): """ Generate a Certificate Signing Request (CSR). A private key need to exist in the slot. \b SLOT PIV slot where the private key is stored. PUBLIC-KEY File containing a public key. Use '-' to use stdin. CSR File to write CSR to. Use '-' to use stdout. """ controller = ctx.obj['controller'] _verify_pin(ctx, controller, pin) data = public_key.read() public_key = serialization.load_pem_public_key( data, default_backend()) try: csr = controller.generate_certificate_signing_request( slot, public_key, subject, touch_callback=prompt_for_touch) except APDUError: ctx.fail('Certificate Signing Request generation failed.') csr_output.write(csr.public_bytes(encoding=serialization.Encoding.PEM))
def generate_certificate( ctx, slot, management_key, pin, public_key, subject, valid_days): """ Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key need to exist in the slot. \b SLOT PIV slot where private key is stored. PUBLIC-KEY File containing a public key. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=True) data = public_key.read() public_key = serialization.load_pem_public_key( data, default_backend()) now = datetime.datetime.now() valid_to = now + datetime.timedelta(days=valid_days) try: controller.generate_self_signed_certificate( slot, public_key, subject, now, valid_to, touch_callback=prompt_for_touch) except APDUError as e: logger.error('Failed to generate certificate for slot %s', slot, exc_info=e) ctx.fail('Certificate generation failed.')
def create_proxy_credentials(issuer_cred, public_key, lifetime_hours): """ Given an issuer credentials PEM file in the form of a string, a public_key string from an activation requirements document, and an int for the proxy lifetime, returns credentials as a unicode string in PEM format containing a new proxy certificate and an extended proxy chain. """ # parse the issuer credential loaded_cert, loaded_private_key, issuer_chain = parse_issuer_cred(issuer_cred) # load the public_key into a cryptography object loaded_public_key = serialization.load_pem_public_key( public_key.encode("ascii"), backend=default_backend() ) # check that the issuer certificate is not an old proxy # and is using the keyUsage section as required confirm_not_old_proxy(loaded_cert) validate_key_usage(loaded_cert) # create the proxy cert cryptography object new_cert = create_proxy_cert( loaded_cert, loaded_private_key, loaded_public_key, lifetime_hours ) # extend the proxy chain as a unicode string extended_chain = loaded_cert.public_bytes(serialization.Encoding.PEM).decode( "ascii" ) + six.u(issuer_chain) # return in PEM format as a unicode string return ( new_cert.public_bytes(serialization.Encoding.PEM).decode("ascii") + extended_chain )
def _get_secret_data(self, secret): """Retrieves the secret data. Converts the Barbican secret to bytes suitable for a Castellan object. If the secret is a public key, private key, or certificate, the secret is expected to be in PEM format and will be converted to DER. :param secret: the secret from barbican with the payload of data :returns: the secret data """ if secret.secret_type == "public": key = serialization.load_pem_public_key(secret.payload, backend=backends.default_backend()) return key.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo ) elif secret.secret_type == "private": key = serialization.load_pem_private_key(secret.payload, backend=backends.default_backend(), password=None) return key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ) elif secret.secret_type == "certificate": cert = cryptography_x509.load_pem_x509_certificate(secret.payload, backend=backends.default_backend()) return cert.public_bytes(encoding=serialization.Encoding.DER) else: return secret.payload
def _pubkey_handshake(self, srv_privkey, client_pubkeys): modp_group = DH_GROUP #private exponent srv_dh_privkey = int(os.urandom(modp_group["q_size"]+1).encode('hex'), 16) srv_dh_privkey = srv_dh_privkey % modp_group["q"] #public key srv_dh_pubkey_int = pow(modp_group["g"], srv_dh_privkey, modp_group["p"]) srv_dh_pubkey = "{1:0{0}x}".format(modp_group['p_size']*2, srv_dh_pubkey_int) srv_dh_pubkey = srv_dh_pubkey.decode('hex') msg = self.recv_msg() if msg["type"] != "pubkey_client_hello": raise SecSocketException("Handshake failed.") ctl_identity = msg["identity"] try: ctl_pubkey = load_pem_public_key(msg["ctl_pubkey"], backend) except: raise SecSocketException("Handshake failed.") local_ctl_pubkey = client_pubkeys[ctl_identity] if not self._cmp_pub_keys(local_ctl_pubkey, ctl_pubkey): raise SecSocketException("Handshake failed.") ctl_dh_pubkey = msg["ctl_pub_dh"] signature = msg["signature"] if not self._verify_signature(local_ctl_pubkey, ctl_dh_pubkey, signature): raise SecSocketException("Handshake failed.") ctl_dh_pubkey_int = int(ctl_dh_pubkey.encode('hex'), 16) srv_pubkey = srv_privkey.public_key() srv_pubkey_pem = srv_pubkey.public_bytes( encoding=ser.Encoding.PEM, format=ser.PublicFormat.SubjectPublicKeyInfo) signature = self._sign_data(srv_dh_pubkey, srv_privkey) msg = {"type": "pubkey_server_hello", "srv_pubkey": srv_pubkey_pem, "srv_pub_dh": srv_dh_pubkey, "signature": signature} self.send_msg(msg) ZZ = pow(ctl_dh_pubkey_int, srv_dh_privkey, modp_group["p"]) ZZ = "{1:0{0}x}".format(modp_group['p_size']*2, ZZ) ZZ = self._master_secret.decode('hex') self._master_secret = self.PRF(ZZ, "master secret", self._ctl_random + self._slave_random, 48) self._init_cipher_spec() self._send_change_cipher_spec()
def rsa_encrypt(data, pem, b64_encode=True): """ rsa 加密 :param data: 待加密字符串/binary :param pem: RSA public key 内容/binary :param b64_encode: 是否对输出进行 base64 encode :return: 如果 b64_encode=True 的话,返回加密并 base64 处理后的 string;否则返回加密后的 binary """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding encoded_data = to_binary(data) pem = to_binary(pem) public_key = serialization.load_pem_public_key(pem, backend=default_backend()) encrypted_data = public_key.encrypt( encoded_data, padding=padding.OAEP( mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None, ) ) if b64_encode: encrypted_data = base64.b64encode(encrypted_data).decode('utf-8') return encrypted_data
def getPublicKey(registry=None): ''' Return the user's public key (generating and saving a new key pair if necessary) ''' registry = registry or Registry_Base_URL pubkey_pem = None if _isPublicRegistry(registry): pubkey_pem = settings.getProperty('keys', 'public') else: for s in _getSources(): if _sourceMatches(s, registry): if 'keys' in s and s['keys'] and 'public' in s['keys']: pubkey_pem = s['keys']['public'] break if not pubkey_pem: pubkey_pem, privatekey_pem = _generateAndSaveKeys() else: # settings are unicode, we should be able to safely decode to ascii for # the key though, as it will either be hex or PEM encoded: pubkey_pem = pubkey_pem.encode('ascii') # if the key doesn't look like PEM, it might be hex-encided-DER (which we # used historically), so try loading that: if b'-----BEGIN PUBLIC KEY-----' in pubkey_pem: pubkey = serialization.load_pem_public_key(pubkey_pem, default_backend()) else: pubkey_der = binascii.unhexlify(pubkey_pem) pubkey = serialization.load_der_public_key(pubkey_der, default_backend()) return _pubkeyWireFormat(pubkey)
def __init__(self, secret, algorithm=None): if algorithm is None: algorithm = DEFAULT_SIGN_ALGORITHM assert algorithm in ALGORITHMS, "Unknown algorithm" if isinstance(secret, six.string_types): secret = secret.encode("ascii") self._rsa_public = None self._rsa_private = None self._hash = None self.sign_algorithm, self.hash_algorithm = algorithm.split('-') if self.sign_algorithm == 'rsa': try: self._rsahash = HASHES[self.hash_algorithm] self._rsa_private = serialization.load_pem_private_key(secret, None, backend=default_backend()) self._rsa_public = self._rsa_private.public_key() except ValueError as e: try: self._rsa_public = serialization.load_pem_public_key(secret, backend=default_backend()) except ValueError as e: raise HttpSigException("Invalid key.") elif self.sign_algorithm == 'hmac': self._hash = hmac.HMAC(secret, HASHES[self.hash_algorithm](), backend=default_backend())
def load(cls, data=None, filename=None): if filename is not None: with open(filename, 'rb') as fh: data = fh.read() public_key = serialization.load_pem_public_key( data, default_backend()) return PublicKey(public_key)
def from_string(cls, public_key): """Construct an Verifier instance from a public key or public certificate string. Args: public_key (Union[str, bytes]): The public key in PEM format or the x509 public key certificate. Returns: Verifier: The constructed verifier. Raises: ValueError: If the public key can't be parsed. """ public_key_data = _helpers.to_bytes(public_key) if _CERTIFICATE_MARKER in public_key_data: cert = cryptography.x509.load_pem_x509_certificate( public_key_data, _BACKEND) pubkey = cert.public_key() else: pubkey = serialization.load_pem_public_key( public_key_data, _BACKEND) return cls(pubkey)
def encrypt(data, symmetric_key=None, public_key=None): """ Encrypts data with symmetric key or public key. """ if symmetric_key is not None: if public_key is not None: raise ValueError( "Either a symmetric or a public key is required, not both." ) fernet = Fernet(symmetric_key) return fernet.encrypt(data) elif public_key is not None: public_key_obj = load_pem_public_key( data=public_key, backend=default_backend() ) return public_key_obj.encrypt( data, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) ) else: raise ValueError("Either a symmetric or a public key is required.")
def __init__(self, apiHost, applicationId): self.apiHost = apiHost self.applicationId = applicationId if self.debug == True: httplib.HTTPConnection.debuglevel = 1 logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True with open(PRIVATE_KEY_FILE, 'r') as rsa_priv_file: self.rsaPrivateKey = load_pem_private_key(ensure_bytes(rsa_priv_file.read()), password=None, backend=default_backend()) with open(PUBLIC_KEY_FILE, 'r') as rsa_pub_file: self.rsaPublicKey = load_pem_public_key(ensure_bytes(rsa_pub_file.read()), backend=default_backend()) with open(POYNT_PUBLIC_KEY_FILE, 'r') as rsa_poynt_pub_file: self.rsaPoyntPublicKey = load_pem_public_key(ensure_bytes(rsa_poynt_pub_file.read()), backend=default_backend())
def decode_public_key(self, encoded): """ Based on spotnab, this is the gzipped version of the key with base64 applied to it. We decode it and load it. """ fileobj = StringIO() try: fileobj.write(b64decode(encoded)) except TypeError: return False fileobj.seek(0L, SEEK_SET) self.public_key = None with GzipFile(fileobj=fileobj, mode="rb") as f: try: self.public_key = serialization.load_pem_public_key( f.read(), backend=default_backend() ) except ValueError: # Could not decrypt content return False if not self.public_key: return False return True
def test_public_bytes_openssh(self, backend): _skip_curve_unsupported(backend, ec.SECP192R1()) _skip_curve_unsupported(backend, ec.SECP256R1()) key_bytes = load_vectors_from_file( os.path.join( "asymmetric", "PEM_Serialization", "ec_public_key.pem" ), lambda pemfile: pemfile.read(), mode="rb" ) key = serialization.load_pem_public_key(key_bytes, backend) ssh_bytes = key.public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH ) assert ssh_bytes == ( b"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAy" b"NTYAAABBBCS8827s9rUZyxZTi/um01+oIlWrwLHOjQxRU9CDAndom00zVAw5BRrI" b"KtHB+SWD4P+sVJTARSq1mHt8kOIWrPc=" ) key = ec.generate_private_key(ec.SECP192R1(), backend).public_key() with pytest.raises(ValueError): key.public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH )
def test_encode_decode_with_ecdsa_sha512(self): # PEM-formatted EC key with open('tests/testkey_ec', 'r') as ec_priv_file: priv_eckey = load_pem_private_key(ensure_bytes(ec_priv_file.read()), password=None, backend=default_backend()) jwt_message = jwt.encode(self.payload, priv_eckey, algorithm='ES512') with open('tests/testkey_ec.pub', 'r') as ec_pub_file: pub_eckey = load_pem_public_key(ensure_bytes(ec_pub_file.read()), backend=default_backend()) assert jwt.decode(jwt_message, pub_eckey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_eckey, *load_output) # string-formatted key with open('tests/testkey_ec', 'r') as ec_priv_file: priv_eckey = ec_priv_file.read() jwt_message = jwt.encode(self.payload, priv_eckey, algorithm='ES512') with open('tests/testkey_ec.pub', 'r') as ec_pub_file: pub_eckey = ec_pub_file.read() assert jwt.decode(jwt_message, pub_eckey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_eckey, *load_output)
def MsgRecvSequence(dynamic_socket, peerAdd, dataRecv): print "MsgRecvSequence" comm_private_key = None comm_public_key = None try: (peername, comm_private_key, comm_public_key) = AuthSequenceB(dynamic_socket, peerAdd, dataRecv) # Decrypt msg and output it on console if comm_private_key == None or comm_public_key == None: print "MsgRecvSequence Error" return (dataRecv, addr) = dynamic_socket.recvfrom(4096) comm_public_key = serialization.load_pem_public_key( comm_public_key, backend=default_backend() ) comm_private_key = serialization.load_pem_private_key( comm_private_key, password=None, backend=default_backend() ) msg = decryptSendMsg(dataRecv, comm_private_key, comm_public_key) print "Message Recieved From "+peername+" : " print msg except socket.timeout: print "socket timeout" except: print "Unexpected error:", sys.exc_info()[0] finally: dynamic_socket.close()
def deserialize_pk(pk_s): if isinstance(pk_s, (bytes, basestring, unicode)): return serialization.load_pem_public_key( bytes(pk_s), backend=default_backend() ) else: return pk_s
def build_pubkey(pubkeystr): """ Build an EC public key from stored string """ # Build the public key from PEM format pubkey = load_pem_public_key(bytes(pubkeystr, 'utf-8'), backend=default_backend()) return pubkey
def encrypt_variable(variable, build_repo, public_key=None): """ Encrypt an environment variable for ``build_repo`` for Travis ``variable`` should be a bytes object, of the form ``b'ENV=value'``. ``build_repo`` is the repo that ``doctr deploy`` will be run from. It should be like 'gforsyth/doctr'. ``public_key`` should be a pem format public key, obtained from Travis if not provided. """ if not isinstance(variable, bytes): raise TypeError("variable should be bytes") if not b"=" in variable: raise ValueError("variable should be of the form 'VARIABLE=value'") if not public_key: # TODO: Error handling r = requests.get('https://api.travis-ci.org/repos/{build_repo}/key'.format(build_repo=build_repo), headers={'Accept': 'application/vnd.travis-ci.2+json'}) r.raise_for_status() public_key = r.json()['key'] public_key = public_key.replace("RSA PUBLIC KEY", "PUBLIC KEY").encode('utf-8') key = serialization.load_pem_public_key(public_key, backend=default_backend()) pad = padding.PKCS1v15() return base64.b64encode(key.encrypt(variable, pad))
def Deserialize_Pub_Key(key_bytes): deserialized_pub_key = serialization.load_pem_public_key( key_bytes, backend=default_backend()) if isinstance(deserialized_pub_key, rsa.RSAPublicKey) != True: raise RuntimeError ("Invalid Public key file") else: return deserialized_pub_key
def serialize_public_keys(key): backend = default_backend() try: key = serialization.load_pem_public_key(key, backend) return key except Exception as e: print "An error occured while serializing the public keys! %s" %e sys.exit()
def test_public_bytes_pkcs1_unsupported(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) key = load_vectors_from_file( os.path.join("asymmetric", "PEM_Serialization", "ec_public_key.pem"), lambda pemfile: serialization.load_pem_public_key(pemfile.read().encode(), backend), ) with pytest.raises(ValueError): key.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.PKCS1)
def test_public_bytes_invalid_encoding(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) key = load_vectors_from_file( os.path.join("asymmetric", "PEM_Serialization", "ec_public_key.pem"), lambda pemfile: serialization.load_pem_public_key(pemfile.read().encode(), backend), ) with pytest.raises(TypeError): key.public_bytes("notencoding", serialization.PublicFormat.SubjectPublicKeyInfo)
def validateHubPubKey(doc): if not doc['value']: raise ValidationException( 'PUB_KEY must not be empty.', 'value') key = doc['value'] if isinstance(key, six.string_types): key = key.encode('utf-8') try: serialization.load_pem_public_key( key, backend=default_backend() ) except ValueError: raise ValidationException( "PUB_KEY's data structure could not be decoded.") except UnsupportedAlgorithm: raise ValidationException( "PUB_KEY's type is not supported.")
def load_public_key(self, public_key_pem_export): public_key_pem_export = (bytes(public_key_pem_export, encoding='utf8') if not isinstance(public_key_pem_export, bytes) else public_key_pem_export) return serialization.load_pem_public_key( data=public_key_pem_export, backend=default_backend() )
def process(self, msg): # Contador de mensagens aumenta self.msg_count += 1 # Se receber mensagem vazia, assume que o cliente se desconectou ou teve um # problema com a mensagem recebida (assinatura inválida, confidencialidade # comprometida, etc.) if len(msg) <= 0: return None # Se receber a 1ª mensagem, trata-se da chave pública de DH do cliente elif self.msg_count == 0: print('> Client #{} [{}] sent its public key.'.format( self.id, self.msg_count)) # Chave pública de DH do cliente cl_key_public_dh_bytes = msg cl_key_public_dh = load_pem_public_key(cl_key_public_dh_bytes, backend=default_backend()) # Chave partilhada (gerada a partir da chave privada de DH do servidor e da # pública do cliente) key_shared = sv_key_private_dh.exchange(cl_key_public_dh) hkdf = HKDF(algorithm=hashes.SHA256(), length=64, salt=None, info=hkdf_info, backend=default_backend()) # Derivação da chave partilhada key_derived = hkdf.derive(key_shared) # Separação da chave derivada em chave de MAC e chave de encriptação e # desencriptação self.key_mac = key_derived[:32] self.key_enc = key_derived[32:] # Mensagem a assinar, constituida por ambas as chaves públicas de DH self.sig_message = sv_key_public_dh_bytes + cl_key_public_dh_bytes # Assinatura do servidor assinada pela sua chave privade de RSA sv_signature = sv_key_private_rsa.sign( self.sig_message, apadding.PSS(mgf=apadding.MGF1(hashes.SHA256()), salt_length=apadding.PSS.MAX_LENGTH), hashes.SHA256()) print('» Sending my public key, signature and certificate #{}...'. format(self.id)) # Envio da chave pública de DH, da assinatura e do certificado do servidor return sv_key_public_dh_bytes + sv_signature + sv_cert_bytes # Se receber a 2ª mensagem, trata-se da assinatura e da primeria mensagem # encriptada pelo cliente if self.msg_count == 1: print( '> Client #{} [{}] sent its signature and certificate.'.format( self.id, self.msg_count)) # Os primeiros 256 bytes estão reservados para a assinatura do cliente cl_signature = msg[:256] cl_cert_bytes = msg[256:] # Validação do certificado do cliente try: cl_cert_ossl = crypto.load_certificate(crypto.FILETYPE_PEM, cl_cert_bytes) cl_cert = crypto.X509.to_cryptography(cl_cert_ossl) cl_storectx = crypto.X509StoreContext(store, cl_cert_ossl) crypto.X509StoreContext.verify_certificate(cl_storectx) print('» Client #{}\'s certificate accepted!'.format(self.id)) except: print('» Client #{}\'s certificate denied!'.format(self.id)) return None # Chave pública de RSA do cliente cl_key_public_rsa = cl_cert.public_key() # Verificação da assinatura do cliente através da sua chave pública de RSA try: cl_key_public_rsa.verify( cl_signature, self.sig_message, apadding.PSS(mgf=apadding.MGF1(hashes.SHA256()), salt_length=apadding.PSS.MAX_LENGTH), hashes.SHA256()) print('» Client #{}\'s signature accepted!'.format(self.id)) except: print('» Client #{}\'s signature denied!'.format(self.id)) return None my_text = 'Welcome to the chat!' # A partir da 2ª mensagem, trata-se de uma mensagem encriptada pelo cliente elif self.msg_count >= 2: # Separação da mensagem recebida (1ºs 32 bytes formam a tag do MAC, os # restantes formam a mensagem encriptada) msg_tag = msg[:32] msg_enc = msg[32:] # Verificação da tag da mensagem mac_check = unmac(msg_enc, self.key_mac, msg_tag) # Se a integridade da mensagem tiver sido atacada if not mac_check: print( '» Client #{}\'s message\'s integrity compromised!'.format( self.id)) return None else: # Desencriptação da mensagem msg_dec = decrypt(msg_enc, self.key_enc) # Se a confidencialidade da mensagem tiver sido atacada if not msg_dec: print( '» Client #{}\'s message\'s confidentiality compromised!' .format(self.id)) return None else: # Unpadding da mensagem msg = unpad(msg_dec) text = msg.decode() print('> Client #{} [{}]: "{}"'.format(self.id, self.msg_count, text)) # Transformação das letras da mensagem para maiúsculas my_text = text.upper() my_msg = my_text.encode() print('» Input #{}: {}'.format(self.id, my_text)) # Padding da mensagem msg_pad = pad(my_msg) # Encriptação da mensagem msg_enc = encrypt(msg_pad, self.key_enc) # Geração da tag da mensagem msg_tag = mac(msg_enc, self.key_mac) # Concatenação da tag com a mensagem encriptada return msg_tag + msg_enc
def main(): print("|--------------------------------------|") print("| SECURE MEDIA CLIENT |") print("|--------------------------------------|\n") global activesession global cifras global CSUIT global dKey global client_cert #se ainda n existir uma activesession if not activesession: # Get a list of media files print("Contacting Server") #se o que recebermos não é hello quer dizer que nao existe uma sessao aberta server_cert = requests.get(f'{SERVER_URL}/api/certs', cookies=cookies) server_cert = x509.load_pem_x509_certificate(server_cert.content, backend=default_backend()) isVerified = True chain = get_issuers(server_cert, trusted_certs, []) if chain: for cert in chain: if not (verify_signature( trusted_certs[cert.issuer.rfc4514_string()], cert) and verify_dates(cert) and verify_extensions(cert) and verify_crl(cert)): isVerified = False else: isVerified = False if not isVerified: return "ERROR 505" """ pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load("/usr/local/lib/libpteidpkcs11.so") slots = pkcs11.getSlotList() all_attr = list(PyKCS11.CKA.keys()) #Filter attributes all_attr = [e for e in all_attr if isinstance(e, int)] for slot in slots: session = pkcs11.openSession(slot) for obj in session.findObjects(): #Get Object attributes attr = session.getAttributeValue(obj, all_attr) #Create dictionary with attributes attr = dict(zip(map(PyKCS11.CKA.get, all_attr), attr)) print(" Label: ", attr["CKA_LABEL"]) if attr["CKA_CLASS"] == 1: client_cert = x509.load_der_x509_certificate(bytes(attr["CKA_VALUE"]), default_backend()) """ with open("client.crt", "rb") as file: certificate_data = file.read() client_cert = x509.load_pem_x509_certificate( certificate_data, backend=default_backend()) #dizemos hello ao server posting = requests.post( f'{SERVER_URL}/api/hello', cookies=cookies, data=client_cert.public_bytes(encoding=serialization.Encoding.PEM)) #se o que recebermos não é hello quer dizer que nao existe uma sessao aberta if posting.text == "goodbye": return "ERROR 505" elif posting.text != "hello": #recebemos a id da nossa sessao e guardamos como um cookie que queremos enviar nas seguintes comunicações cookies['session_id'] = posting.text #CSUIT negotiation algorithms = ['AES', 'SEED', 'CAST5', 'TripleDES', 'Camellia'] modes = ['CFB', 'CTR', 'OFB'] dg = ['SHA256', 'SHA512', 'SHA3256', 'SHA3512'] code = 0 for alg in algorithms: for mod in modes: for dig in dg: message = alg + '_' + mod + '_' + dig #perguntamos se o server tem esta combinação de CSUIT posting = requests.post(f'{SERVER_URL}/api/csuit', data=message, cookies=cookies) code = posting.status_code #se sim entao determinamos este como o nosso csuit e seguimos em frente if code == 200: CSUIT = message break if code == 200: break if code == 200: break if (code != 200): return #key negotiation # Generate a private key for use in the exchange. private_key = parameters.generate_private_key() # Generate a public key public_key = private_key.public_key() # transform that public key into a readable and sendable object pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) # send public key to the server and receive server public key / all ivs needed for the ciphers posting = requests.post(f'{SERVER_URL}/api/difhell', data=pem, cookies=cookies) info = posting.json() #get ivs ivs = info['ivs'] #get server public key server_public_key = serialization.load_pem_public_key( info['pem'].encode('latin')) # exchange using our private key and the server's public key shared_key = private_key.exchange(server_public_key) # Perform key derivation. derived_key = HKDF(algorithm=hashes.SHA256(), length=96, salt=None, info=b'handshake data').derive(shared_key) # and divide the key into 3 keys with length 32 meaning it will be a 256 length key that can be used as a key # for the ciphers key1 = HKDF(algorithm=hashes.SHA256(), length=16, salt=None, info=b'handshake data').derive(derived_key[0:31]) key2 = HKDF(algorithm=hashes.SHA256(), length=16, salt=None, info=b'handshake data').derive(derived_key[32:63]) key3 = HKDF(algorithm=hashes.SHA256(), length=16, salt=None, info=b'handshake data').derive(derived_key[64:95]) dKey = HKDF(algorithm=hashes.SHA256(), length=16, salt=None, info=b'handshake data').derive(key1 + key2 + key3) # create and save ciphers + hmac cifras += [start_cifra(key1, ivs[0].encode('latin'))] cifras += [start_cifra(key2, ivs[1].encode('latin'))] cifras += [start_hmac(key3)] # set activesession as True cause there is a active session up and running activesession = True #get music list now that we have permission req = requests.get(f'{SERVER_URL}/api/list', cookies=cookies) if req.status_code == 200: print("Got Server List") media_list = json.loads(decifrar(req.content)) # Present a simple selection menu idx = 0 print("MEDIA CATALOG\n") for item in media_list: d = datetime.now() + timedelta(minutes=5) mylicenses[idx] = [1, d.timestamp()] print(f'{idx} - {media_list[idx]["name"]}') idx += idx print("----") while True: selection = input("Select a media file number (q to quit): ") if selection.strip() == 'q': # we can only leave this session with this user when the server receives this encripted message # in case someone steals your id and tries to stop you from staying logged in then he needs to know your keys # and CSUIT to stop you posting = requests.post(f'{SERVER_URL}/api/bye', cookies=cookies, data=client_cert.public_bytes( encoding=serialization.Encoding.PEM)) sys.exit(0) if not selection.isdigit(): continue selection = int(selection) if 0 <= selection < len(media_list): if mylicenses.get(int(selection))[0] == 0 or datetime.now( ).timestamp() > mylicenses.get(int(selection))[1]: continue mylicenses[selection][0] -= 1 print(mylicenses.get(int(selection))[0]) break # Example: Download first file media_item = media_list[selection] print(f"Playing {media_item['name']}") # Detect if we are running on Windows or Linux # You need to have ffplay or ffplay.exe in the current folder # In alternative, provide the full path to the executable if os.name == 'nt': proc = subprocess.Popen(['ffplay.exe', '-i', '-'], stdin=subprocess.PIPE) else: proc = subprocess.Popen(['ffplay', '-i', '-'], stdin=subprocess.PIPE) # Get data from server and send it to the ffplay stdin through a pipe for chunk in range(media_item['chunks'] + 1): #decifrar com rotação de chaves #using dkey para derivar req = requests.get( f'{SERVER_URL}/api/download?id={media_item["id"]}&chunk={chunk}', cookies=cookies) criptedData = json.loads(decifrar(req.content)) if ("error" in criptedData.keys()): break mainDataCipher = start_cifra( dKey, criptedData['iv'].encode('latin')).decryptor() dKey = HKDF(algorithm=hashes.SHA256(), length=16, salt=None, info=b'handshake data').derive(dKey + cifrar(criptedData['data'])) decriptar = start_hmac(dKey).copy() decriptar.update(criptedData['data'].encode('latin')) MAClinha = decriptar.finalize() if (MAClinha != criptedData['HMAC'].encode('latin')): return "ERROR 500" decifrado = mainDataCipher.update( criptedData['data'].encode('latin')) + mainDataCipher.finalize() chunk = json.loads(decifrado.decode('latin')) data = binascii.a2b_base64(chunk['data'].encode('latin')) try: proc.stdin.write(data) except: break proc.stdin.close() proc.kill() proc.terminate()
def test_01_create_token(self): db_token = Token(self.serial1, tokentype="push") db_token.save() token = PushTokenClass(db_token) self.assertEqual(token.token.serial, self.serial1) self.assertEqual(token.token.tokentype, "push") self.assertEqual(token.type, "push") class_prefix = token.get_class_prefix() self.assertEqual(class_prefix, "PIPU") self.assertEqual(token.get_class_type(), "push") # Test to do the 2nd step, although the token is not yet in clientwait self.assertRaises(ParameterError, token.update, {"otpkey": "1234", "pubkey": "1234", "serial": self.serial1}) # Run enrollment step 1 token.update({"genkey": 1}) # Now the token is in the state clientwait, but insufficient parameters would still fail self.assertRaises(ParameterError, token.update, {"otpkey": "1234"}) self.assertRaises(ParameterError, token.update, {"otpkey": "1234", "pubkey": "1234"}) # Unknown config self.assertRaises(ParameterError, token.get_init_detail, params={"firebase_config": "bla"}) fb_config = {FIREBASE_CONFIG.REGISTRATION_URL: "http://test/ttype/push", FIREBASE_CONFIG.JSON_CONFIG: CLIENT_FILE, FIREBASE_CONFIG.TTL: 10, FIREBASE_CONFIG.API_KEY: "1", FIREBASE_CONFIG.APP_ID: "2", FIREBASE_CONFIG.PROJECT_NUMBER: "3", FIREBASE_CONFIG.PROJECT_ID: "4"} # Wrong JSON file self.assertRaises(ConfigAdminError, set_smsgateway, "fb1", u'privacyidea.lib.smsprovider.FirebaseProvider.FirebaseProvider', "myFB", fb_config) # Wrong Project number fb_config[FIREBASE_CONFIG.JSON_CONFIG] = FIREBASE_FILE self.assertRaises(ConfigAdminError, set_smsgateway, "fb1", u'privacyidea.lib.smsprovider.FirebaseProvider.FirebaseProvider', "myFB", fb_config) # Missing APP_ID self.assertRaises(ConfigAdminError, set_smsgateway, "fb1", u'privacyidea.lib.smsprovider.FirebaseProvider.FirebaseProvider', "myFB", {FIREBASE_CONFIG.REGISTRATION_URL: "http://test/ttype/push", FIREBASE_CONFIG.JSON_CONFIG: CLIENT_FILE, FIREBASE_CONFIG.TTL: 10, FIREBASE_CONFIG.API_KEY: "1", FIREBASE_CONFIG.PROJECT_NUMBER: "3", FIREBASE_CONFIG.PROJECT_ID: "4"}) # Missing API_KEY_IOS self.assertRaises(ConfigAdminError, set_smsgateway, "fb1", u'privacyidea.lib.smsprovider.FirebaseProvider.FirebaseProvider', "myFB", {FIREBASE_CONFIG.REGISTRATION_URL: "http://test/ttype/push", FIREBASE_CONFIG.JSON_CONFIG: CLIENT_FILE, FIREBASE_CONFIG.TTL: 10, FIREBASE_CONFIG.APP_ID_IOS: "1", FIREBASE_CONFIG.PROJECT_NUMBER: "3", FIREBASE_CONFIG.PROJECT_ID: "4"}) # Everything is fine fb_config[FIREBASE_CONFIG.PROJECT_ID] = "test-123456" r = set_smsgateway("fb1", u'privacyidea.lib.smsprovider.FirebaseProvider.FirebaseProvider', "myFB", fb_config) self.assertTrue(r > 0) detail = token.get_init_detail(params={"firebase_config": self.firebase_config_name}) self.assertEqual(detail.get("serial"), self.serial1) self.assertEqual(detail.get("rollout_state"), "clientwait") enrollment_credential = detail.get("enrollment_credential") self.assertTrue("pushurl" in detail) self.assertFalse("otpkey" in detail) # Run enrollment step 2 token.update({"enrollment_credential": enrollment_credential, "serial": self.serial1, "fbtoken": "firebasetoken", "pubkey": self.smartphone_public_key_pem_urlsafe}) self.assertEqual(token.get_tokeninfo("firebase_token"), "firebasetoken") self.assertEqual(token.get_tokeninfo("public_key_smartphone"), self.smartphone_public_key_pem_urlsafe) self.assertTrue(token.get_tokeninfo("public_key_server").startswith(u"-----BEGIN RSA PUBLIC KEY-----\n"), token.get_tokeninfo("public_key_server")) parsed_server_pubkey = serialization.load_pem_public_key( to_bytes(token.get_tokeninfo("public_key_server")), default_backend()) self.assertIsInstance(parsed_server_pubkey, RSAPublicKey) self.assertTrue(token.get_tokeninfo("private_key_server").startswith(u"-----BEGIN RSA PRIVATE KEY-----\n"), token.get_tokeninfo("private_key_server")) parsed_server_privkey = serialization.load_pem_private_key( to_bytes(token.get_tokeninfo("private_key_server")), None, default_backend()) self.assertIsInstance(parsed_server_privkey, RSAPrivateKey) detail = token.get_init_detail() self.assertEqual(detail.get("rollout_state"), "enrolled") augmented_pubkey = "-----BEGIN RSA PUBLIC KEY-----\n{}\n-----END RSA PUBLIC KEY-----\n".format( detail.get("public_key")) parsed_stripped_server_pubkey = serialization.load_pem_public_key( to_bytes(augmented_pubkey), default_backend()) self.assertEqual(parsed_server_pubkey.public_numbers(), parsed_stripped_server_pubkey.public_numbers()) remove_token(self.serial1)
def read_from_file(uuid): f = open(os.path.join(KEYS_DIR + str(uuid) + '/pub_rsa'), 'rb') # Read from file payload = serialization.load_pem_public_key(f.read(), default_backend()) return payload
def forward(self, *args, **options): vault_type = options.get('ipavaulttype') if vault_type is None: internal_cmd = self.api.Command.vault_add_internal vault_type = internal_cmd.params.ipavaulttype.default password = options.get('password') password_file = options.get('password_file') public_key = options.get('ipavaultpublickey') public_key_file = options.get('public_key_file') # don't send these parameters to server if 'password' in options: del options['password'] if 'password_file' in options: del options['password_file'] if 'public_key_file' in options: del options['public_key_file'] if vault_type != u'symmetric' and (password or password_file): raise errors.MutuallyExclusiveError( reason=_('Password can be specified only for ' 'symmetric vault')) if vault_type != u'asymmetric' and (public_key or public_key_file): raise errors.MutuallyExclusiveError( reason=_('Public key can be specified only for ' 'asymmetric vault')) if self.api.env.in_server: backend = self.api.Backend.ldap2 else: backend = self.api.Backend.rpcclient if not backend.isconnected(): backend.connect() if vault_type == u'standard': pass elif vault_type == u'symmetric': # get password if password and password_file: raise errors.MutuallyExclusiveError( reason=_('Password specified multiple times')) elif password: pass elif password_file: password = validated_read('password-file', password_file, encoding='utf-8') password = password.rstrip('\n') else: password = self.api.Backend.textui.prompt_password( 'New password') # generate vault salt options['ipavaultsalt'] = os.urandom(16) elif vault_type == u'asymmetric': # get new vault public key if public_key and public_key_file: raise errors.MutuallyExclusiveError( reason=_('Public key specified multiple times')) elif public_key: pass elif public_key_file: public_key = validated_read('public-key-file', public_key_file, mode='rb') # store vault public key options['ipavaultpublickey'] = public_key else: raise errors.ValidationError( name='ipavaultpublickey', error=_('Missing vault public key')) # validate public key and prevent users from accidentally # sending a private key to the server. try: load_pem_public_key(data=public_key, backend=default_backend()) except ValueError as e: raise errors.ValidationError( name='ipavaultpublickey', error=_('Invalid or unsupported vault public key: %s') % e, ) # create vault response = self.api.Command.vault_add_internal(*args, **options) # prepare parameters for archival opts = options.copy() if 'description' in opts: del opts['description'] if 'ipavaulttype' in opts: del opts['ipavaulttype'] if vault_type == u'symmetric': opts['password'] = password del opts['ipavaultsalt'] elif vault_type == u'asymmetric': del opts['ipavaultpublickey'] # archive blank data self.api.Command.vault_archive(*args, **opts) return response
def deserialize_pub_key(pub_key_serialized): return load_pem_public_key(pub_key_serialized)
def process(self, msg): """ Processa uma mensagem (`bytestring`) enviada pelo CLIENTE. Retorna a mensagem a transmitir como resposta (`None` para finalizar ligação) """ self.msg_cnt += 1 if(msg[:1]==b'P'): P = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 G = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 global pn global private_key_dh_server global public_key_server_dh global derived_key pn = dh.DHParameterNumbers(P,G) parameters = pn.parameters(default_backend()) #chave privada do server private_key_dh_server = parameters.generate_private_key() #gerar chave publica public_key = private_key_dh_server.public_key() public_key_server_dh= public_key.public_numbers().y #envia chave publica dh do server res = 'P'+ str(public_key_server_dh) ress = res.encode() msg = ress return msg if(msg[:1]==b'S'): #ler assinatura do cliente vsign = msg[1:257] public_key_cliente_dh = msg[257:565] ''' peerPublicNumbers = dh.DHPublicNumbers(public_key_cliente_dh, pn) peer_key = peerPublicNumbers.public_key(default_backend()) public_key_server_dh_peer = private_key_dh_server.exchange(peer_key) ''' #ver chave publica file do cliente filepub = open("publicKeyCli.pem","rb") public_key_client_file = filepub.read() filepub.close() public_key_client_file_serialization = serialization.load_pem_public_key( public_key_client_file, backend=default_backend() ) #concatenar gxgy = public key dh server + public_key_dh public_key_client gxgy = str(public_key_server_dh).encode() gxy = gxgy + public_key_cliente_dh # verificar assinatura verifySignature(vsign, public_key_client_file_serialization, gxy) #abrir chave privada file do servidor filepriv = open("privateKeySvr.pem","rb") key_private_server_file = filepriv.read() filepriv.close() key_private_server_file_serial = serialization.load_pem_private_key( key_private_server_file, password=None, backend=default_backend() ) #4º - Assina gxgy com priv_servidor signature_Server = key_private_server_file_serial.sign( gxy, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) ''' derived_key = HKDF( algorithm=hashes.SHA512(), length=24, salt=None, info=b'handshake data', backend=default_backend() ).derive(shared_key) ''' #5º - Envia assinaturax msgcomsign = b'm' + signature_Server return msgcomsign if (msg[:1] == b'4'): balhelhe =b'4' print('é seguro falarmos') return balhelhe if (msg[:1] == b'C'): self.msg_cnt += 1 #dividir iv do hmac do texto da mensagem iv_client = msg[1:17] mac_client = msg [17:49] novamensagem = msg[49:] ctp = encriptarcli (keyaes, iv_client, novamensagem) print('%d : %r' % (self.id,ctp)) iv = os.urandom(16) ct = encriptarserver(keyaes, iv, ctp) # hmac da mensagem final= hmacserver(keymac,ct) msgfinal =b'4'+ iv + final + ct return msgfinal if len(msgfinal)>0 else None
deepvault_public_key = deepvault_private_key.public_key() # len == 266 deepvault_public_key_pem_spki = deepvault_public_key.public_bytes( encoding=Encoding.PEM, format=PublicFormat.SubjectPublicKeyInfo).decode() count = 1 # ECDHE ecdh_data = {'pub_key': deepvault_public_key_pem_spki, 'counter': count} count += 1 auth_post = requests.post(deepapi_host + '/auth', headers=headers, data=json.dumps(ecdh_data)) deepapi_public_key = load_pem_public_key(auth_post.json()['pub_key'].encode(), default_backend()) shared_secret = deepvault_private_key.exchange(ec.ECDH(), deepapi_public_key) # challenge-response iv = secrets.token_bytes(16) salt = secrets.token_bytes(32) iterations = 150000 kdf = PBKDF2HMAC( algorithm=SHA512(), length=32, # 32 * 8 = 256 bits salt=salt, iterations=iterations,
backend = default_backend() # load and hash the data to be signed from task 1 #SHA 256 with open("encryptme.txt", 'rb') as file: data_to_encrypt = file.read() myhash = hashes.SHA256() hasher_sha256 = hashes.Hash(myhash, backend) hasher_sha256.update(data_to_encrypt) digest = hasher_sha256.finalize() #load the public key from task 2 with open("ku.pem", 'rb') as file: public_key = serialization.load_pem_public_key(data=file.read(), backend=backend) # Load the signature from the signature file with open("file.sig", 'rb') as file: #get signature from file sig = file.read().split(b"-----BEGIN SIGNATURE-----\n")[1].split( b"\n-----END SIGNATURE-----")[0] print("sig", sig) # unpad using same algorithm # unpad using same algorithm pad = padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH) try: public_key.verify(signature=base64_decode(sig)[0],
def load_public_key(self): with open(os.path.join(self.config['keys']['public key']), 'rb') as k: pub_key = serialization.load_pem_public_key( k.read(), backend=default_backend()) return pub_key
def sendFernet(s, data, fernet_key): pub = data["message"].encode("utf8") client_public = serialization.load_pem_public_key( pub, backend=default_backend()) jsonstr = hubExchange(client_public, fernet_key) s.send(jsonstr)
def handle_echo(reader, writer): global conn_cnt global parameters conn_cnt +=1 #Gerar a chave p = parameters.parameter_numbers().p writer.write(str(p).encode()) yield from writer.drain() g = parameters.parameter_numbers().g writer.write(str(g).encode()) yield from writer.drain() #Enviar a public key private_key = parameters.generate_private_key() public_key = private_key.public_key() public_bytes = public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) writer.write(public_bytes) yield from writer.drain() #Receber a public key dele, assim como a assinatura e o certificado public_key2 = yield from reader.read(3000) partner_pk = load_pem_public_key(public_key2, default_backend()) shared_key = private_key.exchange(partner_pk) assinatura_partner = yield from reader.read(256) certificate_part = yield from reader.read(3000) certificate_part = crypto.load_certificate(crypto.FILETYPE_PEM, certificate_part) if(len(assinatura_partner)!=0): if(verify_chain_of_trust(certificate_part)==True): res = verificar(assinatura_partner,public_bytes, public_key2, certificate_part) if res == 0: writer.write(b"") yield from writer.drain() else: #Enviar a assinatura assim como o certificado do servidor p12 = crypto.load_pkcs12(open("Servidor.p12", 'rb').read(), "1234") assinatura = assinar(public_bytes, public_key2, p12) writer.write(assinatura) yield from writer.drain() certificate = p12.get_certificate() cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, certificate) writer.write(cert_pem) yield from writer.drain() #Gerar a chave aesgcm = AESGCM(shared_key[:32]) srvwrk = ServerWorker(conn_cnt, aesgcm) data = yield from reader.read(100) while True: if data[:1]==b'E': break if not data: continue addr = writer.get_extra_info('peername') res = srvwrk.respond(data[1:], addr) if not res: break res = b'M'+res writer.write(res) yield from writer.drain() data = yield from reader.read(100) print("[%d]" % srvwrk.id) writer.close()
def _store_pub_key(self, context, signer_pubkey, transaction_payload): address = self.make_address_from_data(transaction_payload.public_key) LOGGER.info('Pub key address {}'.format(address)) account_address = AccountHandler.make_address_from_data(signer_pubkey) LOGGER.info('Account address {}'.format(address)) data, account = get_multiple_data(context, [(address, PubKeyStorage), (account_address, Account)]) if data: raise InvalidTransaction('This pub key is already registered.') cert_signer_pubkey = load_pem_public_key( transaction_payload.public_key.encode('utf-8'), backend=default_backend()) try: ehs_bytes = binascii.unhexlify( transaction_payload.entity_hash_signature) eh_bytes = binascii.unhexlify(transaction_payload.entity_hash) except binascii.Error: LOGGER.debug( f'entity_hash_signature {transaction_payload.entity_hash_signature}' ) LOGGER.debug(f'entity_hash {transaction_payload.entity_hash}') raise InvalidTransaction( 'Entity hash or signature not a hex format') # FIXME: For support PKCS1v15 and PSS LOGGER.warn('HAZARD: Detecting padding for verification') sigerr = 0 pkcs = padding.PKCS1v15() pss = padding.PSS(mgf=padding.MGF1(hashes.SHA512()), salt_length=padding.PSS.MAX_LENGTH) for _padding in (pkcs, pss): try: cert_signer_pubkey.verify(ehs_bytes, eh_bytes, _padding, hashes.SHA512()) LOGGER.warn('HAZARD: Padding found: %s', _padding.name) except InvalidSignature: sigerr += 1 if sigerr == 2: raise InvalidTransaction('Invalid signature') valid_from = datetime.fromtimestamp(transaction_payload.valid_from) valid_to = datetime.fromtimestamp(transaction_payload.valid_to) if valid_to - valid_from > PUB_KEY_MAX_VALIDITY: raise InvalidTransaction( 'The public key validity exceeds the maximum value.') data = PubKeyStorage() data.owner = signer_pubkey data.payload.CopyFrom(transaction_payload) data.revoked = False if not account: account = Account() if _get_setting_value(context, 'remme.economy_enabled', 'true').lower() == 'true': if account.balance < PUB_KEY_STORE_PRICE: raise InvalidTransaction( 'Not enough tokens to register a new pub key. Current balance: {}' .format(account.balance)) account.balance -= PUB_KEY_STORE_PRICE if address not in account.pub_keys: account.pub_keys.append(address) return {address: data, account_address: account}
def key_from_pem(self, pem): "Get the EC from a public PEM." return serialization.load_pem_public_key(pem, backend=default_backend())
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization with open('claveLorenzo.pem', 'rb') as key_file: public_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend()) message = b"Nos pegamos?" ciphertext = public_key.encrypt( message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) #OAEP is the recommended choice for any new protocols or applications # PKCS1v15 should only be used to support legacy protocols. print('ciphertext: ', ciphertext) print('ciphertext: ', ciphertext.hex())
def loadKey(key): return serialization.load_pem_public_key(key,backend=default_backend())
def airvpn(self): import base64 import time from xml.etree import ElementTree as et from lxml import etree from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization, hashes, asymmetric, ciphers self.airvpn_servers = {} self.airvpn_protocols = {} self.backend = default_backend() #Those are sent with AES-256-CBC encryption data_params = { "login" : self.username, "password" : self.password, "system" : "linux_x64", "version" : "999" } #Loading public RSA key with open("{}/airvpn_api.pem".format(ROOTDIR), "rb") as pem: rsa_pub_key = serialization.load_pem_public_key( pem.read(), backend=self.backend ) #Generating random AES key self.aes_key = os.urandom(32) self.aes_iv = os.urandom(16) self.cipher = ciphers.Cipher(ciphers.algorithms.AES(self.aes_key), ciphers.modes.CBC(self.aes_iv), backend=self.backend) aes_params = {"key" : self.aes_key, "iv" : self.aes_iv} a = b'' for k,v in aes_params.items(): a = a + base64.b64encode(k.encode('utf-8')) + b':' + base64.b64encode(v) + b'\n' #Encrypting AES key with RSA aes_params_crypt = rsa_pub_key.encrypt(a, asymmetric.padding.PKCS1v15()) data_params["act"] = "user" user_params_crypt = self.encrypt_data_params(data_params) payload = { "s" : base64.b64encode(aes_params_crypt).decode("utf-8"), "d" : base64.b64encode(user_params_crypt).decode("utf-8") } try: cert_xml = self.call_air_api(payload) decrypt_server = self.cipher.decryptor() decrypt_user = self.cipher.decryptor() cert_xml = decrypt_user.update(cert_xml.content) + decrypt_user.finalize() parser = etree.XMLParser(recover=True) cert_xml_root = et.fromstring(cert_xml, parser=parser) self.temp_path = "{}/{}".format(TEMPDIR, self.provider) for a in cert_xml_root.attrib: if cert_xml_root.attrib[a] == "Wrong login/password.": raise ValueError("Wrong credentials") if a != "login" and a != "expirationdate": with open("{}/{}".format(self.temp_path, a), "w") as c: c.write(cert_xml_root.attrib[a]) user_key = cert_xml_root[0][0] for a in user_key.attrib: if a == "crt" or a == "key": with open("{}/{}".format(self.temp_path, a), "w") as c: c.write(user_key.attrib[a]) data_params["act"] = "manifest" data_params["ts"] = "0" server_params_crypt = self.encrypt_data_params(data_params) payload["d"] = base64.b64encode(server_params_crypt).decode("utf-8") server_xml = self.call_air_api(payload) decrypt_server = self.cipher.decryptor() server_xml = decrypt_server.update(server_xml.content) + decrypt_server.finalize() server_xml = server_xml.decode("utf-8").split("</manifest>")[0] + "</manifest>" server_xml_root = et.fromstring(server_xml, parser=parser) for i, child in enumerate(server_xml_root): if child.tag == "modes": modes = i elif child.tag == "servers": servers = i n = 1 for mode in server_xml_root[modes]: try: self.airvpn_protocols["protocol_{}".format(n)] = { "protocol" : mode.attrib["protocol"].upper(), "port" : mode.attrib["port"], "ip" : "ip" + str(int(mode.attrib["entry_index"])+1), "ipv6" : "ipv4" } n+=1 self.airvpn_protocols["protocol_{}".format(n)] = { "protocol" : mode.attrib["protocol"].upper(), "port" : mode.attrib["port"], "ip" : "ip" + str(int(mode.attrib["entry_index"])+1), "ipv6" : "ipv6" } n+=1 except KeyError: pass entry_ips = ["ip1", "ip2", "ip3", "ip4", "ip1_6", "ip2_6", "ip3_6", "ip4_6"] for server in server_xml_root[servers]: try: country = country_translate(server.attrib["country_code"]) self.airvpn_servers[server.attrib["name"]] = { "name" : server.attrib["name"], "provider": "Airvpn", "city": server.attrib["location"], "country" : country, "tunnel" : "OpenVPN" } self.log.emit(("debug", "Importing {}".format(server.attrib["name"]))) ips = server.attrib["ips_entry"].split(",") for index, entry in enumerate(ips): self.airvpn_servers[server.attrib["name"]][entry_ips[index]] = entry except KeyError: pass airvpn_data = { "server" : self.airvpn_servers, "protocol" : self.airvpn_protocols, "provider" : "Airvpn" } self.copy_certs(self.provider) self.finished.emit(airvpn_data) except ValueError as e: self.log.emit(("debug", e)) m = "Airvpn download failed&Perhaps the credentials you entered are wrong&{}".format(self.provider) self.remove_temp_dir(self.provider) self.failed.emit(m) except Exception as e: self.log.emit(("debug", e)) self.log.emit(("info", "Airvpn: Request failed - aborting")) self.remove_temp_dir(self.provider) self.failed.emit("Sorry, something went wrong")
def deserializeKey(key): return load_pem_public_key(key, backend=default_backend())
def deserialize_key(pub_value): return serialization.load_pem_public_key( base64.b64decode(pub_value.encode()), default_backend())
import os from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.serialization import load_pem_public_key from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes import socket # step 1 with open('public_key.pem', 'rb') as f: pem_data = f.read() public_key = load_pem_public_key(pem_data, backend=default_backend()) #print(public_key) #print(type(public_key)) #print(isinstance(public_key, rsa.RSAPublicKey)) #print((public_key.public_numbers().e, public_key.public_numbers().n)) # step 2 random_key = Fernet.generate_key() print('random key is: ', random_key) input_file = 'test.txt' output_file = 'test.encrypted' with open(input_file, 'rb') as f: data = f.read() fernet = Fernet(random_key) encrypted = fernet.encrypt(data) with open(output_file, 'wb') as f:
def read_public(key): """Возвращает публичный ключ""" public_key = serialization.load_pem_public_key(key, backend=default_backend()) return public_key
def setKeys(self, privKey, pubKey): self.privateKey = serialization.load_pem_private_key( bytearray.fromhex(privKey), password=None) self.publicKey = serialization.load_pem_public_key( bytearray.fromhex(pubKey))
def test_02_api_enroll(self): self.authenticate() # Failed enrollment due to missing policy with self.app.test_request_context('/token/init', method='POST', data={"type": "push", "genkey": 1}, headers={'Authorization': self.at}): res = self.app.full_dispatch_request() self.assertNotEqual(res.status_code, 200) error = res.json.get("result").get("error") self.assertEqual(error.get("message"), "Missing enrollment policy for push token: push_firebase_configuration") self.assertEqual(error.get("code"), 303) r = set_smsgateway(self.firebase_config_name, u'privacyidea.lib.smsprovider.FirebaseProvider.FirebaseProvider', "myFB", {FIREBASE_CONFIG.REGISTRATION_URL: "http://test/ttype/push", FIREBASE_CONFIG.TTL: 10, FIREBASE_CONFIG.API_KEY: "1", FIREBASE_CONFIG.APP_ID: "2", FIREBASE_CONFIG.PROJECT_NUMBER: "3", FIREBASE_CONFIG.PROJECT_ID: "test-123456", FIREBASE_CONFIG.JSON_CONFIG: FIREBASE_FILE}) self.assertTrue(r > 0) set_policy("push1", scope=SCOPE.ENROLL, action="{0!s}={1!s}".format(PUSH_ACTION.FIREBASE_CONFIG, self.firebase_config_name)) # 1st step with self.app.test_request_context('/token/init', method='POST', data={"type": "push", "genkey": 1}, headers={'Authorization': self.at}): res = self.app.full_dispatch_request() self.assertEqual(res.status_code, 200) detail = res.json.get("detail") serial = detail.get("serial") self.assertEqual(detail.get("rollout_state"), "clientwait") self.assertTrue("pushurl" in detail) # check that the new URL contains the serial number self.assertTrue("&serial=PIPU" in detail.get("pushurl").get("value")) self.assertTrue("appid=" in detail.get("pushurl").get("value")) self.assertTrue("appidios=" in detail.get("pushurl").get("value")) self.assertTrue("apikeyios=" in detail.get("pushurl").get("value")) self.assertFalse("otpkey" in detail) enrollment_credential = detail.get("enrollment_credential") # 2nd step. Failing with wrong serial number with self.app.test_request_context('/ttype/push', method='POST', data={"serial": "wrongserial", "pubkey": self.smartphone_public_key_pem_urlsafe, "fbtoken": "firebaseT"}): res = self.app.full_dispatch_request() self.assertTrue(res.status_code == 404, res) status = res.json.get("result").get("status") self.assertFalse(status) error = res.json.get("result").get("error") self.assertEqual(error.get("message"), "No token with this serial number in the rollout state 'clientwait'.") # 2nd step. Fails with missing enrollment credential with self.app.test_request_context('/ttype/push', method='POST', data={"serial": serial, "pubkey": self.smartphone_public_key_pem_urlsafe, "fbtoken": "firebaseT", "enrollment_credential": "WRonG"}): res = self.app.full_dispatch_request() self.assertTrue(res.status_code == 400, res) status = res.json.get("result").get("status") self.assertFalse(status) error = res.json.get("result").get("error") self.assertEqual(error.get("message"), "ERR905: Invalid enrollment credential. You are not authorized to finalize this token.") # 2nd step: as performed by the smartphone with self.app.test_request_context('/ttype/push', method='POST', data={"enrollment_credential": enrollment_credential, "serial": serial, "pubkey": self.smartphone_public_key_pem_urlsafe, "fbtoken": "firebaseT"}): res = self.app.full_dispatch_request() self.assertTrue(res.status_code == 200, res) detail = res.json.get("detail") # still the same serial number self.assertEqual(serial, detail.get("serial")) self.assertEqual(detail.get("rollout_state"), "enrolled") # Now the smartphone gets a public key from the server augmented_pubkey = "-----BEGIN RSA PUBLIC KEY-----\n{}\n-----END RSA PUBLIC KEY-----\n".format( detail.get("public_key")) parsed_server_pubkey = serialization.load_pem_public_key( to_bytes(augmented_pubkey), default_backend()) self.assertIsInstance(parsed_server_pubkey, RSAPublicKey) pubkey = detail.get("public_key") # Now check, what is in the token in the database toks = get_tokens(serial=serial) self.assertEqual(len(toks), 1) token_obj = toks[0] self.assertEqual(token_obj.token.rollout_state, u"enrolled") self.assertTrue(token_obj.token.active) tokeninfo = token_obj.get_tokeninfo() self.assertEqual(tokeninfo.get("public_key_smartphone"), self.smartphone_public_key_pem_urlsafe) self.assertEqual(tokeninfo.get("firebase_token"), u"firebaseT") self.assertEqual(tokeninfo.get("public_key_server").strip().strip("-BEGIN END RSA PUBLIC KEY-").strip(), pubkey) # The token should also contain the firebase config self.assertEqual(tokeninfo.get(PUSH_ACTION.FIREBASE_CONFIG), self.firebase_config_name)
""" Created on Fri Mar 24 14:54:11 2017 @author: Pericle """ from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import hashes # Read the public key. filename = raw_input('Type the PEM file containing the EC public key: ') with open(filename, 'rb') as f: pubkey_text = f.read() pubkey = serialization.load_pem_public_key(pubkey_text, backend=default_backend()) # Read the file to verify. filename = raw_input('Type the file to verify: ') with open(filename, 'rb') as f: plaintext = f.read() # Read the signature. filename = raw_input('Type the signature file: ') with open(filename, 'rb') as f: signature = f.read() # Verify the file. pubkey.verify(signature, plaintext, ec.ECDSA(hashes.SHA256())) # If passing here, the verification is ok.
def load_public_key(key_file_path): with open(key_file_path, 'rb') as key_file: return serialization.load_pem_public_key( data=key_file.read(), backend=default_backend())
def main(): command = sys.argv[1] if command in ("generatekey"): path = os.getcwd() print("Choose the key algorithm for your keypair") key_algorithm = input( "1. RSA 2048 2. RSA 4096 3. ECDSA P256 4. ECDSA P384 \n") if int(key_algorithm) == 1: private_key = generate_RSA_private_key(2048) print("RSA 2048 choosed") elif int(key_algorithm) == 2: print("RSA 4096 choosed") private_key = generate_RSA_private_key(4096) elif int(key_algorithm) == 3: print("ECDSA P256") private_key = generate_ECP256_private_key() elif int(key_algorithm) == 4: print("ECDSA P384") private_key = generate_ECP384_private_key() else: print("Please type number between 1-4") sys.exit() key_name = input("Type your key name \n") try: YOUR_DIRECTORY_NAME = key_name + "_key_directory" if not (os.path.isdir(YOUR_DIRECTORY_NAME)): os.makedirs(os.path.join(YOUR_DIRECTORY_NAME)) except OSError as e: if e.errno != errno.EEXIST: print("Failed to create directory!!!!!") raise private_key_path = "./" + YOUR_DIRECTORY_NAME + "/" + key_name + "_private_key.pem" with open(private_key_path, "wb") as key_file: pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) key_file.write(pem) public_key_path = "./" + YOUR_DIRECTORY_NAME + "/" + key_name + "_public_key.pem" with open(public_key_path, "wb") as key_file: public_key = generate_pub_key(private_key) pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) key_file.write(pem) print("Keys are generated in " + YOUR_DIRECTORY_NAME + " directory") elif command in ("generatecsr"): key_path = input("enter your private key pem file path \n:") with open(key_path, "rb") as f: private_key_pem = f.read() private_key = load_pem_private_key(private_key_pem, password=None, backend=default_backend()) print("private key selected") pub_path = input("enter your public key pem file path \n:") with open(pub_path, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) print("publick key selected") country = input("Country Name (2 letter code) [GB]:").capitalize() state = input("State or Province Name (full name) [Berkshire]:") local = input("Locality Name (eg, city) [Newbury]:") organization = input( "Organization Name (eg, company) [My Company Ltd]:") name_of_us = input( "Common Name (eg, your name or your server's hostname) []:") domain_url = input("Domain URL (eg, www.mofas.io) []:") csr = x509.CertificateSigningRequestBuilder().subject_name( x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, country), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state), x509.NameAttribute(NameOID.LOCALITY_NAME, local), x509.NameAttribute(NameOID.ORGANIZATION_NAME, organization), x509.NameAttribute(NameOID.COMMON_NAME, name_of_us), ])).add_extension( x509.SubjectAlternativeName([ # Describe what sites we want this certificate for. x509.DNSName(domain_url), ]), critical=False, # Sign the CSR with our private key. ).sign(private_key, hashes.SHA256(), default_backend()) # Write our CSR out to disk. filepath = os.getcwd() + "/csr.pem" with open(filepath, "wb") as f: f.write(csr.public_bytes(serialization.Encoding.PEM)) print("CSR file save in ", filepath) elif command in ("requestcert"): csr_path = input("enter your csr pem file path \n:") with open(csr_path, "rb") as f: csr_pem = f.read() csr = load_pem_x509_csr(csr_pem, backend=default_backend()) print("csr selected.") print("\n") subject_country = csr.subject.get_attributes_for_oid( NameOID.COUNTRY_NAME)[0].value.capitalize() subject_common_name = csr.subject.get_attributes_for_oid( NameOID.COMMON_NAME)[0].value subject_organization = csr.subject.get_attributes_for_oid( NameOID.ORGANIZATION_NAME)[0].value subject_locality = csr.subject.get_attributes_for_oid( NameOID.LOCALITY_NAME)[0].value subject_state = csr.subject.get_attributes_for_oid( NameOID.STATE_OR_PROVINCE_NAME)[0].value subject = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, subject_country), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, subject_state), x509.NameAttribute(NameOID.LOCALITY_NAME, subject_locality), x509.NameAttribute(NameOID.ORGANIZATION_NAME, subject_organization), x509.NameAttribute(NameOID.COMMON_NAME, subject_common_name), ]) search_dir(os.getcwd()) choosed_CA = input("choose your CA :") path = os.getcwd() + "/" + choosed_CA private_key_path = path + "/private_key.pem" public_key_path = path + "/public_key.pem" with open(private_key_path, "rb") as f: private_key_pem = f.read() CA_private_key = load_pem_private_key(private_key_pem, password=None, backend=default_backend()) print("private key selected") with open(public_key_path, "rb") as key_file: CA_public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) CA_path = path + "/ca.conf" with open(CA_path, "rt") as f: lines = f.readlines() for line in lines: if line.split(':')[0] == "COUNTRY_NAME": print(line.split(':')[1]) issuer_country = line.split(':')[1][:2] elif line.split(':')[0] == "COMMON_NAME": issuer_common_name = line.split(':')[1] elif line.split(':')[0] == "ORGANIZATION_NAME": issuer_organization = line.split(':')[1] elif line.split(':')[0] == "LOCALITY_NAME": issuer_locality = line.split(':')[1] elif line.split(':')[0] == "STATE_OR_PROVINCE_NAME": issuer_state = line.split(':')[1] print("::" + issuer_country + "::") issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, issuer_country), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, issuer_state), x509.NameAttribute(NameOID.LOCALITY_NAME, issuer_locality), x509.NameAttribute(NameOID.ORGANIZATION_NAME, issuer_organization), x509.NameAttribute(NameOID.COMMON_NAME, issuer_common_name), ]) issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, subject_country), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, subject_state), x509.NameAttribute(NameOID.LOCALITY_NAME, subject_locality), x509.NameAttribute(NameOID.ORGANIZATION_NAME, subject_organization), x509.NameAttribute(NameOID.COMMON_NAME, subject_common_name), ]) one_day = datetime.timedelta(1, 0, 0) cert = x509.CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(CA_public_key).serial_number( x509.random_serial_number()).not_valid_before( datetime.datetime.utcnow()).not_valid_after( # Our certificate will be valid for 10 days datetime.datetime.utcnow() + datetime.timedelta(days=3650)).add_extension( x509.SubjectAlternativeName( [x509.DNSName(u"localhost")]), critical=False, # Sign our certificate with our private key ).sign(CA_private_key, hashes.SHA256(), default_backend()) # Write our certificate out to disk. with open('./' + subject_common_name + ".crt", "wb") as f: f.write(cert.public_bytes(encoding=serialization.Encoding.PEM, )) print( "Your certificate has been published, you can have it in the path " + path + '/' + subject_common_name + ".crt")
def rsa_public_pem_to_key(self, pem): public_key = serialization.load_pem_public_key( pem, backend=default_backend()) return public_key
class WayTooDank(BaseException): def __init__(self, message): self.message = message def __repr__(self): return f'<WAYTOODANK {self.message}>' def __str__(self): return repr(self) if _os.path.exists('code_sign_public.pem'): with open('code_sign_public.pem', 'rb') as f: __public_key = load_pem_public_key(f.read(), backend=default_backend()) else: __public_key = None def verify_signed_code(code: str, sign: bytes): if not __public_key: # no public key to load, can't verify, just act like the signature is wrong. return False try: __public_key.verify( sign, bytes(code, 'utf-8'), padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) return True except InvalidSignature:
OIDC_CLIENT_ID = keycloak_conf["client_id"] OIDC_CLIENT_SECRET = keycloak_conf["client_secret"] OIDC_SCOPES = keycloak_conf["scopes"] CRISPY_TEMPLATE_PACK = "bootstrap4" DNSSEC_KEY_LOCATION = "secrets/k.pem" DNSSEC_PUBKEY_LOCATION = "secrets/p.pem" with open(DNSSEC_PUBKEY_LOCATION, "rb") as f: pub_key_data = f.read() with open("domains_jwt_pub.pem", "rb") as f: DOMAINS_JWT_PUB = f.read() DNSSEC_PUBKEY = load_pem_public_key(pub_key_data, backend=default_backend()) if not issubclass(type(DNSSEC_PUBKEY), EllipticCurvePublicKey): raise Exception("Only EC public keys supported") BILLING_URL = "http://*****:*****@localhost:5672/rpc" REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [
def pub_priv_checker(pub_pem_data, key_pem_data, pass_key=None): try: pub_key = serialization.load_pem_public_key(pub_pem_data, backend=default_backend()) except Exception, e: return {'error': False, 'msg': u'公钥内容错误!'}