Example #1
0
def rsa_key_to_str(private_key: rsa.RSAPrivateKey) -> str:
    """ return RSA private key as string - PEM format, no encryption """
    return private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()
    ).decode()
Example #2
0
def save_private_key(key: rsa.RSAPrivateKey,
                     file_name: Path,
                     passphrase: bytes = None,
                     encoding: str = 'PEM',
                     format: str = 'PKCS8'):
    """
    Save private key to file.
    Default is PEM key in PKCS8 format.

    Parameters
    ----------
    key
        Private key object.
    file_name
        Output file name.
    passphrase
        Passphrase to encrypt file.
    encoding
        Encoding format.
    format
        Output format.
        Values: PKCS8 or TraditionalOpenSSL
    """
    with open(str(file_name), "wb") as outf:
        outf.write(
            key.private_bytes(
                encoding=Encoding[encoding],
                format=PrivateFormat[format],
                encryption_algorithm=serialization.BestAvailableEncryption(
                    password=passphrase),
            ))
Example #3
0
def serialize_privkey(private_key: rsa.RSAPrivateKey) -> bytes:
    """
    Serialize an RSA private into the DER format.
    """
    return private_key.private_bytes(serialization.Encoding.DER,
                                     serialization.PrivateFormat.PKCS8,
                                     serialization.NoEncryption())
Example #4
0
def dump_private_key(key: rsa.RSAPrivateKey) -> bytes:
    """Dump a private key to PEM format (text)

    :param key: The Private Key objec to dump
    :return: The bytes of the private key, as PEM
    """
    return key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
Example #5
0
def get_private_key_pem(private_key: RSAPrivateKey) -> bytes:
    """
    Returns private key PEM file bytes.
    :param private_key: RSPrivateKey
    :return: bytes
    """
    return private_key.private_bytes(  # type: ignore
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
Example #6
0
def write_key(rsa_key: RSAPrivateKey,
              path: PathLike,
              password: Optional[str] = None) -> None:
    try:
        encryption_algorithm = BestAvailableEncryption(password.encode())
    except AttributeError:
        encryption_algorithm = NoEncryption()
    pem = rsa_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8,
                                encryption_algorithm)
    with open(path, 'wb') as file:
        file.write(pem)
Example #7
0
def key_to_bytes(
    key: RSAPrivateKey,
    passphrase: Optional[str] = None,
):
    kwargs = {"encryption_algorithm": serialization.NoEncryption()}
    if passphrase is not None:
        kwargs["encryption_algorithm"] = serialization.BestAvailableEncryption(
            passphrase.encode())
    return key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        **kwargs,
    )
Example #8
0
def _key_to_str(key_object: rsa.RSAPrivateKey) -> str:
    """ Converts a private key object to a string """
    pem = key_object.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())

    key_str = pem.decode()  # type: str
    key_str = key_str[len(_PRIVATE_BEGIN_TAG):]  # remove being tag
    key_str = key_str[:-(len(_PRIVATE_END_TAG) + 1)]  # remove end tag
    key_str = key_str.replace("\n", "")  # remove new lines

    return key_str
Example #9
0
    def private_key(self, private_key: rsa.RSAPrivateKey):
        if self._password is not None:
            enc = serialization.BestAvailableEncryption(self._password)
        else:
            enc = serialization.NoEncryption()

        key_bytes = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=enc)

        with open(os.path.join(self._key_path), 'wb') as fd:
            fd.write(key_bytes)
Example #10
0
async def write_certs(key: rsa.RSAPrivateKey, cert: x509.Certificate,
                      name: str):

    assert len(name) > 0

    with open(f"{name:s}.key", "wb") as f:
        f.write(
            key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption(),  # ?
            ))

    with open(f"{name:s}.crt", "wb") as f:
        f.write(cert.public_bytes(encoding=serialization.Encoding.PEM, ))
Example #11
0
    def encode(self, private_key: RSAPrivateKey) -> bytes:
        private_bytes = private_key.private_bytes(
            encoding=Encoding.PEM,
            format=PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=NoEncryption())

        public_key = private_key.public_key()
        numbers = public_key.public_numbers()
        n = numbers.n.to_bytes(int(public_key.key_size / 8),
                               'big').lstrip(b'\x00')

        kid = sha1(n).hexdigest()

        payload = self.payload()

        return jwt_encode(payload,
                          private_bytes,
                          algorithm='RS256',
                          headers={'kid': kid})
def _save_key(namespace: str, identifier: str, key_pair: rsa.RSAPrivateKey):
    key_dir = pathlib.Path(KEY_STORE_PATH) / namespace / identifier
    os.makedirs(key_dir)

    with open(key_dir / 'id_rsa', 'wb') as f:
        key_binary = key_pair.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()
        )

        f.write(key_binary)

    with open(key_dir / 'id_rsa.pub', 'wb') as f:
        key_binary = key_pair.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        f.write(key_binary)
Example #13
0
def serialize_privkey(private_key: rsa.RSAPrivateKey) -> bytes:
    """
    Serialize an RSA private into the DER format.
    """
    return private_key.private_bytes(serialization.Encoding.DER,
            serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
Example #14
0
File: certs.py Project: hrnciar/pip
def serialize_key(key: rsa.RSAPrivateKey) -> bytes:
    return key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
 def convert_private_key_to_pem(private_key: rsa.RSAPrivateKey) -> str:
     return private_key.private_bytes(
         encoding=serialization.Encoding.PEM,
         format=serialization.PrivateFormat.TraditionalOpenSSL,
         encryption_algorithm=serialization.NoEncryption()).decode()
Example #16
0
def _private_key_to_bytes(private_key: rsa.RSAPrivateKey) -> bytes:
    return private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )