/* (non-Javadoc)
@see io.jsondb.JsonDBOperations#changeEncryption(io.jsondb.crypto.ICipher)
552748
@SuppressWarnings("unchecked")
  @Override
  public <T> void changeEncryption(ICipher newCipher) {
    if (!encrypted) {
      throw new InvalidJsonDbApiUsageException("DB is not encrypted, nothing to change for EncryptionKey");
    }

    for (Entry<String, Map<Object, ?>> entry : collectionsRef.get().entrySet()) {
      CollectionMetaData cmd = cmdMap.get(entry.getKey());
      if (cmd.hasSecret()) {
        cmd.getCollectionLock().writeLock().lock();
      }
    }
    String collectionName = null;
    try {
      for (Entry<String, Map<Object, ?>> entry : collectionsRef.get().entrySet()) {
        collectionName = entry.getKey();
        Map<Object, T> collection = (Map<Object, T>) entry.getValue();

        CollectionMetaData cmd = cmdMap.get(collectionName);
        if (cmd.hasSecret()) {
          Map<Object, T> reCryptedObjects = new LinkedHashMap<Object, T>();
          for (Entry<Object, T> object : collection.entrySet()) {
            T clonedObject = (T) Util.deepCopy(object.getValue());
            CryptoUtil.decryptFields(clonedObject, cmd, dbConfig.getCipher());
            CryptoUtil.encryptFields(clonedObject, cmd, newCipher);
            //We will reuse the Id in the previous collection, should hopefully not cause any issues
            reCryptedObjects.put(object.getKey(), clonedObject);
          }
          JsonWriter jw = null;
          try {
            jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName));
          } catch (IOException ioe) {
            logger.error("Failed to obtain writer for " + collectionName, ioe);
            throw new JsonDBException("Failed to save " + collectionName, ioe);
          }
          boolean updateResult = jw.updateInJsonFile(collection, reCryptedObjects);
          if (!updateResult) {
            throw new JsonDBException("Failed to write re-crypted collection data to .json files, database might have become insconsistent");
          }
          collection.putAll(reCryptedObjects);
        }
      }
      dbConfig.setCipher(newCipher);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
      logger.error("Error when encrypting value for a @Secret annotated field for entity: " + collectionName, e);
      throw new JsonDBException("Error when encrypting value for a @Secret annotated field for entity: " + collectionName, e);
    } finally {
      for (Entry<String, Map<Object, ?>> entry : collectionsRef.get().entrySet()) {
        CollectionMetaData cmd = cmdMap.get(entry.getKey());
        if (cmd.hasSecret()) {
          cmd.getCollectionLock().writeLock().unlock();
        }
      }
    }
  }
636689
public boolean changePassword(String password, User user) {
		user.setPassword(CryptManager.passwordHash(password));
		this.dao.persist(user);

		return true;
	}
176567
void changeWriteCiphers() throws SSLException {
        if (connectionState != cs_HANDSHAKE
                && connectionState != cs_RENEGOTIATE) {
            throw new SSLProtocolException(
                "State error, change cipher specs");
        }

        // ... create compressor

        CipherBox oldCipher = writeCipher;

        try {
            writeCipher = handshaker.newWriteCipher();
            writeMAC = handshaker.newWriteMAC();
        } catch (GeneralSecurityException e) {
            // "can't happen"
            throw (SSLException)new SSLException
                                ("Algorithm missing:  ").initCause(e);
        }

        // See comment above.
        oldCipher.dispose();

        // reset the flag of the first application record
        isFirstAppOutputRecord = true;
    }
123728
@Override
    public Change decodeChange(UUID changeId, ByteBuffer buf) {
        int sep = getSeparatorIndex(buf);
        Encoding encoding = getEncoding(buf, sep);
        String body = getBody(buf, sep);
        JsonTokener tokener;
        Set<String> tags;

        ChangeBuilder builder = new ChangeBuilder(changeId);
        switch (encoding) {
            case D1:
                builder.with(Deltas.fromString(body));
                break;
            case D2:
                // Spec for D2 is as follows:
                // D2:<tags>:<Delta>
                tokener = new JsonTokener(body);
                tags = FluentIterable.from(tokener.nextArray()).transform(Functions.toStringFunction()).toSet();
                tokener.next(':');
                builder.with(Deltas.fromString(tokener)).with(tags);
                break;
            case D3:
                // Spec for D3 is as follows:
                // D3:<tags>:<change flags>:<Delta>
                tokener = new JsonTokener(body);
                tags = FluentIterable.from(tokener.nextArray()).transform(Functions.toStringFunction()).toSet();
                tokener.next(':');
                boolean isConstant = false;
                boolean isMapDelta = false;
                char changeFlag = tokener.next();
                while (changeFlag != ':' && changeFlag != 0) {
                    // In the future there may be more change flags, though for now we're only interested in
                    // those provided below
                    switch (ChangeFlag.deserialize(changeFlag)) {
                        case CONSTANT_DELTA:
                            isConstant = true;
                            break;
                        case MAP_DELTA:
                            isMapDelta = true;
                            break;
                    }
                    changeFlag = tokener.next();
                }

                // There are numerous circumstances where the expense of parsing a literal map delta is wasted.  For
                // example, with two consecutive literal deltas for the same record the elder is immediately replaced
                // by the latter, so resources spent parsing and instantiating the elder are unnecessary.  Return a lazy
                // map literal instead to defer instantiation until necessary.
                if (isConstant && isMapDelta) {
                    builder.with(Deltas.literal(new LazyJsonMap(body.substring(tokener.pos())))).with(tags);
                } else {
                    // Even if the delta is not a literal map delta there are still benefits to evaluating it lazily.
                    // For example, if a delta is behind a compaction record but has not yet been deleted it won't
                    // be used.
                    builder.with(new LazyDelta(tokener, isConstant)).with(tags);
                }
                break;
            case C1:
                builder.with(JsonHelper.fromJson(body, Compaction.class));
                break;
            case H1:
                builder.with(JsonHelper.fromJson(body, History.class));
                break;
            default:
                throw new UnsupportedOperationException(encoding.name());
        }
        return builder.build();
    }
465835
public void changePassphrase(String oldpassphrase, String newpassphrase)
			throws IOException, InvalidPassphraseException {
		SshKeyPair pair = toKeyPair(oldpassphrase);
		formattedkey = encryptKey(pair, newpassphrase);
	}
1190618
func (s *CreateSecurityConfigurationInput) SetEncryptionConfiguration(v *EncryptionConfiguration) *CreateSecurityConfigurationInput {
	s.EncryptionConfiguration = v
	return s
}
234674
@ShellMethod(key = "generate-key", value = "Generate signing/encryption crypto keys for CAS settings")
    public void generateKey(@ShellOption(value = {"key-size"},
        defaultValue = "256", help = "Key size") final int keySize) {
        LOGGER.info(EncodingUtils.generateJsonWebKey(keySize));
    }
69174
public static int updateEncryptCert(Map<String, String> resData,
			String encoding) {
		return SDKUtil.getEncryptCert(resData, encoding);
	}
883142
public boolean setPublicKey (PublicKey key)
    {
        if (SecureUtil.ciphersSupported(key)) {
            _publicKey = key;
            return true;
        }
        return false;
    }
148655
public void setNew(final String _plainPassword,
                       final String _currentValue)
        throws EFapsException
    {
        initConfig();
        read(_currentValue);
        final ConfigurablePasswordEncryptor passwordEncryptor = new ConfigurablePasswordEncryptor();
        passwordEncryptor.setConfig(this.digesterConfig);
        final String encrypted = passwordEncryptor.encryptPassword(_plainPassword);
        shiftAll();
        this.props.setProperty(PasswordStore.DIGEST + 0, encrypted);
        this.props.setProperty(PasswordStore.ALGORITHM + 0, this.digesterConfig.getAlgorithm());
        this.props.setProperty(PasswordStore.ITERATIONS + 0, this.digesterConfig.getIterations().toString());
        this.props.setProperty(PasswordStore.SALTSIZE + 0, this.digesterConfig.getSaltSizeBytes().toString());
    }
999655
private void initializeEncryptionProvider() {
		if (key != null) {
			try {
				encryptionProvider = EncryptionProviderFactory.getProvider(key);
			} catch (UnsupportedKeySizeException e) {
				throw new RuntimeCryptoException(e.getMessage(), e);
			} catch (UnsupportedAlgorithmException e) {
				throw new RuntimeCryptoException(e.getMessage(), e);
			}
		}
	}
614485
protected void initRC4Encryption(byte[] sharedSecret) {
        log.debug("Shared secret: {}", Hex.encodeHexString(sharedSecret));
        // create output cipher
        log.debug("Outgoing public key [{}]: {}", outgoingPublicKey.length, Hex.encodeHexString(outgoingPublicKey));
        byte[] rc4keyOut = new byte[32];
        // digest is 32 bytes, but our key is 16
        calculateHMAC_SHA256(outgoingPublicKey, 0, outgoingPublicKey.length, sharedSecret, KEY_LENGTH, rc4keyOut, 0);
        log.debug("RC4 Out Key: {}", Hex.encodeHexString(Arrays.copyOfRange(rc4keyOut, 0, 16)));
        try {
            cipherOut = Cipher.getInstance("RC4");
            cipherOut.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(rc4keyOut, 0, 16, "RC4"));
        } catch (Exception e) {
            log.warn("Encryption cipher creation failed", e);
        }
        // create input cipher
        log.debug("Incoming public key [{}]: {}", incomingPublicKey.length, Hex.encodeHexString(incomingPublicKey));
        // digest is 32 bytes, but our key is 16
        byte[] rc4keyIn = new byte[32];
        calculateHMAC_SHA256(incomingPublicKey, 0, incomingPublicKey.length, sharedSecret, KEY_LENGTH, rc4keyIn, 0);
        log.debug("RC4 In Key: {}", Hex.encodeHexString(Arrays.copyOfRange(rc4keyIn, 0, 16)));
        try {
            cipherIn = Cipher.getInstance("RC4");
            cipherIn.init(Cipher.DECRYPT_MODE, new SecretKeySpec(rc4keyIn, 0, 16, "RC4"));
        } catch (Exception e) {
            log.warn("Decryption cipher creation failed", e);
        }
    }
313001
@Modified
    protected synchronized void modify(QuickStartSecurityConfig config) {
        this.config = config;

        validateConfigurationProperties();

        if (urConfigReg == null) {
            registerQuickStartSecurityRegistryConfiguration();
        } else {
            updateQuickStartSecurityRegistryConfiguration();
        }

        unregisterQuickStartSecurityAdministratorRole();
        registerQuickStartSecurityAdministratorRole();
    }
990285
public void setKey(String key) throws CryptoException {
		final int length = key.length();
		if (length < KEY_MIN_LENGTH || length >= SBOX_LENGTH) {
			throw new CryptoException("Key length has to be between {} and {}", KEY_MIN_LENGTH, (SBOX_LENGTH - 1));
		}

		final WriteLock writeLock = this.lock.writeLock();
		writeLock.lock();
		try {
			this.key = StrUtil.utf8Bytes(key);
			this.sbox = initSBox(this.key);
		} finally {
			writeLock.unlock();
		}
	}
625591
@Restricted(NoExternalUse.class) // TODO pending API
    public Cipher encrypt(byte[] iv) {
        try {
            Cipher cipher = Secret.getCipher(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getKey(), new IvParameterSpec(iv));
            return cipher;
        } catch (GeneralSecurityException e) {
            throw new AssertionError(e);
        }
    }
697714
public static base_response change(nitro_service client, sslfips resource) throws Exception {
		sslfips updateresource = new sslfips();
		updateresource.fipsfw = resource.fipsfw;
		return updateresource.perform_operation(client,"update");
	}
197801
func (s *ResultConfigurationUpdates) SetEncryptionConfiguration(v *EncryptionConfiguration) *ResultConfigurationUpdates {
	s.EncryptionConfiguration = v
	return s
}