Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypted AES key too large to Decrypt with RSA (Java)

I am trying to make a program that Encrypts data using AES, then encrypts the AES key with RSA, and then decrypt. However, once i encrypt the AES key it comes out to 128 bytes. RSA will only allow me to decrypt 117 bytes or less, so when i go to decrypt the AES key it throws 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?

like image 975
Petey B Avatar asked Sep 14 '26 09:09

Petey B


1 Answers

When you use encryption, always specifying padding. Otherwise, your clear-text will be padded to the block size. For example,

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

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

The AES key is only 16 bytes for 128-bit. So it should fit in any RSA block nicely.

like image 155
ZZ Coder Avatar answered Sep 16 '26 21:09

ZZ Coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!