Creates a new JWT for the specified principal. Token is signed using
the SecretKey with an HMAC 256 algorithm.

@param claims a Map of all claims
@return a String representation of the generated token
@since 1.0.0
497812
public String createToken(final Map<String, Object> claims) {
        final JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setClaims(claims);
        return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).compact();
    }
13657
public function encode($claims, $ttl = null)
    {
        if (!$this->_key) {
            throw new MisuseException('Jwt key is not set');
        }

        $key = is_string($this->_key) ? $this->_key : $this->_key[0];

        $claims['iat'] = time();
        $claims['exp'] = time() + ($ttl ?: $this->_ttl);

        $header = $this->base64urlEncode(json_encode(['alg' => $this->_alg, 'typ' => 'JWT']));
        $payload = $this->base64urlEncode(json_encode($claims, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $signature = $this->base64urlEncode(hash_hmac(strtr($this->_alg, ['HS' => 'sha']), "$header.$payload", $key, true));

        return "$header.$payload.$signature";
    }
169875
func GenerateToken(claims map[string]interface{}, expiration time.Time) (s string, err error) {
	t := jwt.New(jwt.GetSigningMethod("RS256"))
	t.Header["typ"] = "JWT"
	t.Header["alg"] = "RS256"
	t.Header["kid"] = pubKeyId
	claims["exp"] = expiration.Unix()
	t.Claims = jwt.MapClaims(claims)
	privKey, err := jwt.ParseRSAPrivateKeyFromPEM(privKeyPEMEncoded)
	if err != nil {
		return "", err
	}
	return t.SignedString(privKey)
}
1350726
func (m *Middleware) CreateToken(identity string) (string, error) {
	// For now, the header will be static
	header, err := encode(fmt.Sprintf(`{"typ":%q,"alg":%q}`, typ, alg))
	if err != nil {
		return "encoding header", ErrEncoding
	}

	// Generate claims for user
	claims, err := m.claims(identity)
	if err != nil {
		return "generating claims", err
	}

	claimsJSON, err := json.Marshal(claims)
	if err != nil {
		return "mashalling claims", ErrEncoding
	}

	claimsSet, err := encode(claimsJSON)
	if err != nil {
		return "encoding claims", ErrEncoding
	}

	toSig := strings.Join([]string{header, claimsSet}, ".")

	h := hmac.New(sha256.New, []byte(m.secret))
	h.Write([]byte(toSig))
	sig, err := encode(h.Sum(nil))
	if err != nil {
		return "encoding signature", ErrEncoding
	}

	response := strings.Join([]string{toSig, sig}, ".")
	return response, nil
}
1343133
func (j *JWT) Create(ctx context.Context, user Principal) (Token, error) {
	// Create a new token object, specifying signing method and the claims
	// you would like it to contain.
	claims := &Claims{
		StandardClaims: gojwt.StandardClaims{
			Subject:   user.Subject,
			Issuer:    user.Issuer,
			ExpiresAt: user.ExpiresAt.Unix(),
			IssuedAt:  user.IssuedAt.Unix(),
			NotBefore: user.IssuedAt.Unix(),
		},
		Organization: user.Organization,
		Group:        user.Group,
	}
	token := gojwt.NewWithClaims(gojwt.SigningMethodHS256, claims)
	// Sign and get the complete encoded token as a string using the secret
	t, err := token.SignedString([]byte(j.Secret))
	// this will only fail if the JSON can't be encoded correctly
	if err != nil {
		return "", err
	}
	return Token(t), nil
}
1198950
public function createCustomToken($uid, array $claims = [], \DateTimeInterface $expiresAt = null): Token
    {
        if (count($claims)) {
            $this->builder->set('claims', $claims);
        }

        $this->builder->set('uid', (string) $uid);

        $now = time();
        $expiration = $expiresAt ? $expiresAt->getTimestamp() : $now + (60 * 60);

        $token = $this->builder
            ->setIssuedAt($now)
            ->setExpiration($expiration)
            ->sign($this->signer, $this->privateKey)
            ->getToken();

        $this->builder->unsign();

        return $token;
    }
353723
@Override
    public Builder claimFrom(JwtToken jwt) throws InvalidTokenException {
        if (jwt != null && !jwt.getClaims().isEmpty()) {
            claims.putAll(jwt.getClaims());
            // copyClaimsMap(jwt.getClaims());
        } else {
            String err = Tr.formatMessage(tc, "JWT_INVALID_TOKEN_ERR");// "JWT_INVALID_TOKEN_ERR";
            throw new InvalidTokenException(err);
        }
        return this;
    }
462480
@Override
    public IAuthorizationPrincipal newPrincipal(String key, Class type) {
        final Tuple<String, Class> principalKey = new Tuple<>(key, type);
        final Element element = this.principalCache.get(principalKey);
        // principalCache is self populating, it can never return a null entry
        return (IAuthorizationPrincipal) element.getObjectValue();
    }
321501
public String toJwt() {
        Map<String, Object> headers = new HashMap<>();
        headers.put("typ", "JWT");
        headers.putAll(this.getHeaders());

        JwtBuilder builder =
            Jwts.builder()
                .signWith(this.algorithm, this.secretKey)
                .setHeaderParams(headers)
                .setIssuer(this.issuer)
                .setExpiration(expiration);

        if (this.getClaims() != null) {
            for (Map.Entry<String, Object> entry : this.getClaims().entrySet()) {
                builder.claim(entry.getKey(), entry.getValue());
            }
        }

        if (this.getId() != null) {
            builder.setId(this.getId());
        }

        if (this.getSubject() != null) {
            builder.setSubject(this.getSubject());
        }

        if (this.getNbf() != null) {
            builder.setNotBefore(this.getNbf());
        }

        return builder.compact();
    }
1201401
public static String retrieveMasterToken(String tokenSigningKey) {
        Map<String, Object> claims = new HashMap<>();

        claims.put("*", String.valueOf(READ_UPDATE));

        return Jwts.builder()
                   .setSubject("segmentstoreresource")
                   .setAudience("segmentstore")
                   .setClaims(claims)
                   .signWith(SignatureAlgorithm.HS512, tokenSigningKey.getBytes())
                   .compact();
    }
742700
@Override
    public Builder claimFrom(JwtToken jwt, String claimName) throws InvalidClaimException, InvalidTokenException {
        isValidToken(jwt);
        if (JwtUtils.isNullEmpty(claimName)) {
            String err = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_ERR", new Object[] { claimName });
            throw new InvalidClaimException(err);
        }
        if (jwt.getClaims().get(claimName) != null) {
            claims.put(claimName, jwt.getClaims().get(claimName));
        }
        // else {
        // String err = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_ERR", new
        // Object[] { claimName, "null" });
        // throw new InvalidClaimException(err);
        // }
        return this;
    }
1114918
function JWT (options) {
  options = options || {};
  var optionDefaults = {
    crypto: {
      algorithm: 'HS256'
    },
    header: {
      typ: 'JWT'
    },
    claims: {},
    validations: {}
  };
  _.defaultsDeep(options, optionDefaults);

  // -- Private
  var isHmac = false;
  var isSign = false;
  var isUnsecured = false;
  var validations;

  var algPrefix;
  var algBitLength;
  var algorithm;
  var crypto;

  var privateKey;
  var publicKey;
  var secret;

  var jwtClaims;
  var jwtHeader;

  function processKey (key) {
    if (!_.isUndefined(key)) {
      if (Buffer.isBuffer(key)) {
        return key.toString();
      } else {
        return key;
      }
    } else {
      return key;
    }
  }

  // -- Protected
  this.isHmac = function () {
    return isHmac;
  };

  this.isSign = function () {
    return isSign;
  };

  this.isUnsecured = function () {
    return isUnsecured;
  };

  this.getAlgorithm = function () {
    return algorithm;
  };

  this.getCrypto = function () {
    return crypto;
  };

  this.getHeader = function () {
    return jwtHeader;
  };

  this.getClaims = function () {
    return jwtClaims;
  };

  this.getSecret = function () {
    return secret;
  };

  this.getPrivateKey = function () {
    return privateKey;
  };

  this.getPublicKey = function () {
    return publicKey;
  };

  this.getValidations = function () {
    return validations;
  };

  // Public
  this.setValidations = function (obj) {
    validations = obj || {};
    return this;
  };

  this.setPrivateKey = function (key) {
    privateKey = processKey.bind(this)(key) || undefined;
    return this;
  };

  this.setPublicKey = function (key) {
    publicKey = processKey.bind(this)(key) || undefined;
    return this;
  };

  this.setSecret = function (sec) {
    if (!_.isUndefined(sec)) {
      if (Buffer.isBuffer(sec)) {
        secret =  sec.toString();
      } else {
        secret = sec;
      }
    } else {
      secret = sec;
    }
    return this;
  };

  this.setAlgorithm = function (alg) {
    if (_.has(JWT.getSupportedAlgorithms(), alg)) {
      jwtHeader = _.merge(options.header, { alg: alg.toUpperCase() });
      if (alg === 'NONE') {
        isHmac = false;
        isSign = false;
        isUnsecured = true;
        crypto = '';
      } else {
        algorithm = alg.toUpperCase();
        algPrefix = alg.substring(0,2);
        algBitLength = alg.substring(2,5);

        // Set type key
        if (algPrefix === 'RS'
            || algPrefix === 'ES'
            || algPrefix === 'PS'
        ) {
          isHmac = false;
          isSign = true;
          isUnsecured = false;
          crypto = 'RSA-SHA' + algBitLength;
        } else {
          isHmac = true;
          isSign = false;
          isUnsecured = false;
          crypto = 'sha' + algBitLength;
        }
      }
    } else {
      throw new JWTError(JWT_UNKNOWN_ALGORITHM + ' ' +  alg);
    }
    return this;
  };

  this.setClaims = function(claims) {
    jwtClaims = claims;
    return this;
  };

  //-- Initialization
  // Set header / alg
  this.setAlgorithm(options.crypto.algorithm);

  // Set secret / keys
  if (!_.isUndefined(options.crypto.secret)) {
    this.setSecret(options.crypto.secret);
  }

  if (!_.isUndefined(options.crypto.privateKey)) {
    this.setPrivateKey(options.crypto.privateKey);
  }

  if (!_.isUndefined(options.crypto.publicKey)) {
    this.setPublicKey(options.crypto.publicKey);
  }

  // Set default claims
  this.setClaims(options.claims);

  // Set Validations
  this.setValidations(options.validations);

  // Return instance
  return this;
}
384276
private HashMap<String, String> createTokenRequestHeaders(String grantCode) {
        JSONObject payload = new JSONObject();
        HashMap<String, String> headers;
        try {
            payload.put("code", grantCode);

            KeyPair keyPair = certificateStore.getStoredKeyPair();
            String jws = jsonSigner.sign(keyPair, payload);

            headers = new HashMap<>(1);
            headers.put("X-WL-Authenticate", jws);

        } catch (Exception e) {
            throw new RuntimeException("Failed to create token request headers", e);
        }

        return headers;
    }
895415
@Override
    public JwtToken buildJwt() throws JwtException, InvalidBuilderException {
        // Create JWT here
        // TODO check for default claims?
        JwtConfig config = getConfig(configId);
        JwtToken jwt = new TokenImpl(this, config);

        return jwt;
    }
1028673
public String generate(final Map<String, Object> claims) {
        // claims builder
        final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

        // add claims
        for (final Map.Entry<String, Object> entry : claims.entrySet()) {
            builder.claim(entry.getKey(), entry.getValue());
        }
        if (this.expirationTime != null) {
            builder.expirationTime(this.expirationTime);
        }
        return internalGenerate(builder.build());
    }
230448
public Map<String, Object> validateTokenAndGetClaims(final String token) {
        final CommonProfile profile = validateToken(token);

        final Map<String, Object> claims = new HashMap<>(profile.getAttributes());
        claims.put(JwtClaims.SUBJECT, profile.getId());

        return claims;
    }
103833
static String createAuthorizationSignatureV4(
            HttpServletRequest request, S3AuthorizationHeader authHeader,
            byte[] payload, String uri, String credential)
            throws InvalidKeyException, IOException, NoSuchAlgorithmException,
            S3Exception {
        String canonicalRequest = createCanonicalRequest(request, uri, payload,
                authHeader.hashAlgorithm);
        String algorithm = authHeader.hmacAlgorithm;
        byte[] dateKey = signMessage(
                authHeader.date.getBytes(StandardCharsets.UTF_8),
                ("AWS4" + credential).getBytes(StandardCharsets.UTF_8),
                algorithm);
        byte[] dateRegionKey = signMessage(
                authHeader.region.getBytes(StandardCharsets.UTF_8), dateKey,
                algorithm);
        byte[] dateRegionServiceKey = signMessage(
                authHeader.service.getBytes(StandardCharsets.UTF_8),
                dateRegionKey, algorithm);
        byte[] signingKey = signMessage(
                "aws4_request".getBytes(StandardCharsets.UTF_8),
                dateRegionServiceKey, algorithm);
        String date = request.getHeader(AwsHttpHeaders.DATE);
        if (date == null) {
            date = request.getParameter("X-Amz-Date");
        }
        String signatureString = "AWS4-HMAC-SHA256\n" +
                date + "\n" +
                authHeader.date + "/" + authHeader.region +
                "/s3/aws4_request\n" +
                canonicalRequest;
        byte[] signature = signMessage(
                signatureString.getBytes(StandardCharsets.UTF_8),
                signingKey, algorithm);
        return BaseEncoding.base16().lowerCase().encode(signature);
    }