用Java解密Blowfish / CBC

时间:2013-01-28 22:58:42

标签: java perl encryption blowfish

我有解密String的Perl代码,我想在Java中做同样的事情。这是Perl代码:

my $c = Crypt::CBC->new( -key => $keyString, -cipher => 'Blowfish', -header => 'randomiv');
return $c->decrypt_hex($config->{encrypted_password})

这是我对Java代码的尝试:

Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");

// setup an IV (initialization vector) that should be
// randomly generated for each input that's encrypted
byte[] iv = new byte[cipher.getBlockSize()];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);

// decrypt
SecretKey secretKey = new SecretKeySpec(Base64.decodeBase64(keyString), "Blowfish");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
byte[] decrypted = cipher.doFinal(Base64.decodeBase64(input));
return Hex.encodeHexString(decrypted);

我得到了:javax.crypto.BadPaddingException: Given final block not properly padded。但根据thisCrypt CBC库使用PKCS5作为默认填充。

另外,我在最后做了十六进制编码吗?

2 个答案:

答案 0 :(得分:1)

您遇到的一个问题是您生成随机IV而不是导入用于加密的IV。您是否可以访问加密时使用的IV?可能是在密文的开头吗?

答案 1 :(得分:0)

我不做Perl,所以我不确定我的回答是否有效。 Base64可能不是您正在寻找的正确解码。

要创建SecretKeySpec,请尝试执行以下操作:

SecretKey secretKey = new SecretKeySpec(keyString.getBytes("ASCII"), "Blowfish");

要解码文本,请查看可在http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html找到的Hex.decodeHex(char [])...所以您的代码可能如下所示:

byte[] decrypted = cipher.doFinal(Hex.decodeHex(input.toCharArray()));

String unencryptedStuff = new String(decrypted);