File tree Expand file tree Collapse file tree 4 files changed +35
-1
lines changed
main/java/at/favre/lib/bytes
test/java/at/favre/lib/bytes Expand file tree Collapse file tree 4 files changed +35
-1
lines changed Original file line number Diff line number Diff line change 77* add `encodeBase64()` supporting padding-less encoding
88* add `toIntArray()` converter #28
99* add `toLongArray()` converter #29
10+ * add `AutoCloseable` to MutableBytes interface #31
1011
1112### Breaking
1213
Original file line number Diff line number Diff line change @@ -580,6 +580,18 @@ Bytes b = Bytes.from(array).mutable().copy();
580580assertTrue(b. isMutable());
581581```
582582
583+ ##### AutoClosable for try-with-resources
584+
585+ In security-relevant environments it is best practice to wipe the memory of secret data, such as
586+ secret keys. This can be used with Java 7 feature try-with-resource like this:
587+
588+ ``` java
589+ try (MutableBytes b = Bytes . wrap(aesBytes). mutable()) {
590+ SecretKey s = new SecretKeySpec (b. array(), " AES" );
591+ ...
592+ }
593+ ```
594+
583595#### Readonly Bytes
584596
585597On the other hand, if you want a export a instance with limited access,
Original file line number Diff line number Diff line change 3232 * Adds additional mutator, which may change the internal array in-place, like {@link #wipe()}
3333 */
3434@ SuppressWarnings ("WeakerAccess" )
35- public final class MutableBytes extends Bytes {
35+ public final class MutableBytes extends Bytes implements AutoCloseable {
3636
3737 MutableBytes (byte [] byteArray , ByteOrder byteOrder ) {
3838 super (byteArray , byteOrder , new Factory ());
@@ -147,6 +147,11 @@ public boolean equals(Object o) {
147147 return super .equals (o );
148148 }
149149
150+ @ Override
151+ public void close () {
152+ secureWipe ();
153+ }
154+
150155 /**
151156 * Factory creating mutable byte types
152157 */
Original file line number Diff line number Diff line change 2323
2424import org .junit .Test ;
2525
26+ import javax .crypto .SecretKey ;
27+ import javax .crypto .spec .SecretKeySpec ;
2628import java .security .SecureRandom ;
2729import java .util .Arrays ;
2830
@@ -167,4 +169,18 @@ public void testTransformerShouldBeMutable() {
167169 assertTrue (b .append (3 ).isMutable ());
168170 assertTrue (b .hashSha256 ().isMutable ());
169171 }
172+
173+ @ Test
174+ public void testAutoCloseable () {
175+ MutableBytes leak ;
176+
177+ try (MutableBytes b = Bytes .wrap (new byte [16 ]).mutable ()) {
178+ assertArrayEquals (new byte [16 ], b .array ());
179+ SecretKey s = new SecretKeySpec (b .array (), "AES" );
180+ leak = b ;
181+ }
182+
183+ assertArrayNotEquals (new byte [16 ], leak .array ());
184+
185+ }
170186}
You can’t perform that action at this time.
0 commit comments