java - 使用 Java 中的双倍长度 3DES key 进行加密并生成 16 字节数组密码

标签 java encryption 3des

我需要使用 16 字节数组 key Material 在 Java 中创建双倍长度 3DES key ,用它加密消息并取回 16 字节长度数组。我可以让它使用 24 字节,但不能使用 16 字节...

因为 DESede 需要 24 字节 [],这是生成具有 16 字节长 key Material 的双倍长度 3DES key 的唯一方法,所以我能够通过使用 DESede 实例,然后通过在end 获取 24 字节。就像这样:

    byte[] keyMaterial = // Assume this one is 16 bytes. 

    byte[] newKeyBytes = ByteBuffer.wrap( new byte[ 24 ] )
            .put( Arrays.copyOfRange( keyMaterial, 0, 16 ) )
            .put( Arrays.copyOfRange( keyMaterial, 0, 8 ) )
            .array();

    SecretKeyFactory mySecretKeyFactory = SecretKeyFactory.getInstance( "DESede" );
    KeySpec myKeySpec = new DESedeKeySpec( newKeyBytes );
    SecretKey encryptionKey = mySecretKeyFactory.generateSecret( myKeySpec );

现在,当我拥有 DESede key 时,我可以使用它按以下方式加密消息。另外,我需要使用“ECB”模式:

    Cipher cipher = Cipher.getInstance( "DESede/ECB/PKCS5Padding" );
    cipher.init( Cipher.ENCRYPT_MODE, encryptionKey );
    byte[] returnValue = cipher.doFinal( dataToEncrypt )

但结果我得到的是 24 字节数组而不是 16 字节数组,我想这是因为我正在使用 24 字节数组进行加密。

有没有办法创建一个 16 字节长而不是 24 字节长的 3DES SecretKey,或者当使用 24 字节长 SecretKey 加密时,根据需要取回 16 字节长的加密消息而不是 24 字节长?

谢谢!

最佳答案

我想我刚刚找到了问题的答案。

https://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

我使用了 DESede/ECB/NoPadding,当与 NoPadding 一起使用时,然后使用 24 字节 SecretKey 加密 16 字节数组消息会生成一个 16 字节长的密码消息,这正是我所需要的。

我希望这个发现是正确的。如果我错了,请纠正我。

关于java - 使用 Java 中的双倍长度 3DES key 进行加密并生成 16 字节数组密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45352262/

相关文章:

java - 从 String 创建唯一 id (int)

javascript - 下载到Android手机时如何保护受版权保护的多媒体文件?

java - PHP 上的 DESede 长 key ,而不是 Java 中的

php + ios加密解密3des + base64

java - 在 JMockit 中多次重用期望 block

java - JSON解析为多个POJO集合

java - Spring Boot项目中的Eclipse "cannot resolve type"

Java 7 : output from encryption with public RSA key using cipher "RSA/ECB/OAEPWithSHA1AndMGF1Padding" does not match with openssl command

C++如何使用boost制作简单的sha256生成器?

ios - JSON + 3des加密无效