This constructor simplifies instantiation when using HTTPS (REQUIRED!) and symmetric key encryption
358911
public static function fromSymmetricKeyDefaults(string $symmetricKey, int $expirationTime) : self
    {
        return new self(
            new Signer\Hmac\Sha256(),
            $symmetricKey,
            $symmetricKey,
            SetCookie::create(self::DEFAULT_COOKIE)
                ->withSecure(true)
                ->withHttpOnly(true)
                ->withSameSite(SameSite::lax())
                ->withPath('/'),
            new Parser(),
            $expirationTime,
            new SystemClock()
        );
    }
635921
function (sessionKey) {

        //The first 16 bytes (MSB first) will be the key, the next 16 bytes (MSB first) will be the initialization vector (IV), and the final 8 bytes (MSB first) will be the salt.
        var key = new Buffer(16); //just the key... +8); //key plus salt
        var iv = new Buffer(16); //initialization vector

        sessionKey.copy(key, 0, 0, 16); //copy the key
        //sessionKey.copy(key, 16, 32, 40); //append the 8-byte salt
        sessionKey.copy(iv, 0, 16, 32); //copy the iv

        //are we not be doing something with the salt here?

        return crypto.createCipheriv('aes-128-cbc', key, iv);
    }
684887
private byte[] encryptInternal(SecretKeySpec key, String toEncrypt) {
        try {
            Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM + ENCRYPTION_ALGORITHM_MODIFIER);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(toEncrypt.getBytes(ENCODING));
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("Exception during decryptInternal: " + e, e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Exception during encryptInternal: " + e, e);
        }
    }
1003017
private void initWithKey(byte[] key) throws SymmetricKeyException {
        if (key == null)
            throw new SymmetricKeyException("Key cannot be null");
        if (key.length != KEY_SIZE)
            throw new SymmetricKeyException("Key size is not " + KEY_SIZE + "bytes");
        keyData = key;
    }
464140
private void init() throws Exception {
        if (sslContext == null) {
            if (keyStoreInputStream == null && sslConfig.getKeyStorePath() == null &&
		trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) {
                TrustManager[] trust_managers = null;
                if (sslConfig.isTrustAll()) {
                    logger.debug("No keystore or trust store configured.  ACCEPTING UNTRUSTED CERTIFICATES!!!!!");
                    // Create a trust manager that does not validate certificate chains
                    TrustManager trustAllCerts = new X509TrustManager() {
			    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			    }
			    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
			    }

			    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
			    }
			};
                    trust_managers = new TrustManager[] { trustAllCerts };
                }
                
                SecureRandom secureRandom = (sslConfig.getSecureRandomAlgorithm() == null)?null:
		    SecureRandom.getInstance(sslConfig.getSecureRandomAlgorithm());
                sslContext = SSLContext.getInstance(sslConfig.getProtocol());
                sslContext.init(null, trust_managers, secureRandom);
            } else {
                // verify that keystore and truststore
                // parameters are set up correctly               
                checkKeyStore();

                KeyStore keyStore = loadKeyStore();
                KeyStore trustStore = loadTrustStore();

                Collection<? extends CRL> crls = loadCRL(sslConfig.getCrlPath());

                if (sslConfig.isValidateCerts() && keyStore != null) {
                    if (sslConfig.getCertAlias() == null) {
                        List<String> aliases = Collections.list(keyStore.aliases());
			sslConfig.setCertAlias(aliases.size() == 1 ? aliases.get(0) : null);
                    }

                    Certificate cert = sslConfig.getCertAlias() == null?null:
			keyStore.getCertificate(sslConfig.getCertAlias());
                    if (cert == null) {
                        throw new Exception("No certificate found in the keystore" + (sslConfig.getCertAlias() == null ? "":" for alias " + sslConfig.getCertAlias()));
                    }

                    CertificateValidator validator = new CertificateValidator(trustStore, crls);
                    validator.setMaxCertPathLength(sslConfig.getMaxCertPathLength());
                    validator.setEnableCRLDP(sslConfig.isEnableCRLDP());
                    validator.setEnableOCSP(sslConfig.isEnableOCSP());
                    validator.setOcspResponderURL(sslConfig.getOcspResponderURL());
                    validator.validate(keyStore, cert);
                }

                KeyManager[] keyManagers = getKeyManagers(keyStore);
                TrustManager[] trustManagers = getTrustManagers(trustStore, crls);

                SecureRandom secureRandom = (sslConfig.getSecureRandomAlgorithm() == null)?null:
		    SecureRandom.getInstance(sslConfig.getSecureRandomAlgorithm());
                sslContext = (sslConfig.getProvider() == null)?
		    SSLContext.getInstance(sslConfig.getProtocol()):
		    SSLContext.getInstance(sslConfig.getProtocol(), sslConfig.getProvider());
                sslContext.init(keyManagers, trustManagers, secureRandom);

                SSLEngine engine = newSslEngine();
                
                logger.info("Enabled Protocols {} of {}",
			    Arrays.asList(engine.getEnabledProtocols()),
			    Arrays.asList(engine.getSupportedProtocols()));
		logger.debug("Enabled Ciphers {} of {}",
			     Arrays.asList(engine.getEnabledCipherSuites()),
			     Arrays.asList(engine.getSupportedCipherSuites()));
            }
        }
    }
