/*
Factory method for a SnowflakeAzureClient object
@param stage   The stage information that the client will operate on
@param encMat  The encryption material
required to decrypt/encrypt content in stage
516586
public static SnowflakeAzureClient createSnowflakeAzureClient(StageInfo stage,
                                                                RemoteStoreFileEncryptionMaterial encMat)
  throws SnowflakeSQLException
  {
    SnowflakeAzureClient azureClient = new SnowflakeAzureClient();
    azureClient.setupAzureClient(stage, encMat);

    return azureClient;
  }
303902
public void setProcessLaunchedAt(java.util.Collection<DateFilter> processLaunchedAt) {
        if (processLaunchedAt == null) {
            this.processLaunchedAt = null;
            return;
        }

        this.processLaunchedAt = new java.util.ArrayList<DateFilter>(processLaunchedAt);
    }
1188644
public static SSLContext sslContext(AbstractConfig config, String key) {
    final String trustManagerFactoryType = config.getString(key);
    try {
      return SSLContext.getInstance(trustManagerFactoryType);
    } catch (NoSuchAlgorithmException e) {
      ConfigException exception = new ConfigException(
          key,
          trustManagerFactoryType,
          "Unknown Algorithm."
      );
      exception.initCause(e);
      throw exception;
    }
  }
956020
public ByteBuffer getSecretStage(final String secretId, final Stage stage) {
        final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest();
        getSecretValueRequest.setSecretId(secretId);
        getSecretValueRequest.setVersionStage(stage.getAwsName());
        final GetSecretValueResult result = getDelegate().getSecretValue(getSecretValueRequest);
        return result.getSecretBinary();
    }
375082
protected static final byte[] encrypt(byte[] data, byte[] key, String cipher) throws Exception {
        SecretKey sKey = constructSecretKey(key, cipher);
        Cipher ci = createCipher(Cipher.ENCRYPT_MODE, key, cipher, sKey);
        return ci.doFinal(data);
    }
706021
public function encrypt($encrypt, $key)
    {
        $inputParams = [
            'encrypt' => $encrypt,
            'key'     => $key,
        ];
        $this->debug->info(__FUNCTION__, 'Input Params: ' . json_encode($inputParams));
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $this->debug->debug(__FUNCTION__, 'IV Key: ' . json_encode($iv));
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, pack("H*", $key), $encrypt, MCRYPT_MODE_ECB, $iv));
        $this->debug->info(__FUNCTION__, 'encrypt Result: ' . json_encode($encrypted));

        return $encrypted;
    }
858507
public static String encryptByAES(final String content, final String key) {
        try {
            final KeyGenerator kgen = KeyGenerator.getInstance("AES");
            final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            kgen.init(128, secureRandom);
            final SecretKey secretKey = kgen.generateKey();
            final byte[] enCodeFormat = secretKey.getEncoded();
            final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
            final Cipher cipher = Cipher.getInstance("AES");
            final byte[] byteContent = content.getBytes("UTF-8");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            final byte[] result = cipher.doFinal(byteContent);

            return Hex.encodeHexString(result);
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Encrypt failed", e);

            return null;
        }
    }
1055052
static ContentCryptoMaterial fromInstructionFile(
        Map<String, String> instFile,
        EncryptionMaterialsAccessor kekMaterialAccessor,
        Provider securityProvider,
        boolean alwaysUseSecurityProvider,
        long[] range,
        ExtraMaterialsDescription extra,
        boolean keyWrapExpected,
        AWSKMS kms) {
        return fromInstructionFile0(instFile, kekMaterialAccessor,
                                    securityProvider, alwaysUseSecurityProvider, range, extra,
                                    keyWrapExpected, kms);
    }
449945
func Encrypt(payload []byte, keyalg jwa.KeyEncryptionAlgorithm, key interface{}, contentalg jwa.ContentEncryptionAlgorithm, compressalg jwa.CompressionAlgorithm) ([]byte, error) {
	contentcrypt, err := NewAesCrypt(contentalg)
	if err != nil {
		return nil, errors.Wrap(err, `failed to create AES encrypter`)
	}

	var keyenc KeyEncrypter
	var keysize int
	switch keyalg {
	case jwa.RSA1_5:
		pubkey, ok := key.(*rsa.PublicKey)
		if !ok {
			return nil, errors.New("invalid key: *rsa.PublicKey required")
		}
		keyenc, err = NewRSAPKCSKeyEncrypt(keyalg, pubkey)
		if err != nil {
			return nil, errors.Wrap(err, "failed to create RSA PKCS encrypter")
		}
		keysize = contentcrypt.KeySize() / 2
	case jwa.RSA_OAEP, jwa.RSA_OAEP_256:
		pubkey, ok := key.(*rsa.PublicKey)
		if !ok {
			return nil, errors.New("invalid key: *rsa.PublicKey required")
		}
		keyenc, err = NewRSAOAEPKeyEncrypt(keyalg, pubkey)
		if err != nil {
			return nil, errors.Wrap(err, "failed to create RSA OAEP encrypter")
		}
		keysize = contentcrypt.KeySize() / 2
	case jwa.A128KW, jwa.A192KW, jwa.A256KW:
		sharedkey, ok := key.([]byte)
		if !ok {
			return nil, errors.New("invalid key: []byte required")
		}
		keyenc, err = NewKeyWrapEncrypt(keyalg, sharedkey)
		if err != nil {
			return nil, errors.Wrap(err, "failed to create key wrap encrypter")
		}
		keysize = contentcrypt.KeySize()
		switch aesKeySize := keysize / 2; aesKeySize {
		case 16, 24, 32:
		default:
			return nil, errors.Errorf("unsupported keysize %d (from content encryption algorithm %s). consider using content encryption that uses 32, 48, or 64 byte keys", keysize, contentalg)
		}
	case jwa.ECDH_ES_A128KW, jwa.ECDH_ES_A192KW, jwa.ECDH_ES_A256KW:
		pubkey, ok := key.(*ecdsa.PublicKey)
		if !ok {
			return nil, errors.New("invalid key: *ecdsa.PublicKey required")
		}
		keyenc, err = NewEcdhesKeyWrapEncrypt(keyalg, pubkey)
		if err != nil {
			return nil, errors.Wrap(err, "failed to create ECDHS key wrap encrypter")
		}
		keysize = contentcrypt.KeySize() / 2
	case jwa.ECDH_ES:
		fallthrough
	case jwa.A128GCMKW, jwa.A192GCMKW, jwa.A256GCMKW:
		fallthrough
	case jwa.PBES2_HS256_A128KW, jwa.PBES2_HS384_A192KW, jwa.PBES2_HS512_A256KW:
		fallthrough
	default:
		if debug.Enabled {
			debug.Printf("Encrypt: unknown key encryption algorithm: %s", keyalg)
		}
		return nil, errors.Wrap(ErrUnsupportedAlgorithm, "failed to create encrypter")
	}

	if debug.Enabled {
		debug.Printf("Encrypt: keysize = %d", keysize)
	}
	enc := NewMultiEncrypt(contentcrypt, NewRandomKeyGenerate(keysize), keyenc)
	msg, err := enc.Encrypt(payload)
	if err != nil {
		if debug.Enabled {
			debug.Printf("Encrypt: failed to encrypt: %s", err)
		}
		return nil, errors.Wrap(err, "failed to encrypt payload")
	}

	return CompactSerialize{}.Serialize(msg)
}
1185744
@Deprecated
    public Cipher encrypt() {
        try {
            Cipher cipher = Secret.getCipher(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getKey());
            return cipher;
        } catch (GeneralSecurityException e) {
            throw new AssertionError(e);
        }
    }
1289371
@SneakyThrows
    public EncryptedAssertion encode(final Assertion samlObject,
                                     final SamlRegisteredService service,
                                     final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) {
        val encrypter = buildEncrypterForSamlObject(samlObject, service, adaptor);
        return encrypter.encrypt(samlObject);
    }
538522
public static String encrypt(String c, String key) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encoded = cipher.doFinal(c.getBytes());
            return new String(Hex.encodeHex(encoded));

        } catch (final Exception e) {
            logger.warn("Could not encrypt string", e);
            return null;
        }
    }
1157033
function SnowflakeService(connectionConfig, httpClient, config)
{
  // validate input
  Errors.assertInternal(Util.isObject(connectionConfig));
  Errors.assertInternal(Util.isObject(httpClient));
  Errors.assertInternal(!Util.exists(config) || Util.isObject(config));

  // if a config object was specified, verify
  // that it has all the information we need
  var tokenInfoConfig;
  if (Util.exists(config))
  {
    Errors.assertInternal(Util.isObject(config));
    Errors.assertInternal(Util.isObject(config.tokenInfo));

    tokenInfoConfig = config.tokenInfo;
  }

  // create a new TokenInfo instance
  var tokenInfo = new TokenInfo(tokenInfoConfig);

  // create state objects for all the different states we can be in
  var stateOptions =
  {
    snowflakeService : this,
    httpClient       : httpClient,
    connectionConfig : connectionConfig,
    tokenInfo        : tokenInfo
  };
  var statePristine     = new StatePristine(stateOptions);
  var stateConnecting   = new StateConnecting(stateOptions);
  var stateConnected    = new StateConnected(stateOptions);
  var stateRenewing     = new StateRenewing(stateOptions);
  var stateDisconnected = new StateDisconnected(stateOptions);

  var currentState;

  /**
   * Transitions to a given state.
   *
   * @param {Object} state
   * @param {Object} [transitionContext]
   */
  var transitionTo = function(state, transitionContext)
  {
    // this check is necessary to make sure we don't re-enter a transient state
    // like Renewing when we're already in it
    if (currentState !== state)
    {
      // if we have a current state, exit it; the null check is necessary
      // because the currentState is undefined at bootstrap time when we
      // transition to the first state
      if (currentState)
      {
        currentState.exit();
      }

      // update the current state
      currentState = state;

      // enter the new state
      currentState.enter(transitionContext);
    }
  };

  /**
   * Transitions to the Pristine state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToPristine = function(transitionContext)
  {
    transitionTo(statePristine, transitionContext);
  };

  /**
   * Transitions to the Connecting state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToConnecting = function(transitionContext)
  {
    transitionTo(stateConnecting, transitionContext);
  };

  /**
   * Transitions to the Connected state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToConnected = function(transitionContext)
  {
    transitionTo(stateConnected, transitionContext);
  };

  /**
   * Transitions to the Renewing state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToRenewing = function(transitionContext)
  {
    transitionTo(stateRenewing, transitionContext);
  };

  /**
   * Transitions to the Disconnected state.
   *
   * {Object} [transitionContext]
   */
  this.transitionToDisconnected = function(transitionContext)
  {
    transitionTo(stateDisconnected, transitionContext);

    // clear the tokens because we're in a fatal state and we don't want the
    // tokens to be available via getConfig() anymore
    tokenInfo.clearTokens();
  };

  /**
   * Returns a configuration object that can be passed to the SnowflakeService
   * constructor to get an equivalent SnowflakeService object.
   *
   * @returns {Object}
   */
  this.getConfig = function()
  {
    return {
      tokenInfo: tokenInfo.getConfig()
    };
  };

  /**
   * Establishes a connection to Snowflake.
   *
   * @param {Object} options
   */
  this.connect = function(options)
  {
    new OperationConnect(options).validate().execute();
  };

  /**
   * Issues a connect-continue request to Snowflake.
   *
   * @param {Object} [options]
   */
  this.continue = function(options)
  {
    new OperationContinue(options).validate().execute();
  };

  /**
   * Issues a generic request to Snowflake.
   *
   * @param {Object} options
   */
  this.request = function(options)
  {
    new OperationRequest(options).validate().execute();
  };

  /**
   * Terminates the current connection to Snowflake.
   *
   * @param {Object} options
   */
  this.destroy = function(options)
  {
    new OperationDestroy(options).validate().execute();
  };

  /**
   * Creates a new OperationAbstract.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationAbstract(options)
  {
    this.options = options;
  }

  /**
   * Validates the operation options.
   *
   * @returns {Object} the operation.
   */
  OperationAbstract.prototype.validate = function()
  {
    return this;
  };

  /**
   * Executes the operation.
   */
  OperationAbstract.prototype.execute = function(){};

  /**
   * Creates a new OperationConnect.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationConnect(options)
  {
    OperationAbstract.apply(this, arguments);
  }

  Util.inherits(OperationConnect, OperationAbstract);

  /**
   * @inheritDoc
   */
  OperationConnect.prototype.validate = function()
  {
    // verify that the options object contains a callback function
    var options = this.options;
    Errors.assertInternal(
        (Util.isObject(options) && Util.isFunction(options.callback)));

    return this;
  };

  /**
   * @inheritDoc
   */
  OperationConnect.prototype.execute = function()
  {
    currentState.connect(this.options);
  };

  /**
   * Creates a new OperationContinue.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationContinue(options)
  {
    OperationAbstract.apply(this, arguments);
  }

  Util.inherits(OperationContinue, OperationAbstract);

  /**
   * @inheritDoc
   */
  OperationContinue.prototype.validate = function()
  {
    // verify that the options contain a json object
    var options = this.options;
    Errors.assertInternal(
        Util.isObject(options) && Util.isObject(options.json));

    return this;
  };

  /**
   * @inheritDoc
   */
  OperationContinue.prototype.execute = function()
  {
    currentState.continue(this.options);
  };

  /**
   * Creates a new OperationRequest.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationRequest(options)
  {
    OperationAbstract.apply(this, arguments);
  }

  Util.inherits(OperationRequest, OperationAbstract);

  /**
   * @inheritDoc
   */
  OperationRequest.prototype.validate = function()
  {
    // verify that the options object contains all the necessary information
    var options = this.options;
    Errors.assertInternal(Util.isObject(options));
    Errors.assertInternal(Util.isString(options.method));
    Errors.assertInternal(
        !Util.exists(options.headers) || Util.isObject(options.headers));
    Errors.assertInternal(Util.isString(options.url));
    Errors.assertInternal(
        !Util.exists(options.json) || Util.isObject(options.json));

    return this;
  };

  /**
   * @inheritDoc
   */
  OperationRequest.prototype.execute = function()
  {
    currentState.request(this.options);
  };

  /**
   * Creates a new OperationDestroy.
   *
   * @param {Object} options
   * @constructor
   */
  function OperationDestroy(options)
  {
    OperationAbstract.apply(this, arguments);
  }

  Util.inherits(OperationDestroy, OperationAbstract);

  /**
   * @inheritDoc
   */
  OperationDestroy.prototype.validate = function()
  {
    // verify that the options object contains a callback function
    var options = this.options;
    Errors.assertInternal(Util.isObject(options) &&
        Util.isFunction(options.callback));

    return this;
  };

  /**
   * @inheritDoc
   */
  OperationDestroy.prototype.execute = function()
  {
    // delegate to current state
    currentState.destroy(this.options);
  };

  /* All queued operations will be added to this array */
  var operationQueue = [];

  /**
   * Appends a request operation to the queue.
   *
   * @param {Object} options
   */
  this.enqueueRequest = function(options)
  {
    operationQueue.push(new OperationRequest(options));
  };

  /**
   * Appends a destroy operation to the queue.
   *
   * @param {Object} options
   */
  this.enqueueDestroy = function(options)
  {
    operationQueue.push(new OperationDestroy(options));
  };

  /**
   * Executes all the operations in the queue.
   */
  this.drainOperationQueue = function()
  {
    // execute all the operations in the queue
    for (var index = 0, length = operationQueue.length; index < length; index++)
    {
      operationQueue[index].execute();
    }

    // empty the queue
    operationQueue.length = 0;
  };

  this.isConnected = function()
  {
    return currentState === stateConnected;
  };

  this.getServiceName = function()
  {
    return Parameters.getValue(Parameters.names.SERVICE_NAME);
  };

  this.getClientSessionKeepAlive = function()
  {
    return Parameters.getValue(Parameters.names.CLIENT_SESSION_KEEP_ALIVE);
  };

  this.getClientSessionKeepAliveHeartbeatFrequency = function()
  {
    return Parameters.getValue(Parameters.names.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY);
  };

  // if we don't have any tokens, start out as pristine
  if (tokenInfo.isEmpty())
  {
    this.transitionToPristine();
  }
  else
  {
    // we're already connected
    this.transitionToConnected();
  }
}
627842
public static String encrypt(String data, byte[] key)
    {
        try
        {
            Key k = toSecretKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, k);
            byte[] toByteArray = data.getBytes();
            byte[] encrypted = cipher.doFinal(toByteArray);
            return Hex.encodeHexString(encrypted);
        }
        catch (GeneralSecurityException e)
        {
            throw new RuntimeException("Failed to encrypt.", e);
        }
    }
