使用 BlowFish 在 Java 中加密:结果太长

Encrypting in Java with BlowFish: result is too long

我必须使用 BlowFish 使用 C、Perl 和 Java 加密和解密相同的秘密。虽然 C-pgm 和 Perl 给出相同的结果,但 Java 中的结果字符串太长。这里先用C:

写的一个pgm加解密
$ ./enc key Valentin
block: [Valentin]
0a2dc7c9bf82264d
$ ./dec key 0a2dc7c9bf82264d
Valentin

现在Java也一样:

$ java -classpath . BlowFishTest key Valentin
length of pw: 8
length of crypted: 16
0a2dc7c9bf82264dd83df76a225413c1

有趣的是,Java 中结果的第一部分包含与 C 相同的十六进制值,但长度为 16 个字节。

Java代码是:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class BlowFishTest {

    public static void main(String[] args) throws Exception  {
    String key = args[0];
        String clear = args[1];

    encrypt(key, clear);
    }

    private static void encrypt(String key, String password) throws Exception {

    byte[] KeyData = key.getBytes("UTF-8");
    SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
    Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, KS);

    byte[] pw = password.getBytes("UTF-8");
        System.out.println("length of pw: " + pw.length);

        byte[] crypted = cipher.doFinal(pw);
        System.out.println("length of crypted: " + crypted.length);
    StringBuilder sb = new StringBuilder();
        for (byte b : crypted) {
           sb.append(String.format("%02X", b));
        }
        System.out.println(sb.toString().toLowerCase());
    }

}

仅使用 Blowfish 密码 Java 隐式意味着 Blowfish/ECB/Pkcs5padding(这可能因使用的框架而异)。您应该始终以 algorithm/mode/padding 的形式指定密码。 Blocksize 是密码是 64 位(8 字节)。所以Java自动添加一个空的填充块。

如果您不想使用任何填充,您可以指定Blowfish/ECB/NoPadding。我会说幸运的是你正在加密单个块(8 字节)的数据,尝试不同的长度,你会看到