1054317
private static byte[] generateKey(int size) throws SymmetricKeyException {
        if (size <= 0)
            throw new IllegalArgumentException("Size cannot be zero or less than zero.");

        try {
            SecureRandom secureRandom = new SecureRandom();
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(size * 8, secureRandom);
            return keyGenerator.generateKey().getEncoded();
        } catch (NoSuchAlgorithmException e) {
            throw new SymmetricKeyException(e);
        }
    }
130420
private static Object createKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
        Class keyGenClass = lookupKeyGenClass();
        Object keypair = ClassUtil.newInstance(keyGenClass, "RSA", "SHA1WithRSA");
        ClassUtil.applyMethod(keypair, "generate", 2048);
        return keypair;
    }
1134930
function deterministicGenerateK(curve, hash, d, checkSig, nonce) {
    enforceType("Buffer", hash);
    enforceType(BigInteger, d);

    if (nonce) {
        hash = sha256(Buffer.concat([hash, Buffer.alloc(nonce)]));
    }

    // sanity check
    assert.equal(hash.length, 32, "Hash must be 256 bit");

    var x = d.toBuffer(32);
    var k = Buffer.alloc(32);
    var v = Buffer.alloc(32);

    // Step B
    v.fill(1);

    // Step C
    k.fill(0);

    // Step D
    k = HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k);

    // Step E
    v = HmacSHA256(v, k);

    // Step F
    k = HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k);

    // Step G
    v = HmacSHA256(v, k);

    // Step H1/H2a, ignored as tlen === qlen (256 bit)
    // Step H2b
    v = HmacSHA256(v, k);

    var T = BigInteger.fromBuffer(v);

    // Step H3, repeat until T is within the interval [1, n - 1]
    while (T.signum() <= 0 || T.compareTo(curve.n) >= 0 || !checkSig(T)) {
        k = HmacSHA256(Buffer.concat([v, new Buffer([0])]), k);
        v = HmacSHA256(v, k);

        // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
        // Step H2b again
        v = HmacSHA256(v, k);

        T = BigInteger.fromBuffer(v);
    }

    return T;
}
236632
@Override
	public void init(Key key, IvParameterSpec iv) throws InvalidKeyException {
		if(!(key instanceof SecretKey))
			throw new InvalidKeyException();
		int ivLength = iv.getIV().length;
		if(key.getEncoded().length < MIN_KEY_SIZE || key.getEncoded().length < ivLength)
			throw new InvalidKeyException("Key must be longer than " + MIN_KEY_SIZE + " bytes and key must be longer than IV.");
		this.key = key.getEncoded();
		this.iv = iv;
		prehash = Misc.XORintoA(this.key.length == ivLength ? iv.getIV() : Arrays.copyOf(iv.getIV(), this.key.length), this.key);
		blockNo = 0;
		buffer = new ByteQueue(getBlockSize()*2);
		buffer.setResizable(true);
		cfg = true;
	}
