【问题标题】:How to implement Blowfish CBC algorithm space Padding如何实现 Blowfish CBC 算法空间 Padding
【发布时间】:2019-02-27 14:49:48
【问题描述】:

我必须实现 java 密码空间填充。我正在尝试编写支持 Blowfish/CBC/space 模式的 Perl 代码实现。我在 Java Cipher 列表中找不到相关模式,仅支持 PCK5Padding 和 NoPadding。如果有人可以帮助我,Java 是否支持空格填充。

【问题讨论】:

    标签: java encryption padding space


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2012-11-10
      • 1970-01-01
      • 2015-09-25
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多