Serialize certificate to DER.

    Args:
      cert_obj: cryptography.Certificate

    Returns:
      bytes: DER encoded certificate
960548
def serialize_cert_to_der(cert_obj):
    
    return cert_obj.public_bytes(
        cryptography.hazmat.primitives.serialization.Encoding.DER
    )
262249
public static javax.security.cert.X509Certificate convert(java.security.cert.X509Certificate cert) {
        try {
            byte[] encoded = cert.getEncoded();
            return javax.security.cert.X509Certificate.getInstance(encoded);
        } catch (java.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateException e) {
        }
        return null;
    }
625688
def raw_repr(obj):
    ''''''
    if isproxy(obj):
        return '<%s with prime_id=%d>' % (obj.__class__.__name__, obj.prime_id)
    else:
        return repr(obj)
580912
def serialize_verifying_key(vk):
    
    if isinstance(vk, ed25519.keys.VerifyingKey):
        pubkey = vk.to_bytes()
        key_type = SSH_ED25519_KEY_TYPE
        blob = util.frame(SSH_ED25519_KEY_TYPE) + util.frame(pubkey)
        return key_type, blob

    if isinstance(vk, ecdsa.keys.VerifyingKey):
        curve_name = SSH_NIST256_CURVE_NAME
        key_blob = SSH_NIST256_DER_OCTET + vk.to_string()
        parts = [SSH_NIST256_KEY_TYPE, curve_name, key_blob]
        key_type = SSH_NIST256_KEY_TYPE
        blob = b''.join([util.frame(p) for p in parts])
        return key_type, blob

    raise TypeError('unsupported {!r}'.format(vk))
228309
def _decrypt_object(obj):
    '''
    
    '''
    if isinstance(obj, six.string_types):
        return _fetch_secret(obj)
    elif isinstance(obj, dict):
        for pass_key, pass_path in six.iteritems(obj):
            obj[pass_key] = _decrypt_object(pass_path)
    elif isinstance(obj, list):
        for pass_key, pass_path in enumerate(obj):
            obj[pass_key] = _decrypt_object(pass_path)
    return obj
1135288
def get_certificate(self, certificate_uid):
        
        certificate_json = self.get_certificate_json(certificate_uid)
        return model.to_certificate_model(certificate_json)
683287
def certclone(chain, copy_extensions=False):

    for i in range(len(chain)):
        chain[i] = chain[i].to_cryptography()

    newchain = []

    '''
    
    '''

    first = True

    for original in chain[::-1]:

        #print(cert)

        key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
            )

        key_pem = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()
        ).decode()

        if first:
            print(key_pem)
            first=False

        pubkey = key.public_key()

        # Todo: Code to mimic the private key type of original cert
        # maybe based on pubkey.__class__
        cert = x509.CertificateBuilder()
        cert = cert.subject_name(original.subject)
        cert = cert.issuer_name(original.issuer)
        #cert = cert.serial_number(original.serial_number)
        cert = cert.serial_number(x509.random_serial_number())
        cert = cert.not_valid_before(original.not_valid_before)
        cert = cert.not_valid_after(original.not_valid_after)
        cert = cert.public_key(pubkey)

        if copy_extensions:
            for ext in original.extensions:
                cert = cert.add_extension(ext.value, critical=ext.critical)

        cert = cert.sign(private_key=key, algorithm=original.signature_hash_algorithm, backend=default_backend())
        cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode()
        print(cert_pem)

        newchain.insert(0, cert)
977445
def decode_cert(cert):
    

    ret_dict = {}
    subject_xname = X509_get_subject_name(cert.value)
    ret_dict["subject"] = _create_tuple_for_X509_NAME(subject_xname)

    notAfter = X509_get_notAfter(cert.value)
    ret_dict["notAfter"] = ASN1_TIME_print(notAfter)

    peer_alt_names = _get_peer_alt_names(cert)
    if peer_alt_names is not None:
        ret_dict["subjectAltName"] = peer_alt_names

    return ret_dict
355338
def encode(self, obj):
        
        if self._is_valid_mysql_bigint(obj):
            return obj, 'i'

        value = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
        value_type = 'p'
        if (
            self._compress_min_length
            and len(value) >= self._compress_min_length
        ):
            value = zlib.compress(value, self._compress_level)
            value_type = 'z'
        return value, value_type
