Return the secret key used to generate draft mode HMACs. It will be
    randomly generated on first access. Existing draft URLs can be invalidated
    by deleting or updating the ``DRAFT_SECRET_KEY`` setting.
488788
def get_draft_secret_key():
    
    # TODO: Per URL secret keys, so we can invalidate draft URLs for individual
    #       pages. For example, on publish.
    draft_secret_key, created = Text.objects.get_or_create(
        name='DRAFT_SECRET_KEY',
        defaults=dict(
            value=get_random_string(50),
        ))
    return draft_secret_key.value
772964
def get_crypt_key(key_path):
    
    key_path = os.path.expanduser(key_path)
    if os.path.exists(key_path):
        with open(key_path, 'r') as data:
            key = data.read()
    else:
        key = Fernet.generate_key()
        with open(key_path, 'w') as output:
            output.write(key)

    return key
677652
def sign_hmac(secret, payload)
      secret = secret.encode('ASCII')
      payload = payload.encode('ASCII')

      # Decode the private key
      raw_key = Base64.urlsafe_decode64(secret)

      # Create a signature using the private key and the URL
      digest = OpenSSL::Digest.new('sha1')
      raw_signature = OpenSSL::HMAC.digest(digest, raw_key, payload)

      # Encode the signature into base64 for url use form.
      signature =  Base64.urlsafe_encode64(raw_signature)
      return signature
    end
69089
def get_draft(self):
        
        if self.is_draft:
            return self
        elif self.is_published:
            draft = self.publishing_draft
            # Previously the reverse relation could be `DraftItemBoobyTrapped`
            # in some cases. This should be fixed by extra monkey-patching of
            # the `publishing_draft` field in icekit.publishing.apps, but we
            # will leave this extra sanity check here just in case.
            if hasattr(draft, 'get_draft_payload'):
                draft = draft.get_draft_payload()
            return draft
        raise ValueError(  # pragma: no cover
            "Publishable object %r is neither draft nor published" % self)
1324459
public static SecretKey generateKey(String cipherAlgorithm) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(cipherAlgorithm);
        keyGenerator.init(secureRandom);

        return keyGenerator.generateKey();
    }
8295
public static SecretKey newSecretKey() {

        // FYI: AES keys are just random bytes from a strong source of randomness.

        // Get a key generator instance
        KeyGenerator keyGenerator;
        try {
            keyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            try {
                if (SecurityProvider.addProvider()) {
                    keyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
                } else keyGenerator = null;
            } catch (NoSuchAlgorithmException e1) {
                keyGenerator = null;
            }
            if (keyGenerator == null) {
                throw new IllegalStateException("Algorithm unavailable: " + SYMMETRIC_ALGORITHM, e);
            }
        }

        // Generate a key:
        keyGenerator.init(SYMMETRIC_KEY_SIZE);
        return keyGenerator.generateKey();
    }
797614
def get_draft_page_by_id(self, page_id, status='draft'):
        
        url = 'rest/api/content/{page_id}?status={status}'.format(page_id=page_id, status=status)
        return self.get(url)
916371
def initialize_hmac(self):
        # type: (EncryptionMetadata) -> hmac.HMAC
        
        if self._signkey is not None:
            return hmac.new(self._signkey, digestmod=hashlib.sha256)
        else:
            return None
127010
public static String generateSecretAccessKey() {
		final byte[] secretAccessKeyBytes = new byte[30];
		SECURE_RANDOM.nextBytes(secretAccessKeyBytes);
		return StringUtils.chomp(Base64.encodeBase64String(secretAccessKeyBytes));
	}
1319648
def new_credentials():
    
    identifier = binascii.b2a_hex(os.urandom(8)).decode().upper()
    seed = binascii.b2a_hex(os.urandom(32))  # Corresponds to private key
    return identifier, seed
891033
public SecretKey generateKey() {
        SecretKey key = null;
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(128);
            key = generator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            logger.error("Unable to generate AES key", e);
        }

        return key;
    }
81291
def access_key(self):
        
        credential = self.query_parameters.get(_x_amz_credential)
        if credential is not None:
            credential = url_unquote(credential[0])
        else:
            credential = self.authorization_header_parameters.get(_credential)

            if credential is None:
                raise AttributeError("Credential was not passed in the request")
        try:
            key, scope = credential.split("/", 1)
        except ValueError:
            raise AttributeError("Invalid request credential: %r" % credential)

        if scope != self.credential_scope:
            raise AttributeError("Incorrect credential scope: %r (wanted %r)" %
                                 (scope, self.credential_scope))

        return key
1293781
def get_hash(key: str) -> int:
    
    # 4294967295 == 2**32 - 1 which is the maximum allowable seed for a `numpy.random.RandomState`.
    return int(hashlib.sha1(key.encode('utf8')).hexdigest(), 16) % 4294967295
473204
def gen_random_key(size=32):
    
    import os
    if hasattr(os, "urandom"): # Python 2.4+
        return os.urandom(size)

    # Try using PyCrypto if available
    try:
        from Crypto.Util.randpool import RandomPool
        from Crypto.Hash import SHA256
        return RandomPool(hash=SHA256).get_bytes(size)

    except ImportError:
        print >>sys.stderr, "WARNING: The generated key will not be cryptographically-secure key. Consider using Python 2.4+ to generate the key, or install PyCrypto."

        # Stupid random generation
        import random
        L = []
        for i in range(size):
            L.append(chr(random.randint(0, 255)))
        return "".join(L)
733686
def generate_hotp(secret, counter=4):
    
    # https://tools.ietf.org/html/rfc4226
    msg = struct.pack('>Q', counter)
    digest = hmac.new(to_bytes(secret), msg, hashlib.sha1).digest()

    ob = digest[19]
    if PY2:
        ob = ord(ob)

    pos = ob & 15
    base = struct.unpack('>I', digest[pos:pos + 4])[0] & 0x7fffffff
    token = base % 1000000
    return token
292130
def get_hashed_signature(self, url):
        
        data = "%s%s" % (url, self.association_id)
        if self.session_id:
            data = "%s%s" % (data, self.session_id)
        data_b = bytearray(data, 'utf-8')
        secret_key = base64.b64decode(self.secret_key)
        secret_b = bytearray(secret_key)

        hashed = hmac.new(secret_b, data_b, sha1).digest()
        return base64.b64encode(hashed).decode("utf-8")
601801
def derive_key_block(self, master_secret, server_random,
                         client_random, req_len):
        
        seed = server_random + client_random
        if self.tls_version <= 0x0300:
            return self.prf(master_secret, seed, req_len)
        else:
            return self.prf(master_secret, b"key expansion", seed, req_len)