6 Secure Coding Guidance
Avoiding Unnecessary In-Memory Buffering of Plaintext
The Cipher
methods update
and doFinal
support data streaming. However, cipher transformations that use an AES KeyWrap
algorithm (defined in RFC 3394: Advanced Encryption Standard (AES) Key Wrap
Algorithm) such as AESWrap, AESWrapPad, AES/KW/NoPadding, and
AES/KWP/NoPadding don't lend themselves to data streaming because all input data must be
available before any of the input data can be fully processed. Consequently, if an
AESWrap transform Cipher
object is initialized with the
ENCRYPT_MODE
operation, any plaintext passed to an
update
method is copied into an internal buffer so that it may be
later processed during a subsequent doFinal
method call. The
Cipher
object's internal plaintext buffer is zeroed and freed when
doFinal
is invoked or when the Cipher
object is
garbage collected. Applications that want to avoid plaintext being buffered by an
AESWrap transform Cipher
object should avoid calling
update
. For example, consider the following code:
Cipher wrapper = Cipher.getInstance("AESWrap");
wrapper.init(Cipher.ENCRYPT_MODE, secretKey);
wrapper.update(plaintext);
byte[] cipherText = wrapper.doFinal();
You can replace it with the following:
Cipher wrapper = Cipher.getInstance("AESWrap");
wrapper.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = wrapper.doFinal(plaintext);