簡體   English   中英

如何使用 Python 解密使用 PEM RSA 私鑰加密的 Windows EC2 實例密碼?

[英]How to decrypt Windows EC2 instance password that was encrypted with a PEM RSA private key using Python?

我想使用 Python 使用 PEM RSA 密鑰解密文本。 具體來說,我要解密的文本是get_password_data() boto3 函數返回的加密密碼數據。

我看了這個答案,但它對我不起作用。

我正在使用已安裝的pycryptodome

python3 -m pip install --user pycryptodome

我的密鑰文件是 PEM RSA 私鑰:

$ file my_key.pem
my_key.pem: PEM RSA private key

這是我的代碼,它基於上面鏈接的答案:

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5

encrypted_password = '<redacted>'

rsa_key = RSA.importKey(open('my_key.pem', 'rb').read())
cipher = PKCS1_v1_5.new(rsa_key)
password = cipher.decrypt(encrypted_password) # This line throws the error below
print(f'{password=}')

當我運行它時,我收到以下錯誤消息:

AttributeError: 'PKCS115_SigScheme' object has no attribute 'decrypt'

完整追溯:

Traceback (most recent call last):
  File "/home/shane/src/experimentation/decrypt_password_so_example.py", line 8, in <module>
    password = cipher.decrypt(encrypted_password) # This line throws the error below
AttributeError: 'PKCS115_SigScheme' object has no attribute 'decrypt'

我究竟做錯了什么?

通過挖掘 AWS CLI 源代碼,我找到了基於此函數中代碼的解決方案。

我努力尋找解決方案的原因是 boto3 EC2 文檔沒有解釋返回的PasswordData是 base64 編碼的。

這是我的解決方案(請注意,此解決方案需要rsa 模塊):

import boto3
import base64
import rsa

def decrypt_password_data(password_data, pk_path):
    encrypted_password = password_data['PasswordData']

    with open(pk_path) as pk_file:
        pk_contents = pk_file.read()

    private_key = rsa.PrivateKey.load_pkcs1(pk_contents.encode('latin-1'))
    value = base64.b64decode(encrypted_password)
    value = rsa.decrypt(value, private_key)
    decrypted_password = value.decode('utf-8')

    return decrypted_password

用法,如果您有EC2.Instance對象( password_data()文檔):

password_data = instance.password_data(DryRun=False)
password = decrypt_password_data(password_data, '/path/to/key')

用法,如果您有EC2.Client對象( get_password_data()文檔):

password_data = ec2_client.get_password_data(
    InstanceId='i-1234567',  # Replace as needed
    DryRun=False
)
password = decrypt_password_data(password_data, '/path/to/key')

如果您不需要在 Python 中執行此操作並且您已安裝AWS CLI ,則可以改為此( get-password-data文檔鏈接;請注意,這會輸出一個 JSON 對象):

aws ec2 get-password-data --instance-id <instance_id> --priv-launch-key /path/to/key

請注意 boto3 文檔中的以下內容:

啟動實例時,密碼生成和加密可能需要幾分鍾時間。 如果您嘗試在密碼可用之前檢索密碼,則輸出將返回一個空字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM