1

我有解密字符串的 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。但据此Crypt CBC用作PKCS5默认填充。

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

4

2 回答 2

1

您遇到的问题之一是您生成了一个随机 IV,而不是导入用于加密的 IV。您是否有权访问加密时使用的 IV?会不会是在密文的开头?

于 2013-01-28T23:07:14.330 回答
0

I don't do Perl, so I'm not quite sure if my response is valid. Base64 is probably not the right decoding you're looking for.

For creating your SecretKeySpec, try doing something like:

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

For decoding the text, check out Hex.decodeHex(char[]) which can be found at http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html ... so your code might look something like this:

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

String unencryptedStuff = new String(decrypted);
于 2013-01-28T23:12:26.737 回答