简体   繁体   English

Java的3DES加密在加密数据的末尾产生垃圾

[英]Java's 3DES encryption generates trash at the end of encrypted data

I have a 3des Cipher object that is initialized like this: 我有一个像这样初始化的3des Cipher对象:

KeySpec keySpec= new DESedeKeySpec(bytesKey);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey secretKey= secretKeyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(modo, secretKey);

When this object is used to encrypt data, no exception is thrown and the algorithm ends succesfully: 当此对象用于加密数据时,不会引发任何异常,并且算法成功结束:

String unencryptedText = "192 character length text in clear....        ";
byte[] bytesUnencryptedText = unencryptedText.getBytes("UTF8");
byte[] bytesEncryptedData = cipher.doFinal(bytesUnencryptedText);

When we took a look at the encrypted data generated by the doFinal, we noticed 200 bytes are being returned, as opposed to 192 as we expected. 当我们查看由doFinal生成的加密数据时,我们注意到正在返回200个字节,而不是我们期望的192个字节。 These additional 8 bytes took the following hexa value: 08. 这些额外的8个字节采用以下十六进制值:08。

The first 192 bytes are correct and we already have been able to decrypt them and obtain our original data. 前192个字节是正确的,我们已经能够解密它们并获取原始数据。 But the additional 8 bytes are generating an error at our HSM. 但是额外的8个字节在我们的HSM处产生错误。

How can we prevent the Cipher to inject these additional bytes? 我们如何防止密码注入这些额外的字节?

The block size of DES is 64-bit or 8 bytes. DES的块大小为64位或8个字节。 When the plaintext size is a multiple of the plaintext the padding used will add another block of data to the plaintext filled with 0x08. 当明文大小是明文的倍数时,使用的填充将向填充有0x08的明文中添加另一个数据块。 This is how PKCS#5/PKCS#7 padding works. 这就是PKCS#5 / PKCS#7填充的工作方式。

It seems that your HSM expects that no padding is used. 您的HSM似乎期望不使用填充。 Also, from the comments it is apparent that "DESede" defaults to ECB mode, so the fully qualified Cipher would be: 同样,从注释中可以明显看出, "DESede"默认为ECB模式,因此完全合格的密码将为:

Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");

Note that ECB mode is not semantically secure. 请注意,ECB模式在语义上并不安全。 If possible, use a different mode like CBC with an HMAC over the ciphertext, or simply an authenticated mode like GCM. 如果可能,请在密文上使用其他模式(例如CBC和HMAC),或者仅使用身份验证模式(例如GCM)。

When you use NoPadding, the plaintext is filled up with 0x00 bytes and you will have to trim the decrypted plaintext yourself by removing all 0x00 bytes at the end. 当您使用NoPadding时,纯文本将填充0x00字节,并且您将必须通过在末尾删除所有0x00字节来自己修剪解密的纯文本。 To do this, make sure that the plaintext doesn't actually contain 0x00 bytes at the end, otherwise you will remove actual plaintext bytes. 为此,请确保纯文本末尾实际上不包含0x00字节,否则,您将删除实际的纯文本字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM