Create encrypted JWT
502686
def create_token(self, data, token_valid_for=180) -> str:
        
        jwt_token = jwt.encode({
            'data': data,
            'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)},
            self.app_secret)
        return Security.encrypt(jwt_token)
891006
def _jws_header(keyid, algorithm):
    """"""
    data = {
        'typ': 'JWT',
        'alg': algorithm.name,
        # 'kid' is used to indicate the public part of the key
        # used during signing.
        'kid': keyid
    }

    datajson = json.dumps(data, sort_keys=True).encode('utf8')
    return base64url_encode(datajson)
249010
def create_token(self, request, **kwargs):
        

        data = {
            "content": self.get_object().id,
            "create_date": get_request_data(request)["create_date"],
            "expire_date": get_request_data(request)["expire_date"]
        }
        serializer = ObfuscatedUrlInfoSerializer(data=data)
        if not serializer.is_valid():
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST,
                content_type="application/json",
            )
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK, content_type="application/json")
550278
function (user_id, cookie, passphrase, callback) {
		var packed_user_id = String.fromCharCode(0, 0, 0, 0, user_id >> 24 & 0xFF, user_id >> 16 & 0xFF, user_id >> 8 & 0xFF, user_id & 0xFF);
		var client_nonce = "";
		for (var i = 0; i < 16; ++i) {
			client_nonce += String.fromCharCode(Math.random() * 256);
		}
		var seed = packed_user_id + unescape(encodeURIComponent(passphrase));
		var data = packed_user_id + _server_nonce + client_nonce;
		var d = ecp.mpn_pack(util.hash_string_to_words(seed));
		var z = ecp.mpn_pack(util.hash_string_to_words(data));
		var r = ecp.mpn_new(8), s = ecp.mpn_new(8);
		ecp.ecp_sign(r, s, ecp.secp224k1_p, ecp.secp224k1_a, ecp.secp224k1_G, ecp.secp224k1_n, d, z, 8);
		request({
			method: "Authenticate",
			user_id: user_id,
			cookie: cookie,
			nonce: btoa(client_nonce),
			signature: [ btoa(util.words_to_string(ecp.mpn_unpack(r))), btoa(util.words_to_string(ecp.mpn_unpack(s))) ],
		}, callback);
	}
616218
public static Jwt decode(String token) {
		int firstPeriod = token.indexOf('.');
		int lastPeriod = token.lastIndexOf('.');

		if (firstPeriod <= 0 || lastPeriod <= firstPeriod) {
			throw new IllegalArgumentException("JWT must have 3 tokens");
		}
		CharBuffer buffer = CharBuffer.wrap(token, 0, firstPeriod);
		// TODO: Use a Reader which supports CharBuffer
		JwtHeader header = JwtHeaderHelper.create(buffer.toString());

		buffer.limit(lastPeriod).position(firstPeriod + 1);
		byte[] claims = b64UrlDecode(buffer);
		boolean emptyCrypto = lastPeriod == token.length() - 1;

		byte[] crypto;

		if (emptyCrypto) {
			if (!"none".equals(header.parameters.alg)) {
				throw new IllegalArgumentException(
						"Signed or encrypted token must have non-empty crypto segment");
			}
			crypto = new byte[0];
		}
		else {
			buffer.limit(token.length()).position(lastPeriod + 1);
			crypto = b64UrlDecode(buffer);
		}
		return new JwtImpl(header, claims, crypto);
	}
537804
def signatureJWT(self, message):
        
        return hmac.new(
            key=self.secretkey,
            msg=message,
            digestmod=hashlib.sha256
        ).hexdigest()
579537
def token_gen_call(username, password):
    """"""
    secret_key = 'super-secret-key-please-change'
    mockusername = 'User2'
    mockpassword = 'Mypassword'
    if mockpassword == password and mockusername == username: # This is an example. Don't do that.
        return {"token" : jwt.encode({'user': username, 'data': 'mydata'}, secret_key, algorithm='HS256')}
    return 'Invalid username and/or password for user: {0}'.format(username)
