Generate a new Fernet token.

@param random a source of entropy for your application
@param key the secret key for encrypting <em>payload</em> and signing the token
@param payload the unencrypted data to embed in the token
@return a unique Fernet token
433886
public static Token generate(final Random random, final Key key, final byte[] payload) {
        final IvParameterSpec initializationVector = generateInitializationVector(random);
        final byte[] cipherText = key.encrypt(payload, initializationVector);
        final Instant timestamp = Instant.now();
        final byte[] hmac = key.sign(supportedVersion, timestamp, initializationVector, cipherText);
        return new Token(supportedVersion, timestamp, initializationVector, cipherText, hmac);
    }
811669
public static OutputStream encrypt(OutputStream outputStream, byte[] key) {
        checkNotNull(outputStream);
        checkNotNull(key);
        AESFastEngine aesEngine = new AESFastEngine();
        PaddedBufferedBlockCipher cipher =
                new PaddedBufferedBlockCipher(aesEngine, new PKCS7Padding());
        cipher.init(true, new KeyParameter(key));
        return new CipherOutputStream(outputStream, cipher);
    }
767240
function(callback) {
    crypto.randomBytes(16, function(err, buffer) {
        if (err) {
            return callback(err);
        }

        return callback(null, buffer.toString('base64'));
    });
}
1141384
def _random(self, key):
        """"""

        if hasattr(key, "encode"):
            key = key.encode('ascii')

        value = (zlib.crc32(key, self.seed) & MAX_VALUE)

        return value * INV_MAX_VALUE
1293858
private Value generatePayload(Key key) {
        Stopwatch tracer = null;
        try {
            String payload;
            switch (key.getEntityType()) {
                case Application:
                    boolean isRemoteRegionRequested = key.hasRegions();

                    if (ALL_APPS.equals(key.getName())) {
                        if (isRemoteRegionRequested) {
                            tracer = serializeAllAppsWithRemoteRegionTimer.start();
                            payload = getPayLoad(key, registry.getApplicationsFromMultipleRegions(key.getRegions()));
                        } else {
                            tracer = serializeAllAppsTimer.start();
                            payload = getPayLoad(key, registry.getApplications());
                        }
                    } else if (ALL_APPS_DELTA.equals(key.getName())) {
                        if (isRemoteRegionRequested) {
                            tracer = serializeDeltaAppsWithRemoteRegionTimer.start();
                            versionDeltaWithRegions.incrementAndGet();
                            versionDeltaWithRegionsLegacy.incrementAndGet();
                            payload = getPayLoad(key,
                                    registry.getApplicationDeltasFromMultipleRegions(key.getRegions()));
                        } else {
                            tracer = serializeDeltaAppsTimer.start();
                            versionDelta.incrementAndGet();
                            versionDeltaLegacy.incrementAndGet();
                            payload = getPayLoad(key, registry.getApplicationDeltas());
                        }
                    } else {
                        tracer = serializeOneApptimer.start();
                        payload = getPayLoad(key, registry.getApplication(key.getName()));
                    }
                    break;
                case VIP:
                case SVIP:
                    tracer = serializeViptimer.start();
                    payload = getPayLoad(key, getApplicationsForVip(key, registry));
                    break;
                default:
                    logger.error("Unidentified entity type: {} found in the cache key.", key.getEntityType());
                    payload = "";
                    break;
            }
            return new Value(payload);
        } finally {
            if (tracer != null) {
                tracer.stop();
            }
        }
    }
892256
public SecretKey generateSecretKey() throws NoSuchAlgorithmException {
        final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        final SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        keyGen.init(256, random);
        return this.secretKey = keyGen.generateKey();
    }
985512
private String getToken(String filename, long timestamp, String secret_key) throws Exception {
        byte[] bsFilename = filename.getBytes(conf.get(PROP_CHARSET, "UTF-8"));
        byte[] bsKey = secret_key.getBytes(conf.get(PROP_CHARSET, "UTF-8"));
        byte[] bsTimestamp = (new Long(timestamp)).toString().getBytes(conf.get(PROP_CHARSET, "UTF-8"));
        byte[] buff = new byte[bsFilename.length + bsKey.length + bsTimestamp.length];
        System.arraycopy(bsFilename, 0, buff, 0, bsFilename.length);
        System.arraycopy(bsKey, 0, buff, bsFilename.length, bsKey.length);
        System.arraycopy(bsTimestamp, 0, buff, bsFilename.length + bsKey.length, bsTimestamp.length);
        return Lang.digest("MD5", buff, null, 1);
    }
252128
public static void setEncryptionKey(final String key) {

		if (key == null) {

			logger.info("set_encryption_key() was called with null parameter, resetting global secret key");

			// reset hash
			secretKeyHash = null;
			return;
		}

		try {

			secretKeyHash = MessageDigest.getInstance(HASH_ALGO).digest(key.getBytes("UTF-8"));

		} catch (Throwable t) {
			logger.error("Unable to set secret key: {}", t.getMessage());
		}
	}
1143530
function seedRandom(buffer) {
  if (!(buffer instanceof Uint8Array)) {
    buffer = new Uint8Array(buffer);
  }
  openpgp.crypto.random.randomBuffer.set(buffer);
}
180607
def derive_fernet_key(input_key):
    """"""
    hkdf = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        info=info,
        backend=backend,
    )
    return base64.urlsafe_b64encode(hkdf.derive(force_bytes(input_key)))
966375
function token(len = 20, encoding = 'hex') {
  return randomBytes(len)
    .then((buf) => {
      return buf.toString(encoding);
    });
}
80195
public static PrivateKey generatePrivateKey(String algorithm, byte[] key) {
		if (null == key) {
			return null;
		}
		return generatePrivateKey(algorithm, new PKCS8EncodedKeySpec(key));
	}
895680
private synchronized Jwt getJwt(ICacheStrategy cacheStrategy, Jwt.Key key) {
        Jwt result = cacheStrategy.getCachedJwt(key);
        if(result == null) {
            //cache an empty JWT first.
            result = new Jwt(key);
            cacheStrategy.cacheJwt(key, result);
        }
        return result;
    }
256130
public String decrypt(String encrytedText, String key) {
        Objects.requireNonNull(encrytedText, Required.ENCRYPTED_TEXT.toString());
        Objects.requireNonNull(key, Required.KEY.toString());

        CipherParameters cipherParameters = new ParametersWithRandom(new KeyParameter(getSizedSecret(key).getBytes(StandardCharsets.UTF_8)));
        this.paddedBufferedBlockCipher.init(false, cipherParameters);
        
        return new String(cipherData(base64Decoder.decode(encrytedText)), StandardCharsets.UTF_8);
    }
63832
private SecretKey generateAESKey(String privateKey, String salt) {
        try {
            byte[] raw = decodeHex(salt);
            KeySpec spec = new PBEKeySpec(privateKey.toCharArray(), raw, iterationCount, keySize);
            SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF_2_WITH_HMAC_SHA_1);
            return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), AES_ECB_ALGORITHM);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException(e);
        }
    }
466335
public static PublicKey generatePublicKey(String algorithm, byte[] key) {
		if (null == key) {
			return null;
		}
		return generatePublicKey(algorithm, new X509EncodedKeySpec(key));
	}
554413
function random(len) {
    if (subtle) {
        return safeRandom(len);
    } else if (nodeCrypto) {
        return new Uint8Array(nodeCrypto.randomBytes(len));
    } else {
        throw new KdbxError(Consts.ErrorCodes.NotImplemented, 'Random not implemented');
    }
}