473449
function hmacSha256(key, data) {
    if (subtle) {
        var algo = { name: 'HMAC', hash: { name: 'SHA-256' } };
        return subtle.importKey('raw', key, algo, false, ['sign'])
            .then(function(subtleKey) {
                return subtle.sign(algo, subtleKey, data);
            });
    } else if (nodeCrypto) {
        return new Promise(function(resolve) {
            var hmac = nodeCrypto.createHmac('sha256', Buffer.from(key));
            var hash = hmac.update(Buffer.from(data)).digest();
            resolve(hash.buffer);
        });
    } else {
        return Promise.reject(new KdbxError(Consts.ErrorCodes.NotImplemented, 'HMAC-SHA256 not implemented'));
    }
}
760880
private void initCipher(int mode) throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        if (key != null)
        {
            if (params != null)
            {
                if (random != null)
                {
                    cipher.init(mode, key, params, random);
                }
                else
                {
                    cipher.init(mode, key, params);
                }
            }
            else if (spec != null)
            {
                if (random != null)
                {
                    cipher.init(mode, key, spec, random);
                }
                else
                {
                    cipher.init(mode, key, spec);
                }
            }
            else
            {
                if (random != null)
                {
                    cipher.init(mode, key, random);
                }
                else
                {
                    cipher.init(mode, key);
                }
            }
        }
        else
        {
            if (random != null)
            {
                cipher.init(mode, certificate, random);
            }
            else
            {
                cipher.init(mode, certificate);
            }
        }
    }
529268
public static void init(InputStream keyStoreStream, String keyStorePass, String entryName, String entryProtectionParam) {
		if (bypassSecurity) {
			return;
		}

		try {
			KeyStore ks = KeyStore.getInstance("JCEKS");
			ks.load(keyStoreStream, keyStorePass.toCharArray());

			KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) ks.getEntry(entryName,
				new KeyStore.PasswordProtection(entryProtectionParam.toCharArray()));
			SecretKey key = entry.getSecretKey();

			enCipher = Cipher.getInstance(key.getAlgorithm());
			enCipher.init(Cipher.ENCRYPT_MODE, key);

			deCipher = Cipher.getInstance(key.getAlgorithm());
			deCipher.init(Cipher.DECRYPT_MODE, key);

			keyStoreStream.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
344935
function() {
    this.versionMajor = undefined;
    this.versionMinor = undefined;
    this.dataCipherUuid = undefined;
    this.compression = undefined;
    this.masterSeed = undefined;
    this.transformSeed = undefined;
    this.keyEncryptionRounds = undefined;
    this.encryptionIV = undefined;
    this.protectedStreamKey = undefined;
    this.streamStartBytes = undefined;
    this.crsAlgorithm = undefined;
    this.endPos = undefined;
    this.kdfParameters = undefined;
    this.publicCustomData = undefined;
    Object.preventExtensions(this);
}
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);
			}
		}
	}
730960
function Opdata(encryption, hmac) {
  this.encryption = encryption;
  this.hmac = hmac;

  if (this.encryption.length !== 32) {
    throw new Error("Encryption key must be 32 bytes.");
  }

  if (this.hmac.length !== 32) {
    throw new Error("HMAC Key must be 32 bytes");
  }
}
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);
        }
    }
1148325
private CodecCipher setInit(Key key, AlgorithmParameters params, AlgorithmParameterSpec spec, Certificate certificate, SecureRandom random)
    {
        this.key         = key;
        this.params      = params;
        this.spec        = spec;
        this.certificate = certificate;
        this.random      = random;

        return this;
    }