我必须实现Java密码空间填充。我试图写喜欢支持Perl代码的实现,其中支持Blowfish / CBC / space模式。我在Java密码列表中找不到相关的模式,仅支持PCK5Padding和NoPadding。 Java是否支持空格填充?有人可以帮助我吗?
答案 0 :(得分:1)
Space
填充会添加空格,因此加密时长度为8的倍数,解密后则修剪空格。在Java中,您可以使用NoPadding
并自己管理间距。
例如,要在Perl中加密并在Java中解密:
Perl:
use Crypt::CBC;
$cipher = Crypt::CBC->new(
-literal_key => 1,
-key => pack("H*",
"11223344556677889900112233445566778899001122334"
. "455667788990011223344556677889900112233445566"
. "77889900112233445566"),
-cipher => 'Blowfish',
-header => 'none',
-padding => 'space',
-iv => pack("H*", '1234567812345678')
);
$ciphertext = $cipher->encrypt_hex("Message");
print(join('',unpack('H*',$cipher->iv())));
print $ciphertext;
输出: 1234567812345678e70b9ab0a4262ba8
Java:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Hex;
public class Main {
public static void main(String[] args) throws Exception {
Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");
SecretKeySpec key = new SecretKeySpec(Hex.decodeHex(
"11223344556677889900112233445566778899001122334"
+ "455667788990011223344556677889900112233445566"
+ "77889900112233445566"),
"Blowfish");
byte[] iv = Hex.decodeHex("1234567812345678");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(Hex.decodeHex("e70b9ab0a4262ba8"));
System.out.println(new String(result, Charsets.UTF_8).trim());
}
}
输出: Message