Antzi
Antzi

Reputation: 13444

AES CBC PKCS5Padding Java to Ruby

I have troubles communicating encrypted data between java and ruby. Java => Java works fine Ruby => Ruby works fine Ruby => Java works fine Java => Ruby does not work (Error: wrong final block length).

In java I use this code to encrypt the data, and then post it to a rails server Key size

   static public synchronized String encryptAesData(Context pContext, String pData, byte[] pKey, byte[] pIv) {
        Log.d("", "key size <" + pKey.length + "> iv size <" + pIv.length + ">"); //key size <32> iv size <16>

        AlgorithmParameterSpec paramSpec = new IvParameterSpec(pIv);
        SecretKeySpec key = new SecretKeySpec(pKey, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        byte[] encrypted = cipher.doFinal(pData.getBytes());
        return Base64.encodeToString(encrypted, Base64.DEFAULT);

In ruby I use

encrypted_data = Base64.decode64(raw_data)                                                                                                                                                                  
decipher = OpenSSL::Cipher::AES.new(256, :CBC)                                                                                                                                                              
decipher.decrypt                                                                                                                                                                                            
decipher.key = "censored_key".unpack('A*').pack('H*')# decipher.key.size = 32                                                                                                                               
decipher.iv = "censored_iv".unpack('A*').pack('H*') # decipher.iv.size = 16                                                                                                                                 
plain = decipher.update(encrypted_data) + decipher.final  

And get the error "wrong final block length"

Any idea on how to fix that ?

Upvotes: 0

Views: 1727

Answers (2)

Antzi
Antzi

Reputation: 13444

The code above works just fine. The problem was in the encoding of the base64 sent through a post request.

Upvotes: 0

Jk1
Jk1

Reputation: 11463

I suspect that it may be caused by padding scheme used. PKCS5 pads are of 64 bit (8 byte) block size, but AES-256-CBC uses 16 byte blocks. Therefore, try to use PKCS7 padding for Java side.

Upvotes: 1

Related Questions