views:

109

answers:

1
use Crypt::CBC;
my $crypt = Crypt::CBC->new(-key => "password", -cipher => "Crypt::Blowfish");
print $crypt->encrypt_hex('s');

How do I get the same result using java?

Thanks in Advance.

A: 

You can use the javax.crypto package. Although this isn't a solution, it should get you on the right track:

// encrypt
byte[] key = "password".getBytes("US-ASCII");
byte[] plaintext = "s".getBytes("US-ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(key, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
// show result
byte[] result = cipher.doFinal(plaintext);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < result.length; i++) {
    String hex = Integer.toHexString(0xFF & result[i]);
        if (hex.length() == 1) {
            hexString.append('0');
        }
    hexString.append(hex);
}
System.out.println(hexString);

This should solve everything except for the randomly generated salt.

skyuzo
FYI: Your example creates a `Cipher` in ECB mode, not CBC mode. As well, constructing a `String` from the cipher text may back-fire if the cipher emits bytes that cannot be directly converted to characters.
Adam Paynter
Yes, plus using String.getBytes() is almost always a bad idea. It implicitly uses the system default encoding, which may change if you change your OS, your OS environment or your computer, so it's fairly unpredictable...
sleske
I used the above code,but the results are different.
Mak Killbers
@Mak: The results are different because of the issues outlined by me and sleske.
Adam Paynter
@Mak: After looking at `Crypt::CBC`, I also realize that it is more complicated than I originally thought. That Perl module generates its own salt, and derives its own key from the pass phrase. This will require investigation to understand what *exactly* it's doing.
Adam Paynter
@Adam Any help without changing perl code?
Mak Killbers