Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Encrypted AES key is too large to decrypt

843811Apr 6 2010 — edited May 3 2010
Hello,

I am trying to encrypt some data using AES (128 bit), I then encrypt the AES key using RSA (1024 bit), this results in an ecrypted AES key of 128 bytes, now i am not able to decrypt this key using RSA private key because it is larger than 117 bytes. Is there something i am missing here?
        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 = cipher.doFinal(encryptedAesKey); //error thrown here because encrypted key 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);
Thank you
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 31 2010
Added on Apr 6 2010
6 comments
524 views