AES encrypted key is too large for decryption using RSA (Java)

I am trying to create a program that encrypts data using AES, then encrypts the AES key using RSA, and then decrypts. However, as soon as I encrypt the AES key, it will go out up to 128 bytes. RSA will allow me to decrypt 117 bytes or less, so when I get to decrypting the AES key, it gives an error.

Relavent code:

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair kpa = kpg.genKeyPair();
    pubKey = kpa.getPublic();
    privKey = kpa.getPrivate();

    updateText("Private Key: " +privKey +"\n\nPublic Key: " +pubKey);

    updateText("Encrypting " +infile);
    //Genereate aes key
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128); // 192/256
    SecretKey aeskey = kgen.generateKey();
    byte[] raw = aeskey.getEncoded();

    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

    updateText("Encrypting data with AES");
    //encrypt data with AES key
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    SealedObject aesEncryptedData = new SealedObject(infile, aesCipher);

    updateText("Encrypting AES key with RSA");
    //encrypt AES key with RSA
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    byte[] encryptedAesKey = cipher.doFinal(raw);

    updateText("Decrypting AES key with RSA. Encrypted AES key length: " +encryptedAesKey.length);
    //decrypt AES key with RSA       
    Cipher decipher = Cipher.getInstance("RSA");
    decipher.init(Cipher.DECRYPT_MODE, privKey);
    byte[] decryptedRaw = decipher.doFinal(encryptedAesKey); //error thrown here because encryptedAesKey is 128 bytes
    SecretKeySpec decryptedSecKey = new SecretKeySpec(decryptedRaw, "AES");

    updateText("Decrypting data with AES");
    //decrypt data with AES key
    Cipher decipherAES = Cipher.getInstance("AES");
    decipherAES.init(Cipher.DECRYPT_MODE, decryptedSecKey);
    String decryptedText = (String) aesEncryptedData.getObject(decipherAES);

    updateText("Decrypted Text: " +decryptedText);

Any idea on how to get around this?

+3
source share
3 answers

Edit: I misunderstood the problem. You must use a larger RSA key, for example RSA 4096 allows 501 bytes to be encrypted.

AES OFB, . , RC4, . RC4, RC4-drop1024, , 1024 . 1024 rc4 , , WEP, WIFI. RC4 , PRNG. , , XOR. AES OFB, RC4 .

, . , AES 128 CBC , 128 . 128 , . , , .

, ECB. , , (IV), -. IV CWE-329.

+1

, . . ,

Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");

Cipher rsa = Cipher.getInstance("RSA/None/PKCS1Padding");

AES 16 128-. RSA.

+2

You can get rid of complexity problems simply by using the Cipher class wrapper mode / function. You can see my source code for an example of how to do this.

+1
source

Source: https://habr.com/ru/post/1743833/


All Articles