1022451
def encrypt(self, keys=None, cek="", iv="", **kwargs):
        

        _alg = self["alg"]

        # Find Usable Keys
        if keys:
            keys = self.pick_keys(keys, use="enc")
        else:
            keys = self.pick_keys(self._get_keys(), use="enc")

        if not keys:
            logger.error(KEY_ERR.format(_alg))
            raise NoSuitableEncryptionKey(_alg)

        # Determine Encryption Class by Algorithm
        if _alg in ["RSA-OAEP", "RSA-OAEP-256", "RSA1_5"]:
            encrypter = JWE_RSA(self.msg, **self._dict)
        elif _alg.startswith("A") and _alg.endswith("KW"):
            encrypter = JWE_SYM(self.msg, **self._dict)
        else:  # _alg.startswith("ECDH-ES"):
            encrypter = JWE_EC(**self._dict)
            cek, encrypted_key, iv, params, eprivk = encrypter.enc_setup(
                self.msg, key=keys[0], **self._dict)
            kwargs["encrypted_key"] = encrypted_key
            kwargs["params"] = params

        if cek:
            kwargs["cek"] = cek

        if iv:
            kwargs["iv"] = iv

        for key in keys:
            if isinstance(key, SYMKey):
                _key = key.key
            elif isinstance(key, ECKey):
                _key = key.public_key()
            else:  # isinstance(key, RSAKey):
                _key = key.public_key()

            if key.kid:
                encrypter["kid"] = key.kid

            try:
                token = encrypter.encrypt(key=_key, **kwargs)
                self["cek"] = encrypter.cek if 'cek' in encrypter else None
            except TypeError as err:
                raise err
            else:
                logger.debug(
                    "Encrypted message using key with kid={}".format(key.kid))
                return token
181025
def create_binary_security_token(key_file):
    
    node = etree.Element(
        ns_id('BinarySecurityToken', ns.wssens),
        nsmap={ns.wssens[0]: ns.wssens[1]})
    node.set(ns_id('Id', ns.wsuns), get_unique_id())
    node.set('EncodingType', ns.wssns[1] + 'Base64Binary')
    node.set('ValueType', BINARY_TOKEN_TYPE)

    with open(key_file) as fh:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, fh.read())
        node.text = base64.b64encode(
            crypto.dump_certificate(crypto.FILETYPE_ASN1, cert))
    return node
710597
def encode(self, payload):
        
        token = jwt.encode(payload, self.signing_key, algorithm=self.algorithm)
        return token.decode('utf-8')
389608
function encrypt(data, key) {
    return Promise.resolve().then(function() {
        var bytesLeft = data.byteLength;
        var currentOffset = 0, blockIndex = 0, totalLength = 0;
        var buffers = [];

        var next = function() {
            var blockLength = Math.min(BlockSize, bytesLeft);
            bytesLeft -= blockLength;

            var blockData = data.slice(currentOffset, currentOffset + blockLength);
            return getBlockHmac(key, blockIndex, blockLength, blockData).then(function(blockHash) {
                var blockBuffer = new ArrayBuffer(32 + 4);
                var stm = new BinaryStream(blockBuffer);
                stm.writeBytes(blockHash);
                stm.setUint32(blockLength, true);

                buffers.push(blockBuffer);
                totalLength += blockBuffer.byteLength;

                if (blockData.byteLength > 0) {
                    buffers.push(blockData);
                    totalLength += blockData.byteLength;
                    blockIndex++;
                    currentOffset += blockLength;
                    return next();
                } else {
                    var ret = new Uint8Array(totalLength);
                    var offset = 0;
                    for (var i = 0; i < buffers.length; i++) {
                        ret.set(new Uint8Array(buffers[i]), offset);
                        offset += buffers[i].byteLength;
                    }
                    return ret.buffer;
                }
            });
        };
        return next();
    });
}
39286
function encrypt (str) {
    var cipher = crypto.createCipher(algorithm, key)
      , crypted = cipher.update(str, from, to) + cipher.final(to)
    return crypted;
  }
437877
def convert_to_json_with_mac(self, md5digest, hmacdigest):
        # type: (EncryptionMetadata, str, str) -> dict
        
        # encrypt keys
        enc_content_key = blobxfer.operations.crypto.\
            rsa_encrypt_key_base64_encoded(
                None, self._rsa_public_key, self.symmetric_key)
        enc_sign_key = blobxfer.operations.crypto.\
            rsa_encrypt_key_base64_encoded(
                None, self._rsa_public_key, self.signing_key)
        # generate json
        encjson = {
            EncryptionMetadata._JSON_KEY_ENCRYPTION_MODE:
            EncryptionMetadata._ENCRYPTION_MODE,
            EncryptionMetadata._JSON_KEY_CONTENT_IV:
            blobxfer.util.base64_encode_as_string(self.content_encryption_iv),
            EncryptionMetadata._JSON_KEY_WRAPPEDCONTENTKEY: {
                EncryptionMetadata._JSON_KEY_KEYID: 'private:pem',
                EncryptionMetadata._JSON_KEY_ENCRYPTED_KEY: enc_content_key,
                EncryptionMetadata._JSON_KEY_ENCRYPTED_AUTHKEY: enc_sign_key,
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._ENCRYPTED_KEY_SCHEME,
            },
            EncryptionMetadata._JSON_KEY_ENCRYPTION_AGENT: {
                EncryptionMetadata._JSON_KEY_PROTOCOL:
                EncryptionMetadata._ENCRYPTION_PROTOCOL_VERSION,
                EncryptionMetadata._JSON_KEY_ENCRYPTION_ALGORITHM:
                EncryptionMetadata._ENCRYPTION_ALGORITHM,
            },
            EncryptionMetadata._JSON_KEY_INTEGRITY_AUTH: {
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._AUTH_ALGORITHM,
            },
            EncryptionMetadata._JSON_KEY_KEY_WRAPPING_METADATA: {},
        }
        if md5digest is not None:
            encjson[EncryptionMetadata._JSON_KEY_BLOBXFER_EXTENSIONS] = {
                EncryptionMetadata._JSON_KEY_PREENCRYPTED_MD5: md5digest
            }
        if hmacdigest is not None:
            encjson[EncryptionMetadata._JSON_KEY_INTEGRITY_AUTH][
                EncryptionMetadata._JSON_KEY_MAC] = hmacdigest
        bencjson = json.dumps(
            encjson, sort_keys=True, ensure_ascii=False).encode(
                EncryptionMetadata._AUTH_ENCODING_TYPE)
        encjson = {
            EncryptionMetadata._METADATA_KEY_NAME:
            json.dumps(encjson, sort_keys=True)
        }
        # compute MAC over encjson
        hmacsha256 = hmac.new(self._signkey, digestmod=hashlib.sha256)
        hmacsha256.update(bencjson)
        authjson = {
            EncryptionMetadata._JSON_KEY_AUTH_METAAUTH: {
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._AUTH_ALGORITHM,
                EncryptionMetadata._JSON_KEY_AUTH_ENCODING:
                EncryptionMetadata._AUTH_ENCODING_TYPE,
                EncryptionMetadata._JSON_KEY_MAC:
                blobxfer.util.base64_encode_as_string(hmacsha256.digest()),
            }
        }
        encjson[EncryptionMetadata._METADATA_KEY_AUTH_NAME] = json.dumps(
            authjson, sort_keys=True)
        return encjson
181237
def _make_jwt(self):
        
        now = _helpers.utcnow()
        lifetime = datetime.timedelta(seconds=self._token_lifetime)
        expiry = now + lifetime

        payload = {
            'iss': self._issuer,
            'sub': self._subject,
            'iat': _helpers.datetime_to_secs(now),
            'exp': _helpers.datetime_to_secs(expiry),
            'aud': self._audience,
        }

        payload.update(self._additional_claims)

        jwt = encode(self._signer, payload)

        return jwt, expiry
1234233
def decrypt(self, token, key, cek=None):
        
        if not isinstance(token, JWEnc):
            jwe = JWEnc().unpack(token)
        else:
            jwe = token

        self.jwt = jwe.encrypted_key()
        jek = jwe.encrypted_key()

        _decrypt = RSAEncrypter(self.with_digest).decrypt

        _alg = jwe.headers["alg"]
        if cek:
            pass
        elif _alg == "RSA-OAEP":
            cek = _decrypt(jek, key, 'pkcs1_oaep_padding')
        elif _alg == "RSA-OAEP-256":
            cek = _decrypt(jek, key, 'pkcs1_oaep_256_padding')
        elif _alg == "RSA1_5":
            cek = _decrypt(jek, key)
        else:
            raise NotSupportedAlgorithm(_alg)

        self["cek"] = cek
        enc = jwe.headers["enc"]
        if enc not in SUPPORTED["enc"]:
            raise NotSupportedAlgorithm(enc)

        auth_data = jwe.b64_protected_header()

        msg = self._decrypt(enc, cek, jwe.ciphertext(),
                            auth_data=auth_data,
                            iv=jwe.initialization_vector(),
                            tag=jwe.authentication_tag())

        if "zip" in jwe.headers and jwe.headers["zip"] == "DEF":
            msg = zlib.decompress(msg)

        return msg
1001568
def create_authentication_from_json(values):
        """"""
        key_id = values.get('publicKey')
        authentication_type = values.get('type')
        if not key_id:
            raise ValueError(
                f'Invalid authentication definition, "publicKey" is missing: {values}')

        authentication = {'type': authentication_type, 'publicKey': key_id}

        return authentication
725682
function generateEsJws(protect, bits, key) {
  if (key instanceof Buffer) {
    key = key.toString();
  } else if (typeof key !== 'string') {
    throw new TypeError('Key must be a buffer or a UTF-8 string');
  }
  if (!key.includes('-----BEGIN') || !key.includes('KEY-----')) {
    throw new TypeError('Key must be a PEM formatted EC private key');
  }
  let signer = crypto.createSign(`SHA${bits}`);
  signer.update(protect);
  let size = 32;
  if (bits === 384) {
    size = 48;
  } else if (bits === 512) {
    size = 66;
  }
  let signature = buf2b64url(ecdsa.derToConcat(signer.sign(key), size));
  return `${protect}.${signature}`;
}