Java AES无填充 [英] Java AES without padding

查看:250
本文介绍了Java AES无填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有自动填充的情况下,AES加密和解密16字节数组的最简单的方法是什么?我找到了使用外部库的解决方案,但是如果可能,我想避免这种情况。



我目前的代码是

  SecretKeySpec skeySpec = new SecretKeySpec(getCryptoKeyByteArray(length = 16)); // 128位
加密加密器= Cipher.getInstance(AES);
encryptor.init(Cipher.ENCRYPT_MODE,skeySpec);
byte [] encrypted = encryptor.doFinal(plain);

我如何防止填充? plain 数据总是固定长度,并包含自己的填充。如何让 plain 成16字节,而不会导致加密成32字节?

解决方案


看到我的评论。对不起,我可能应该第一次仔细看看。


  1. 更改AES to AES / CBC / NoPadding

  2. 更改 decryptor.init(Cipher.DECRYPT_MODE,skeySpec,encryptor.gerParameters());
    li>

仅使用不需要保存初始化向量的方法来加密固定长度的16字节数据,更改AESAES / ECB / NoPadding



我选择ECB因为


What are some of the simplest ways to AES encrypt and decrypt a 16 byte array without the automatic padding? I have found solutions that use external libraries, but I want to avoid that if possible.

My current code is

SecretKeySpec skeySpec = new SecretKeySpec(getCryptoKeyByteArray(length=16)); // 128 bits
Cipher encryptor = Cipher.getInstance("AES");
encryptor.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = encryptor.doFinal(plain);

How can I prevent the padding? The plain data is always fixed length and includes its own padding. How can I allow plain to be 16 bytes without causing encrypted to become 32 bytes?

解决方案

See my comment. Sorry I probably should have taken a closer look the first time.

  1. Change "AES" to "AES/CBC/NoPadding"
  2. Change decryptor.init(Cipher.DECRYPT_MODE, skeySpec); to decryptor.init(Cipher.DECRYPT_MODE, skeySpec, encryptor.gerParameters());

To encrypt only 16 bytes of data, fixed length, using a method that requires no initialization vector to be saved, Change "AES" to "AES/ECB/NoPadding"

I pick ECB because that is the default.

If you need to encrypt more than 16 bytes, consider using something other than ECB, which suffers a certain repetition detection flaw

In this bitmap example, this image has repeated white blocks, so you can deduce the outline of the image simply by looking for where the blocks become different.

If you are only encrypting one block, it doesn't really matter though, only if you are encrypting multiple blocks that are combined does ECB become revealing.

Related: https://security.stackexchange.com/questions/15740/what-are-the-variables-of-aes

这篇关于Java AES无填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