Mcrypt blowfish php is slightly different compared to java and .net

Here is an example code with modified key values โ€‹โ€‹and payload:

$key = '/4rTInjwg/H/nA=='; $key = base64_decode($key); $data = 'val=100|val=200|val=300|val=400|val=500|val=600|val=700|val=800|val=900|'; $data.= 'val2=100|val2=200|val2=300|val2=400|val2=500|val2=600|val2=700|val2=800|val2=900|'; $data.= 'val3=100|val3=200|val3=300|val3=400|val3=500|val3=600|val3=700|val3=800|val3=900|'; $data.= 'val4=100|val4=200|val4=300|val4=400|val4=500|val4=600|val4=700|val4=800|val4=900|'; $result = base64_encode(mcrypt_ecb(MCRYPT_BLOWFISH,$key, $data, MCRYPT_ENCRYPT)); 

This encrypts and decrypts in PHP, but Java and .NET come with different meanings, and even worse, I cannot decrypt the results with Java or .NET. When I try to decrypt values โ€‹โ€‹from java, I get a line that starts on the right, but ends with garbage halfway. I work in 5.3x on Windows XP if someone is wondering.

While I am STFW, I noticed a few threads in which recent comments mention that base64 messed up the result due to typing problems, and I wonder what happens because the results are so close, the first 50 or so the characters match. then everything goes to @ # $ !.

I also read a few threads about block size and padding, but no one can agree on what should be padding. I really need to know if Java adds text, what is the default block size, what will the panel be? See below:

Java Developer:

  import org.apache.commons.codec.binary.Base64; import java.util.ResourceBundle; import com.sun.crypto.provider.SunJCE; ... snip ... StringBuffer ourTransferBuffer = new StringBuffer(s); byte abyte0[] = Base64.decodeBase64(encryptionKey); SunJCE sunjce = new SunJCE(); Security.addProvider(sunjce); SecretKeySpec secretkeyspec = new SecretKeySpec(abyte0, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(1, secretkeyspec); byte abyte1[] = cipher.doFinal(ourTransferBuffer.toString().getBytes()); s = Base64.encodeBase64String(abyte1); return s; ... snip ... 

I've already burned too much, who has any ideas? Thanks.

+4
source share
1 answer

It turned out that just pkcs5 padding fixed the problem.

 ... snip ... $data = 'val=100|val=200|val=300|val=400|val=500|val=600|val=700|val=800|val=900|'; $data.= 'val2=100|val2=200|val2=300|val2=400|val2=500|val2=600|val2=700|val2=800|val2=900|'; $data.= 'val3=100|val3=200|val3=300|val3=400|val3=500|val3=600|val3=700|val3=800|val3=900|'; $data.= 'val4=100|val4=200|val4=300|val4=400|val4=500|val4=600|val4=700|val4=800|val4=900|'; $blocksize = mcrypt_get_block_size('blowfish', 'ecb'); // get block size $pkcs = $blocksize - (strlen($data) % $blocksize); // get pkcs5 pad length $data.= str_repeat(chr($pkcs), $pkcs); // append pkcs5 padding to the data // encrypt and encode $res = base64_encode(mcrypt_ecb(MCRYPT_BLOWFISH,$key, $data, MCRYPT_ENCRYPT)); 
+1
source

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


All Articles