@@ -56,14 +56,16 @@ public int getVersion() {
56
56
57
57
@ Override
58
58
public byte [] kdf (byte [] z ) {
59
+ byte [] hmacKey = null ;
60
+ byte [] aesKey = null ;
59
61
try {
60
- byte [] hmacKey = new Hkdf (HKDF_ALG ).digest (
62
+ hmacKey = new Hkdf (HKDF_ALG ).digest (
61
63
z ,
62
64
HKDF_SALT ,
63
65
HKDF_INFO_HMAC ,
64
66
HKDF_LENGTH );
65
67
66
- byte [] aesKey = new Hkdf (HKDF_ALG ).digest (
68
+ aesKey = new Hkdf (HKDF_ALG ).digest (
67
69
z ,
68
70
HKDF_SALT ,
69
71
HKDF_INFO_AES ,
@@ -75,13 +77,21 @@ public byte[] kdf(byte[] z) {
75
77
.array ();
76
78
} catch (NoSuchAlgorithmException | InvalidKeyException e ) {
77
79
throw new IllegalStateException (e );
80
+ } finally {
81
+ if (hmacKey != null ) {
82
+ Arrays .fill (hmacKey , (byte ) 0 );
83
+ }
84
+ if (aesKey != null ) {
85
+ Arrays .fill (aesKey , (byte ) 0 );
86
+ }
78
87
}
79
88
}
80
89
81
90
@ Override
82
91
public byte [] encrypt (byte [] key , byte [] plaintext ) {
92
+ byte [] aesKey = null ;
83
93
try {
84
- byte [] aesKey = Arrays .copyOfRange (key , 32 , key .length );
94
+ aesKey = Arrays .copyOfRange (key , 32 , key .length );
85
95
byte [] iv = RandomUtils .getRandomBytes (16 );
86
96
87
97
final byte [] ciphertext =
@@ -93,19 +103,27 @@ public byte[] encrypt(byte[] key, byte[] plaintext) {
93
103
.array ();
94
104
} catch (IllegalBlockSizeException | BadPaddingException e ) {
95
105
throw new IllegalStateException (e );
106
+ } finally {
107
+ if (aesKey != null ) {
108
+ Arrays .fill (aesKey , (byte ) 0 );
109
+ }
96
110
}
97
111
}
98
112
99
113
@ Override
100
114
public byte [] decrypt (byte [] key , byte [] ciphertext ) {
115
+ byte [] aesKey = null ;
101
116
try {
102
- byte [] aesKey = Arrays .copyOfRange (key , 32 , key .length );
117
+ aesKey = Arrays .copyOfRange (key , 32 , key .length );
103
118
byte [] iv = Arrays .copyOf (ciphertext , 16 );
104
119
byte [] ct = Arrays .copyOfRange (ciphertext , 16 , ciphertext .length );
105
- byte [] plaintext = getCipher (Cipher .DECRYPT_MODE , aesKey , iv ).doFinal (ct );
106
- return Arrays .copyOf (plaintext , plaintext .length );
120
+ return getCipher (Cipher .DECRYPT_MODE , aesKey , iv ).doFinal (ct );
107
121
} catch (BadPaddingException | IllegalBlockSizeException e ) {
108
122
throw new IllegalStateException (e );
123
+ } finally {
124
+ if (aesKey != null ) {
125
+ Arrays .fill (aesKey , (byte ) 0 );
126
+ }
109
127
}
110
128
}
111
129
@@ -120,8 +138,7 @@ public byte[] authenticate(byte[] key, byte[] message) {
120
138
} catch (NoSuchAlgorithmException | InvalidKeyException e ) {
121
139
throw new RuntimeException (e );
122
140
}
123
- byte [] result = mac .doFinal (message );
124
- return Arrays .copyOf (result , result .length );
141
+ return mac .doFinal (message );
125
142
}
126
143
127
144
private Cipher getCipher (int mode , byte [] secret , byte [] iv ) {
0 commit comments