Ruby 3DES implementation against PHP mcrypt, different results

I am trying to port some obsolete PHP codes to ruby, and I ran into a problem with some 3DES coding. This is a PHP implementation using mcrypt:

function encrypt_3DES($message, $key){

    $bytes = array(0,0,0,0,0,0,0,0); //byte [] IV = {0, 0, 0, 0, 0, 0, 0, 0}
    $iv = implode(array_map("chr", $bytes)); //PHP 4 >= 4.0.2

    $ciphertext = mcrypt_encrypt(MCRYPT_3DES, $key, $message, MCRYPT_MODE_CBC, $iv); 
    return $ciphertext;
}

and this is my ruby ​​code:

def encrypt_3DES(message, key)
  des=OpenSSL::Cipher.new('des3')
  des.encrypt
  des.key = key
  des.update(message)+des.final
end

However, the results are slightly different (with base64 encoding):

//PHP
ZpgH7NWpRx+Mi6tDBZ9q2Q==

# Ruby
ZpgH7NWpRx/usGDIsQ+A8A==

As you can see, this is the lowest part of string bytes that is different. Any pointers are greatly appreciated.

+4
source share
2 answers

I answer my question.

, openssl mcrypt . , http://opensourcetester.co.uk/2012/11/29/zeros-padding-3des-ruby-openssl/

#ENCRYPTION
block_length = 8
des.padding = 0 #Tell Openssl not to pad
des.encrypt
json = '{"somekey":"somevalue"}'
json += "\0" until json.bytesize % block_length == 0 #Pad with zeros
edata = des.update(json) + des.final 
b64data = Base64.encode64(edata).gsub("\n",'')

, ruby ​​openssl PKCS, mcrypt 0 . openssl des.padding = 0, : json += "\0" until json.bytesize % block_length == 0.

, .

+3

PHP MCRYPT_3DES MCRYPT_MODE_CBC ruby ​​OpenSSL 3des ( des-ede3-cbc). .

, des-ede-cbc des-cbc (. )

0

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


All Articles