Beispiel #1
0
def _make_root_certificate(
    subject_name: Name,
    days_valid: int,
    private_key: RSAPrivateKeyWithSerialization,
) -> Certificate:
    return (_make_cert_builder(
        subject_name,
        days_valid,
        private_key.public_key(),
    ).issuer_name(subject_name).add_extension(
        SubjectKeyIdentifier.from_public_key(private_key.public_key()),
        critical=False,
    ).add_extension(
        BasicConstraints(
            ca=True,
            path_length=0,
        ),
        critical=True,
    ).add_extension(
        KeyUsage(
            digital_signature=False,
            content_commitment=False,
            key_encipherment=False,
            data_encipherment=False,
            key_agreement=False,
            key_cert_sign=True,
            crl_sign=True,
            encipher_only=False,
            decipher_only=False,
        ),
        critical=True,
    ).sign(
        private_key,
        SHA256(),
    ))
Beispiel #2
0
def _create_key(pkey: RSAPrivateKeyWithSerialization) -> Key:
    privpem = pkey.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    ).decode("utf-8")

    pub = pkey.public_key()  # type: RSAPublicKeyWithSerialization
    pubpem = pub.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo).decode("utf-8")
    return Key(public_key=pubpem, private_key=privpem, key=pkey)
def public_key(private_key: RSAPrivateKeyWithSerialization) -> str:
    _public_key = private_key.public_key()
    public_key_pem = _public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    return public_key_pem.decode()
Beispiel #4
0
 def sign(self, msg: str,
          private_key: RSAPrivateKeyWithSerialization) -> str:
     signed = private_key.sign(msg.encode("ascii"),
                               padding=padding.PSS(
                                   mgf=padding.MGF1(hashes.SHA256()),
                                   salt_length=padding.PSS.MAX_LENGTH),
                               algorithm=hashes.SHA256())
     return binascii.b2a_base64(signed).decode("utf-8")
Beispiel #5
0
def save_key(private_key: RSAPrivateKeyWithSerialization, path: str):
    private_key_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
    with open(path, "wb") as f:
        f.write(private_key_pem)
Beispiel #6
0
 def decrypt(self, encrypted: str,
             private_key: RSAPrivateKeyWithSerialization) -> str:
     original_message = private_key.decrypt(
         binascii.a2b_base64(encrypted),
         padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                      algorithm=hashes.SHA256(),
                      label=None))
     return original_message.decode("utf-8")
def store_key(private_key: RSAPrivateKeyWithSerialization, where: str):
    pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    with open(where, "wb") as key_file:
        os.chmod(where, 0o0600)
        key_file.write(pem)
Beispiel #8
0
def store_key(private_key: RSAPrivateKeyWithSerialization, where: str):
    pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    with open(
        os.open(where, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_TRUNC, 0o0600), "wb"
    ) as key_file:
        key_file.write(pem)
Beispiel #9
0
    def from_crypto(cls, private_key: rsa.RSAPrivateKeyWithSerialization):
        """Convert a cryptography RSAPrivateKey object to an SQLAlchemy model."""
        # type: (type, rsa.RSAPrivateKeyWithSerialization) -> RSAPrivateKey
        m = cls()
        m.pem_data = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption(),
        )

        return m
Beispiel #10
0
    def _prepare_ssl_certificate(
            self, private_key: rsa.RSAPrivateKeyWithSerialization, dns_list,
            expiry_days, **ssl_cert_configs):
        """
        This function generates a self-signed certificate.

        :param private_key: Private_key
        :param dns_list: List of unicode dns names eg. [u"*.seagate.com", u"localhost"]
        :param expiry_days: Period in days for which certificate will be valid, default: 10 yrs
        :kwargs ssl_cert_configs: ssl certificate general configs as below
            country: Country Name
            state: State Name
            locality: Locality Name
            organization: Organization Name
            CN: Common Name
        :return: Self signed certificate
        """
        x509_dns_name_list = []
        for dns_name in dns_list:
            x509_dns_name_list.append(x509.DNSName(dns_name))

        subject = issuer = x509.Name([
            x509.NameAttribute(NameOID.COUNTRY_NAME,
                               ssl_cert_configs.get("country", "IN")),
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME,
                               ssl_cert_configs.get("state", "MH")),
            x509.NameAttribute(NameOID.LOCALITY_NAME,
                               ssl_cert_configs.get("locality", "Pune")),
            x509.NameAttribute(
                NameOID.ORGANIZATION_NAME,
                ssl_cert_configs.get("organization", "Seagate Technology")),
            x509.NameAttribute(NameOID.COMMON_NAME,
                               ssl_cert_configs.get("CN", "seagate.com"))
        ])
        builder = x509.CertificateBuilder()
        builder = builder.subject_name(subject)
        builder = builder.issuer_name(issuer)
        builder = builder.not_valid_before(datetime.datetime.utcnow())
        builder = builder.not_valid_after(datetime.datetime.utcnow() +
                                          datetime.timedelta(days=expiry_days))
        builder = builder.serial_number(x509.random_serial_number())
        builder = builder.public_key(private_key.public_key())
        builder = builder.add_extension(
            x509.SubjectAlternativeName(x509_dns_name_list), critical=False)
        builder = builder.add_extension(x509.BasicConstraints(
            ca=False, path_length=None),
                                        critical=True)

        certificate = builder.sign(private_key=private_key,
                                   algorithm=hashes.SHA256(),
                                   backend=default_backend())
        return certificate
