title: Blowfish encryption: Java vs. Ruby
body: <p>I am trying to generate some encrypted JBoss data source passwords from Puppet (Ruby). JBoss uses <a href="https://source.jboss.org/browse/PicketBox/trunk/security-jboss-sx/jbosssx/src/main/java/org/picketbox/datasource/security/SecureIdentityLoginModule.java?r=332" rel="nofollow">this library (see line 149)</a> to encrypt / decrypt the passwords (using Blowfish with a predefined key compiled in the Java code).</p>
  
  <p>Now, researching a bit I found that, as default, javax.crypto uses for blowfish the following parameters: Blowfish/ECB/PKCS5Padding.</p>
  
  <p>By default, Ruby's OpenSSL library does not make any padding at all (simply refuses the key if it is not a multiple of 8). I tried to do the padding manually and here is my complete code:</p>
  
  <pre><code>#!/usr/bin/ruby
  
  require 'openssl'
  
  key = 'jaas is the way'
  
  ciph = OpenSSL::Cipher.new('bf-ecb').encrypt
  ciph.key = key + (8 - key.length % 8).chr * (8 - key.length % 8)
  
  b = ciph.update(ARGV[0]) + ciph.final()
  puts b.unpack('H*')
  </code></pre>
  
  <p>I tried to implement the PKCS5 padding the same way as I saw it implemented in Python in a similar (Python vs. Java Blowfish) question here on SO by adding chr(number of bytes until the length is multiple of 8) until the length of the string is multiple of 8. For this specific key, it is supposed to add exactly one chr(1) and when trying to debug, it seems to do it just fine.</p>
  
  <p>The thing is that my Ruby code is giving different results to the ones obtained by the code in the Picketbox library in Java.</p>
  
  <p>EDIT:
  Here are some conclusions I got after running more tests:</p>
  
  <ul>
  <li><p>If both the key and the plain text to be encrypted are 16 bytes long, the results are fine</p></li>
  <li><p>We tried with a 16 bytes long plain text string to be encrypted and a 15 bytes key. Then we padded (both pre and post) the key in Ruby with all characters with ASCII code from 0 to 255 and none of the results were matching the encrypted text we got in Java. This makes no sense at all because, if Java would simply pad the key with whatever, it would add a character to the beginning or the end of the original key. The only logical explanation could be if Java does manipulate the key string by other means, other than appending a character.</p></li>
  </ul>