752215
private ContentCryptoMaterial newContentCryptoMaterial(
            EncryptionMaterialsProvider kekMaterialProvider,
            Provider provider, AmazonWebServiceRequest req) {
        EncryptionMaterials kekMaterials = kekMaterialProvider.getEncryptionMaterials();
        if (kekMaterials == null)
            throw new SdkClientException("No material available from the encryption material provider");
        return buildContentCryptoMaterial(kekMaterials, provider, req);
    }
828265
public static String getString(boolean validate, String key) {
		String value = PROPERTIES.getProperty(key);

		if (value == null && PROPERTIES.containsKey(key + ENC_SUFFIX)) {
			value = PROPERTIES.getProperty(key + ENC_SUFFIX);
			if (value != null) {
				value = StringEncryptorUtil.decrypt(value);
			}
		} else if (value != null && value.trim().startsWith(ENC_PREFIX)) {
			value = value.substring(4);
			value = StringEncryptorUtil.decrypt(value);
		}

		if (validate) {
			if (value == null) {
				throw new RuntimeException("Key not found: " + key);
			} else if (value.trim().length() == 0) {
				throw new RuntimeException("Key without value: " + key);
			}
		}

		return value;
	}
629611
private void useClientCertificateCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useClientCertificateCheckBoxActionPerformed
		// The enable unsafe SSL renegotiation checkbox is independent of using a client certificate (although commonly related)
		// enableUnsafeSSLRenegotiationCheckBox.setEnabled(useClientCertificateCheckBox.isSelected());

		//keyStore tab
		certificatejTabbedPane.setEnabled(useClientCertificateCheckBox.isSelected() );

		keyStoreScrollPane.setEnabled(useClientCertificateCheckBox.isSelected());
		keyStoreList.setEnabled(useClientCertificateCheckBox.isSelected());

		aliasScrollPane.setEnabled(useClientCertificateCheckBox.isSelected());
		aliasTable.setEnabled(useClientCertificateCheckBox.isSelected());

		deleteButton.setEnabled(useClientCertificateCheckBox.isSelected() );
		setActiveButton.setEnabled(useClientCertificateCheckBox.isSelected() );
		showAliasButton.setEnabled(useClientCertificateCheckBox.isSelected() );

		//pkcs12 tab
		fileTextField.setEnabled(useClientCertificateCheckBox.isSelected() );
		browseButton.setEnabled(useClientCertificateCheckBox.isSelected() );
		pkcs12PasswordField.setEnabled(useClientCertificateCheckBox.isSelected() );
		addPkcs12Button.setEnabled(useClientCertificateCheckBox.isSelected() );

		//pkcs11 tab
		driverComboBox.setEnabled(useClientCertificateCheckBox.isSelected() );
		driverButton.setEnabled(useClientCertificateCheckBox.isSelected() );
		pkcs11PasswordField.setEnabled(useClientCertificateCheckBox.isSelected() );
		addPkcs11Button.setEnabled(useClientCertificateCheckBox.isSelected() );
		usePkcs11ExperimentalSliSupportCheckBox.setEnabled(useClientCertificateCheckBox.isSelected());
		usePkcs11ExperimentalSliSupportCheckBox.setSelected(Model.getSingleton().getOptionsParam().getExperimentalFeaturesParam().isExerimentalSliSupportEnabled());

		//actual certificate fields
		certificateTextField.setEnabled(useClientCertificateCheckBox.isSelected() );
		showActiveCertificateButton.setEnabled(useClientCertificateCheckBox.isSelected() );

	}