1717
1818package org .apache .kyuubi .service .authentication
1919
20+ import java .security .SecureRandom
2021import javax .crypto .Cipher
2122import javax .crypto .spec .{IvParameterSpec , SecretKeySpec }
2223
@@ -32,23 +33,17 @@ class InternalSecurityAccessor(conf: KyuubiConf, val isServer: Boolean) {
3233 val cryptoKeyAlgorithm = conf.get(ENGINE_SECURITY_CRYPTO_KEY_ALGORITHM )
3334 val cryptoCipher = conf.get(ENGINE_SECURITY_CRYPTO_CIPHER_TRANSFORMATION )
3435
36+ private val random = new SecureRandom ()
3537 private val tokenMaxLifeTime : Long = conf.get(ENGINE_SECURITY_TOKEN_MAX_LIFETIME )
3638 private val provider : EngineSecuritySecretProvider = EngineSecuritySecretProvider .create(conf)
37- private val (encryptor, decryptor) =
39+ private val (secretKeySpec, encryptor, decryptor) =
3840 initializeForAuth(cryptoCipher, normalizeSecret(provider.getSecret()))
3941
40- private def initializeForAuth (cipher : String , secret : String ): (Cipher , Cipher ) = {
42+ private def initializeForAuth (cipher : String , secret : String ): (SecretKeySpec , Cipher , Cipher ) = {
4143 val secretKeySpec = new SecretKeySpec (secret.getBytes, cryptoKeyAlgorithm)
42- val nonce = new Array [Byte ](cryptoIvLength)
43- val iv = new IvParameterSpec (nonce)
44-
4544 val _encryptor = Cipher .getInstance(cipher)
46- _encryptor.init(Cipher .ENCRYPT_MODE , secretKeySpec, iv)
47-
4845 val _decryptor = Cipher .getInstance(cipher)
49- _decryptor.init(Cipher .DECRYPT_MODE , secretKeySpec, iv)
50-
51- (_encryptor, _decryptor)
46+ (secretKeySpec, _encryptor, _decryptor)
5247 }
5348
5449 def issueToken (): String = {
@@ -69,11 +64,17 @@ class InternalSecurityAccessor(conf: KyuubiConf, val isServer: Boolean) {
6964 }
7065
7166 private [authentication] def encrypt (value : String ): String = synchronized {
72- byteArrayToHexString(encryptor.doFinal(value.getBytes))
67+ val nonce = new Array [Byte ](cryptoIvLength)
68+ random.nextBytes(nonce)
69+ encryptor.init(Cipher .ENCRYPT_MODE , secretKeySpec, new IvParameterSpec (nonce))
70+ byteArrayToHexString(nonce ++ encryptor.doFinal(value.getBytes))
7371 }
7472
7573 private [authentication] def decrypt (value : String ): String = synchronized {
76- new String (decryptor.doFinal(hexStringToByteArray(value)))
74+ val bytes = hexStringToByteArray(value)
75+ val nonce = bytes.take(cryptoIvLength)
76+ decryptor.init(Cipher .DECRYPT_MODE , secretKeySpec, new IvParameterSpec (nonce))
77+ new String (decryptor.doFinal(bytes.drop(cryptoIvLength)))
7778 }
7879
7980 private def normalizeSecret (secret : String ): String = {
0 commit comments