Export a JWKS as a JSON document.

        :param private: Whether it should be the private keys or the public
        :param issuer: The entity ID.
        :return: A JSON representation of a JWKS
1298
def export_jwks_as_json(self, private=False, issuer=""):
        
        return json.dumps(self.export_jwks(private, issuer))
452577
def raw(self) -> str:
        
        if not isinstance(self.identity, Identity):
            raise MalformedDocumentError("Can not return full certification document created from inline")

        return """Version: {version}
Type: Certification
Currency: {currency}
Issuer: {issuer}
IdtyIssuer: {certified_pubkey}
IdtyUniqueID: {certified_uid}
IdtyTimestamp: {certified_ts}
IdtySignature: {certified_signature}
CertTimestamp: {timestamp}
""".format(version=self.version,
           currency=self.currency,
           issuer=self.pubkey_from,
           certified_pubkey=self.identity.pubkey,
           certified_uid=self.identity.uid,
           certified_ts=self.identity.timestamp,
           certified_signature=self.identity.signatures[0],
           timestamp=self.timestamp)
1034257
def ToJson(self):
        
        jsn = super(RegisterTransaction, self).ToJson()

        asset = {
            'type': self.AssetType,
            'name': self.Name.decode('utf-8'),
            'amount': self.Amount.value,
            'precision': self.Precision if type(self.Precision) is int else self.Precision.decode('utf-8'),
            'owner': self.Owner.ToString(),
            'admin': Crypto.ToAddress(self.Admin)
        }
        jsn['asset'] = asset

        return jsn
1047607
def dump_jwks(kbl, target, private=False):
    

    keys = []
    for kb in kbl:
        keys.extend([k.serialize(private) for k in kb.keys() if
                     k.kty != 'oct' and not k.inactive_since])
    res = {"keys": keys}

    try:
        f = open(target, 'w')
    except IOError:
        (head, tail) = os.path.split(target)
        os.makedirs(head)
        f = open(target, 'w')

    _txt = json.dumps(res)
    f.write(_txt)
    f.close()
489416
def sign_message(payload, private_key)
      signature_urlencoded = ''

      key = OpenSSL::PKey::RSA.new(private_key)

      payload_decoded = CGI::unescape(payload.chomp('decode'))

      signature = key.sign(OpenSSL::Digest::MD5.new, payload_decoded)
      signature_base64 = Base64.strict_encode64(signature)
      signature_urlencoded = "#{CGI::escape(signature_base64)}decode"

      return signature_urlencoded
    end
891006
def _jws_header(keyid, algorithm):
    """"""
    data = {
        'typ': 'JWT',
        'alg': algorithm.name,
        # 'kid' is used to indicate the public part of the key
        # used during signing.
        'kid': keyid
    }

    datajson = json.dumps(data, sort_keys=True).encode('utf8')
    return base64url_encode(datajson)
1075979
def FromJson(json):
        
        type = ContractParameterType.FromString(json['type'])

        value = json['value']
        param = ContractParameter(type=type, value=None)

        if type == ContractParameterType.Signature or type == ContractParameterType.ByteArray:
            param.Value = bytearray.fromhex(value)

        elif type == ContractParameterType.Boolean:
            param.Value = bool(value)

        elif type == ContractParameterType.Integer:
            param.Value = int(value)

        elif type == ContractParameterType.Hash160:
            param.Value = UInt160.ParseString(value)

        elif type == ContractParameterType.Hash256:
            param.Value = UInt256.ParseString(value)

        # @TODO Not sure if this is working...
        elif type == ContractParameterType.PublicKey:
            param.Value = ECDSA.decode_secp256r1(value).G

        elif type == ContractParameterType.String:
            param.Value = str(value)

        elif type == ContractParameterType.Array:
            val = [ContractParameter.FromJson(item) for item in value]
            param.Value = val

        return param
1071027
function exportKs (password, privateKey, salt, iv, type, option = {}) {
  if (!password || !privateKey || !type) {
    throw new Error('Missing parameter! Make sure password, privateKey and type provided')
  }

  if (!crypto.isPrivateKey(privateKey)) {
    throw new Error('given Private Key is not a valid Private Key string');
  }

  salt = salt || util.bytesToHexUpperString(crypto.generateSalt());
  iv = iv || util.bytesToHexUpperString(crypto.generateIv())

  return crypto.marshal(
    crypto.deriveKey(password, salt, option), privateKey,
    util.strToBuffer(salt), util.strToBuffer(iv), type, option
  );
}
925167
def _get_private_key_obj(private_key, passphrase=None):
    '''
    
    '''
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase))
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey
365323
def export(self, private_keys=True):
        
        exp_dict = dict()
        for k, v in iteritems(self):
            if k == 'keys':
                keys = list()
                for jwk in v:
                    keys.append(json_decode(jwk.export(private_keys)))
                v = keys
            exp_dict[k] = v
        return json_encode(exp_dict)
1039835
def serialize_private_key_to_pem(private_key, passphrase_bytes=None):
    
    return private_key.private_bytes(
        encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
        format=cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=cryptography.hazmat.primitives.serialization.BestAvailableEncryption(
            passphrase_bytes
        )
        if passphrase_bytes is not None
        else cryptography.hazmat.primitives.serialization.NoEncryption(),
    )
185568
def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]:
    
    if isinstance(obj, Enum):
        # Properly serialize Enums (such as OpenSslVersionEnum)
        result = obj.name

    elif isinstance(obj, ObjectIdentifier):
        # Use dotted string representation for OIDs
        result = obj.dotted_string

    elif isinstance(obj, x509._Certificate):
        # Properly serialize certificates
        certificate = obj
        result = {  # type: ignore
            # Add general info
            'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'),
            'hpkp_pin': CertificateUtils.get_hpkp_pin(obj),

            # Add some of the fields of the cert
            'subject': CertificateUtils.get_name_as_text(certificate.subject),
            'issuer': CertificateUtils.get_name_as_text(certificate.issuer),
            'serialNumber': str(certificate.serial_number),
            'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"),
            'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"),
            'signatureAlgorithm': certificate.signature_hash_algorithm.name,
            'publicKey': {
                'algorithm': CertificateUtils.get_public_key_type(certificate)
            },
        }

        dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate)
        if dns_alt_names:
            result['subjectAlternativeName'] = {'DNS': dns_alt_names}  # type: ignore

        # Add some info about the public key
        public_key = certificate.public_key()
        if isinstance(public_key, EllipticCurvePublicKey):
            result['publicKey']['size'] = str(public_key.curve.key_size)  # type: ignore
            result['publicKey']['curve'] = public_key.curve.name  # type: ignore
        else:
            result['publicKey']['size'] = str(public_key.key_size)
            result['publicKey']['exponent'] = str(public_key.public_numbers().e)

    elif isinstance(obj, object):
        # Some objects (like str) don't have a __dict__
        if hasattr(obj, '__dict__'):
            result = {}
            for key, value in obj.__dict__.items():
                # Remove private attributes
                if key.startswith('_'):
                    continue

                result[key] = _object_to_json_dict(value)
        else:
            # Simple object like a bool
            result = obj

    else:
        raise TypeError('Unknown type: {}'.format(repr(obj)))

    return result
171875
def ensure_rsa_params(jwk_dict, private):
    """"""
    provided = frozenset(jwk_dict.keys())
    if private is not None and private:
        required = RSA_PUBLIC_REQUIRED | RSA_PRIVATE_REQUIRED
    else:
        required = RSA_PUBLIC_REQUIRED
    return ensure_params('RSA', provided, required)
862608
def ToJson(self):
        
        jsn = super(MinerTransaction, self).ToJson()
        jsn['nonce'] = self.Nonce
        return jsn
748893
def serialize(self, as_private=None):
        
        if as_private is None:
            as_private = self.secret_exponent() is not None
        if self.secret_exponent() is None and as_private:
            raise PublicPrivateMismatchError("public key has no private parts")

        ba = bytearray()
        ba.extend([self._depth])
        ba.extend(self._parent_fingerprint + struct.pack(">L", self._child_index) + self._chain_code)
        if as_private:
            ba += b'\0' + self._secret_exponent_bytes
        else:
            ba += self.sec(is_compressed=True)
        return bytes(ba)
1001568
def create_authentication_from_json(values):
        """"""
        key_id = values.get('publicKey')
        authentication_type = values.get('type')
        if not key_id:
            raise ValueError(
                f'Invalid authentication definition, "publicKey" is missing: {values}')

        authentication = {'type': authentication_type, 'publicKey': key_id}

        return authentication
327531
def _get_deprecated_jwt_issuers():
    
    # If JWT_ISSUERS is not defined, attempt to return the deprecated settings.
    warnings.warn(
        "'JWT_ISSUERS' list not defined, checking for deprecated settings.",
        DeprecationWarning
    )

    return [
        {
            'ISSUER': api_settings.JWT_ISSUER,
            'SECRET_KEY': api_settings.JWT_SECRET_KEY,
            'AUDIENCE': api_settings.JWT_AUDIENCE
        }
    ]