Beispiel #11
0
def _save_cert_chain(
    path_pem: Path,
    certificate_chain: Iterable[Certificate],
    key: RSAPrivateKeyWithSerialization,
) -> None:
    path_pem.parent.mkdir(mode=0o770, parents=True, exist_ok=True)
    with path_pem.open(mode="wb") as f:
        f.write(
            key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8,
                              NoEncryption()))
        for cert in certificate_chain:
            f.write(cert.public_bytes(Encoding.PEM))
    path_pem.chmod(mode=0o660)
Beispiel #12
0
def decrypt(priv_key: rsa.RSAPrivateKeyWithSerialization, msg: bytes) -> bytes:
    """
    Decrypts a message and returns the plain text.

    :param priv_key: RSA private key to decrypt the message with.
    :type priv_key: :class:`rsa.RSAPrivateKeyWithSerialization`
    :param msg: Message to decrypt
    :type msg: bytes
    :return: The decrypted message
    :rtype: :type:`str`
    """
    return priv_key.decrypt(msg, padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(), label=None))
Beispiel #13
0
def sign(private_key: rsa.RSAPrivateKeyWithSerialization, msg: bytes) -> bytes:
    """
    Signs a message with a private key to provide proof of authenticity.

    :param private_key: The private key to sign the message with.
    :type private_key: :class:`rsa.RSAPrivateKeyWithSerialization`
    :param msg: The message to sign.
    :type msg: `str`
    :return: The signature.
    :rtype: `bytes`
    """
    return private_key.sign(msg, padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH),
        hashes.SHA256())
Beispiel #14
0
def ssh_public_key(keypair: rsa.RSAPrivateKeyWithSerialization) -> str:
    """
    converts an rsa keypair to openssh format public key

    :param keypair: keypair.
    :type keypair: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization
    :return: string of public key
    """
    eb = utils.int_to_bytes(keypair.public_key().public_numbers().e)
    nb = utils.int_to_bytes(keypair.public_key().public_numbers().n)
    if eb[0] & 0x80: eb = bytes([0x00]) + eb
    if nb[0] & 0x80: nb = bytes([0x00]) + nb
    keyparts = [b'ssh-rsa', eb, nb]
    keystring = b''.join([struct.pack(">I", len(kp)) + kp for kp in keyparts])
    return str(b'ssh-rsa ' + b64encode(keystring), encoding='utf-8')
Beispiel #15
0
def ssh_public_key(keypair: rsa.RSAPrivateKeyWithSerialization) -> str:
    """
    converts an rsa keypair to openssh format public key

    :param keypair: keypair.
    :type keypair: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization
    :return: string of public key
    """
    eb = utils.int_to_bytes(keypair.public_key().public_numbers().e)
    nb = utils.int_to_bytes(keypair.public_key().public_numbers().n)
    if eb[0] & 0x80: eb = bytes([0x00]) + eb
    if nb[0] & 0x80: nb = bytes([0x00]) + nb
    keyparts = [b'ssh-rsa', eb, nb]
    keystring = b''.join([struct.pack(">I", len(kp)) + kp for kp in keyparts])
    return str(b'ssh-rsa ' + b64encode(keystring), encoding='utf-8')
Beispiel #16
0
 def process_bind_param(self, value: rsa.RSAPrivateKeyWithSerialization,
                        dialect):
     return value.private_bytes(
         encoding=serialization.Encoding.DER,
         format=serialization.PrivateFormat.PKCS8,
         encryption_algorithm=serialization.NoEncryption())
Beispiel #17
0
 def _serialize_private_key(private_key: RSAPrivateKeyWithSerialization) -> bytes:
     return private_key.private_bytes(
         Encoding.PEM,
         PrivateFormat.PKCS8,
         NoEncryption(),
     )
def sign(private_key: RSAPrivateKeyWithSerialization, data: str) -> str:
    signature = private_key.sign(
        data=bytes(data, "utf-8"), padding=padding.PKCS1v15(), algorithm=hashes.SHA256()
    )
    sig = base64.b64encode(signature)
    return sig.decode()
Beispiel #19
0
def dump_key(key: rsa.RSAPrivateKeyWithSerialization) -> bytes:
    return key.private_bytes(
        serialization.Encoding.PEM,
        serialization.PrivateFormat.TraditionalOpenSSL,
        serialization.NoEncryption(),
    )
Beispiel #20
0
def rsa_to_pem(key: rsa.RSAPrivateKeyWithSerialization) -> str:
    return key.private_bytes(encoding=serialization.Encoding.PEM,
                             format=serialization.PrivateFormat.PKCS8,
                             encryption_algorithm=serialization.NoEncryption())