Convert Encrypt code in java to Ruby

后端 未结 2 1566
野趣味
野趣味 2020-12-30 19:01

I have been trying to convert a code for encrypt in java to ruby, but I am not able to do it completely. I getting different values.

   passphrase = passphra         


        
2条回答
  •  心在旅途
    2020-12-30 19:31

    Encrypt Code:

    def aes(key,string)
      cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
      cipher.encrypt
      cipher.padding = 1
      cipher.key = hex_to_bin(Digest::SHA1.hexdigest('secret_key')[0..32])
      cipher_text = cipher.update(string)
      cipher_text << cipher.final
      return bin_to_hex(cipher_text).upcase
    end
    

    Decrypt Code:

    def aes_decrypt(key, encrypted)
      encrypted = hex_to_bin(encrypted.downcase)
      cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
      cipher.decrypt
      cipher.padding = 1
      cipher.key = hex_to_bin(Digest::SHA1.hexdigest('secret_key')[0..32])
      d = cipher.update(encrypted)
      d << cipher.final
    end
    

    hex_to_bin and bin_to_hex

    def hex_to_bin(str)
      [str].pack "H*"
    end
    
    def bin_to_hex(s)
      s.unpack('C*').map{ |b| "%02X" % b }.join('')
    end
    

    In My case, The java code was using default initialization vector, So I did not set any iv, Also, there was hex_to_bin was a missing piece there. So after that, all started working properly.

    I hope it helps someone if they come across this issue.

提交回复
热议问题