@@ -31,9 +31,6 @@ final class SecureStringUtil {
3131 /* authentication tag length in bits */
3232 static final int TAG_LENGTH = 16 ;
3333
34- /* initialization vector */
35- byte [] iv ;
36-
3734 /** secret key for encryption/decryption */
3835 SecretKeySpec secretKey ;
3936
@@ -68,7 +65,6 @@ static SecureStringUtil getInstance() throws SQLServerException {
6865 * if error
6966 */
7067 private SecureStringUtil () throws SQLServerException {
71- iv = new byte [IV_LENGTH ];
7268 try {
7369 // generate key */
7470 KeyGenerator keygen = KeyGenerator .getInstance (KEYGEN_ALGORITHEM );
@@ -99,6 +95,8 @@ private SecureStringUtil() throws SQLServerException {
9995 byte [] getEncryptedBytes (char [] chars ) throws SQLServerException {
10096 if (chars == null )
10197 return null ;
98+
99+ byte [] iv = new byte [IV_LENGTH ];
102100 SecureRandom random = new SecureRandom ();
103101 random .nextBytes (iv );
104102 GCMParameterSpec ivParamSpec = new GCMParameterSpec (TAG_LENGTH * 8 , iv );
@@ -107,7 +105,10 @@ byte[] getEncryptedBytes(char[] chars) throws SQLServerException {
107105 encryptCipher .init (Cipher .ENCRYPT_MODE , secretKey , ivParamSpec );
108106
109107 byte [] cipherText = encryptCipher .doFinal (Util .charsToBytes (chars ));
110- return cipherText ;
108+ byte [] bytes = new byte [iv .length + cipherText .length ];
109+ System .arraycopy (iv , 0 , bytes , 0 , iv .length );
110+ System .arraycopy (cipherText , 0 , bytes , iv .length , cipherText .length );
111+ return bytes ;
111112 } catch (Exception e ) {
112113 MessageFormat form = new MessageFormat (SQLServerException .getErrString ("R_EncryptionFailed" ));
113114 Object [] msgArgs = {e .getMessage ()};
@@ -127,13 +128,17 @@ byte[] getEncryptedBytes(char[] chars) throws SQLServerException {
127128 char [] getDecryptedChars (byte [] bytes ) throws SQLServerException {
128129 if (bytes == null )
129130 return null ;
131+
132+ byte [] iv = new byte [IV_LENGTH ];
133+ System .arraycopy (bytes , 0 , iv , 0 , IV_LENGTH );
134+
130135 GCMParameterSpec ivParamSpec = new GCMParameterSpec (TAG_LENGTH * 8 , iv );
131136
132137 byte [] plainText = null ;
133138 try {
134139 decryptCipher .init (Cipher .DECRYPT_MODE , secretKey , ivParamSpec );
135140
136- plainText = decryptCipher .doFinal (bytes );
141+ plainText = decryptCipher .doFinal (bytes , IV_LENGTH , bytes . length - IV_LENGTH );
137142 return Util .bytesToChars (plainText );
138143 } catch (Exception e ) {
139144 MessageFormat form = new MessageFormat (SQLServerException .getErrString ("R_DecryptionFailed" ));
0 commit comments