Как я могу сгенерировать ключ OpenS SH RSA, используя python из закрытого ключа, хранящегося в диспетчере секретов в AWS? - PullRequest
1 голос
/ 03 августа 2020

У меня есть приведенный ниже код, который генерирует json publi c и частные строки ключа, сгенерированного шпатлевкой и сохраненного в AWS секретном менеджере:

import boto3
import base64
from botocore.exceptions import ClientError
def get_secret():
    secret_name = "Server/Name"
    region_name = "us-west-1"
    # Create a Secrets Manager client
    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name
    )
    # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
    # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
    # We rethrow the exception by default.
    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'DecryptionFailureException':
            # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InternalServiceErrorException':
            # An error occurred on the server side.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            # You provided an invalid value for a parameter.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            # You provided a parameter value that is not valid for the current state of the resource.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'ResourceNotFoundException':
            # We can't find the resource that you asked for.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
    else:
        # Decrypts secret using the associated KMS CMK.
        # Depending on whether the secret is a string or binary, one of these fields will be populated.
        if 'SecretString' in get_secret_value_response:
            secret = get_secret_value_response['SecretString']
        else:
            decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
    return json.loads(secret)

key = get_secret()
print(key)

JSON вывод:

{'Key': 'PuTTY-User-Key-File-2: ssh-rsa Encryption: none Comment: rsa-key-20200608 Public-Lines: 6 AAAAB3NzaC1yc2EAAAABJQAAAQEA9CfhCMQOh0OCjzQsgpceJwklTtKJYOZLpl02 ********publicLines********* 
Private-Lines: 14 r1ePzc1522MZrfWYn3t7sBhLWA26jqMTWeqSkflnW1MMGay8fpkiTpVZPnX7Oe5L +hgkHZSJDgyzHpkA22XqQgi6uAfK7lugTCkYfq3n4xVU3U+ CzNr+kuMxNRoJBOyU ********privateLines*********'}

Но я хочу сгенерировать ключ формата OpenS SH RSA для моих частных строк.

Ожидаемый результат:

-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCtCnvOu+3qxh+mGvejBMsAVDVA/c8C4su1M6q0xPFISwHOQsmP
k3AE2pjwKHOsa0IqxPG39EKrdYhBHB5geMQv3httLIoXzj0oxMEIEhqZ2AgA378D
Qtky91WcZE67KpmWDOXG95FCBZj7PX7XbdwR+Uk4kLhE2Z6vkWDe7st8rQIDAQAB
AoGAakmZOKfogJ/HiuDfoQttobsXpt7/i7dBBwFAZp7d0dj4t/gAFKesU97tt/4w
5wRO9TRZgPORC/46fjvGUN19KyHs3JRhiYrsKVnJNBBpAG1+9pBi+avPR9sxBKG7
HWiSXKRRCddwWpDuyMrzyre+k+mAtulbF6kecBIrSfEBg6ECQQC+Hht9S93CMmiy
YKUiBwMhvbMoYukGGIhB3WSZK28PvYadV2uVAHYCxGq2U1ULJwHWac5OMDzR+J4y
MuxlJT5I0Y4fr4qgkQJARWfPg+l7jPj1csj56r2e1cxhYqamU6rNP3PHjKdzJ5zK
eS87SRFybqd578kFEdfaR+CesRKzXswfDTKoM77wnQ==
-----END RSA PRIVATE KEY-----

1 Ответ

0 голосов
/ 19 августа 2020

Вы можете просто сохранить уже закодированные ключи в виде строки, а не заключать их в JSON. См., Например, аналогичный вопрос о хранении закрытого ключа.

...