836796
def from_der(der):
        
        d = get_bytes(der)
        # d must conform to (from btcd):
        # [0 ] 0x30      - ASN.1 identifier for sequence
        # [1 ] <1-byte>  - total remaining length
        # [2 ] 0x02      - ASN.1 identifier to specify an integer follows
        # [3 ] <1-byte>  - length of R
        # [4.] <bytes>   - R
        # [..] 0x02      - ASN.1 identifier to specify an integer follows
        # [..] <1-byte>  - length of S
        # [..] <bytes>   - S

        # 6 bytes + R (min. 1 byte) + S (min. 1 byte)
        if len(d) < 8:
            raise ValueError("DER signature string is too short.")
        # 6 bytes + R (max. 33 bytes) + S (max. 33 bytes)
        if len(d) > 72:
            raise ValueError("DER signature string is too long.")
        if d[0] != 0x30:
            raise ValueError("DER signature does not start with 0x30.")
        if d[1] != len(d[2:]):
            raise ValueError("DER signature length incorrect.")

        total_length = d[1]

        if d[2] != 0x02:
            raise ValueError("DER signature no 1st int marker.")
        if d[3] <= 0 or d[3] > (total_length - 7):
            raise ValueError("DER signature incorrect R length.")

        # Grab R, check for errors
        rlen = d[3]
        s_magic_index = 4 + rlen
        rb = d[4:s_magic_index]

        if rb[0] & 0x80 != 0:
            raise ValueError("DER signature R is negative.")
        if len(rb) > 1 and rb[0] == 0 and rb[1] & 0x80 != 0x80:
            raise ValueError("DER signature R is excessively padded.")

        r = int.from_bytes(rb, 'big')

        # Grab S, check for errors
        if d[s_magic_index] != 0x02:
            raise ValueError("DER signature no 2nd int marker.")
        slen_index = s_magic_index + 1
        slen = d[slen_index]
        if slen <= 0 or slen > len(d) - (slen_index + 1):
            raise ValueError("DER signature incorrect S length.")

        sb = d[slen_index + 1:]

        if sb[0] & 0x80 != 0:
            raise ValueError("DER signature S is negative.")
        if len(sb) > 1 and sb[0] == 0 and sb[1] & 0x80 != 0x80:
            raise ValueError("DER signature S is excessively padded.")

        s = int.from_bytes(sb, 'big')

        if r < 1 or r >= bitcoin_curve.n:
            raise ValueError("DER signature R is not between 1 and N - 1.")
        if s < 1 or s >= bitcoin_curve.n:
            raise ValueError("DER signature S is not between 1 and N - 1.")

        return Signature(r, s)
1207066
def pretty_format_cert(cls, cert):
        
        crt = cert.get('cert')
        if crt:
            crt = ('-----BEGIN CERTIFICATE-----\n' +
                   '\n'.join([crt[index * 64:(index + 1) * 64]
                              for index in range(int(len(crt) / 64) + 1)]).rstrip('\n') +  # noqa
                   '\n-----END CERTIFICATE-----')
        return crt
1021682
def from_signed_raw(cls: Type[CertificationType], signed_raw: str) -> CertificationType:
        
        n = 0
        lines = signed_raw.splitlines(True)

        version = int(Identity.parse_field("Version", lines[n]))
        n += 1

        Certification.parse_field("Type", lines[n])
        n += 1

        currency = Certification.parse_field("Currency", lines[n])
        n += 1

        pubkey_from = Certification.parse_field("Issuer", lines[n])
        n += 1

        identity_pubkey = Certification.parse_field("IdtyIssuer", lines[n])
        n += 1

        identity_uid = Certification.parse_field("IdtyUniqueID", lines[n])
        n += 1

        identity_timestamp = BlockUID.from_str(Certification.parse_field("IdtyTimestamp", lines[n]))
        n += 1

        identity_signature = Certification.parse_field("IdtySignature", lines[n])
        n += 1

        timestamp = BlockUID.from_str(Certification.parse_field("CertTimestamp", lines[n]))
        n += 1

        signature = Certification.parse_field("Signature", lines[n])

        identity = Identity(version, currency, identity_pubkey, identity_uid, identity_timestamp, identity_signature)

        return cls(version, currency, pubkey_from, identity, timestamp, signature)
536290
def _TLS_Ext_CertTypeDispatcher(m, *args, **kargs):
    
    tmp_len = struct.unpack("!H", m[2:4])[0]
    if tmp_len == 1:
        cls = TLS_Ext_ServerCertType
    else:
        cls = TLS_Ext_ClientCertType
    return cls(m, *args, **kargs)
809355
def generateCertificate(cls):
        
        key = generate_key()
        cert = generate_certificate(key)
        return cls(key=key, cert=cert)
1253751
def certificate_object(self):
        
        if not self.certificate:
            return None
        self.certificate.seek(0)
        return crypto.parse_certificate(self.certificate.read())
1095935
def object_to_bytes(obj):
    
    if isinstance(obj, str):
        return bytearray(obj, "UTF-8")
    elif isinstance(obj, bool):
        return bytearray()
    elif isinstance(obj, int):
        return pack("<L", obj)
    elif obj is None:
        return bytearray()
    elif isinstance(obj, bytearray):
        return obj
    else:
        return obj.get_raw()
1248434
private function toDer()
    {
        $pattern = '/.*-----BEGIN CERTIFICATE-----(.*)-----END CERTIFICATE-----.*/msU';
        $replacement = '${1}';

        $plainPemData = preg_replace($pattern, $replacement, $this->pemCert);
        if (null === $plainPemData) {
            throw new RuntimeException('unable to extract the encoded DER data from the certificate');
        }

        // create one long string of the certificate which turns it into an
        // encoded DER cert
        $search = array(' ', "\t", "\n", "\r", "\0" , "\x0B");
        $encodedDerCert = str_replace($search, '', $plainPemData);

        return base64_decode($encodedDerCert);
    }