Sign jws.

@param key            the key
@param value          the value
@param algHeaderValue the alg header value
@return the byte [ ]
437998
@SneakyThrows
    public static byte[] signJws(final Key key, final byte[] value, final String algHeaderValue) {
        val base64 = EncodingUtils.encodeBase64(value);
        val jws = new JsonWebSignature();
        jws.setEncodedPayload(base64);
        jws.setAlgorithmHeaderValue(algHeaderValue);
        jws.setKey(key);
        jws.setHeader("typ", "JWT");
        return jws.getCompactSerialization().getBytes(StandardCharsets.UTF_8);
    }
38453
protected String signToken(final OidcRegisteredService svc, final JsonWebSignature jws) throws Exception {
        LOGGER.debug("Fetching JSON web key to sign the token for : [{}]", svc.getClientId());
        val jsonWebKey = getJsonWebKeySigningKey();
        LOGGER.debug("Found JSON web key to sign the token: [{}]", jsonWebKey);
        if (jsonWebKey.getPrivateKey() == null) {
            throw new IllegalArgumentException("JSON web key used to sign the token has no associated private key");
        }
        configureJsonWebSignatureForTokenSigning(svc, jws, jsonWebKey);
        return jws.getCompactSerialization();
    }
300422
protected void setHeaderValue() throws MalformedMessageException {

        // Empty header values valid, we'll store a space character for that
        if (null == this.parsedToken) {
            this.parsedToken = new byte[] { BNFHeaders.SPACE };
        }
        if (this.bIsMultiLine) {
            // must append the new value to the old
            byte[] oldValue = this.currentElem.asBytes();
            int size = oldValue.length + this.parsedToken.length + 1;
            if (size > this.limitTokenSize) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Multiline header value too large: " + size);
                }
                throw new MalformedMessageException("Multiline value length: " + size);
            }
            byte[] newValue = new byte[oldValue.length + this.parsedToken.length + 1];
            System.arraycopy(oldValue, 0, newValue, 0, oldValue.length);
            newValue[oldValue.length] = BNFHeaders.SPACE;
            System.arraycopy(this.parsedToken, 0,
                             newValue, oldValue.length + 1, this.parsedToken.length);
            this.currentElem.setByteArrayValue(newValue);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Saved multiline header value [" + this.currentElem.getDebugValue() + "]");
            }
            // note: header is already saved in storage, we're just updating the
            // value with more data. Don't call add header API.
        } else {
            // just save this value itself
            this.currentElem.setByteArrayValue(this.parsedToken);
            addHeader(this.currentElem, FILTER_YES);
        }
        // now that we have the parsed value saved, start tracking changes/removes
        this.currentElem.startTracking();
    }
1162273
def _jws_signature(signdata, privkey, algorithm):
    
    signature = algorithm.sign(privkey, signdata)
    return base64url_encode(signature)
892378
@SneakyThrows
    public static String decryptJwtValue(final Key secretKeyEncryptionKey, final String value) {
        val jwe = new JsonWebEncryption();
        jwe.setKey(secretKeyEncryptionKey);
        jwe.setCompactSerialization(value);
        LOGGER.trace("Decrypting value...");
        try {
            return jwe.getPayload();
        } catch (final JoseException e) {
            if (LOGGER.isTraceEnabled()) {
                throw new DecryptionException(e);
            }
            throw new DecryptionException();
        }
    }
241145
def sign(jwk, jws = nil, header = nil)
      plain_text = to_binary
      if jws.nil?
        jwk = JOSE::JWK.from(jwk)
        jws = jwk.signer
      end
      jws = JOSE::JWS.from(jws).to_map
      if not jws.has_key?('typ')
        jws = jws.put('typ', 'JWT')
      end
      return JOSE::JWK.sign(plain_text, jws, jwk, header)
    end
502327
public static Action header(final String key, final String value) {
        return new Action(input -> {
            input.setHeader(key, value);
            return input;
        });
    }
134423
protected byte[] newSigningKey(AWSCredentials credentials,
            String dateStamp, String regionName, String serviceName) {
        byte[] kSecret = ("AWS4" + credentials.getAWSSecretKey())
                .getBytes(Charset.forName("UTF-8"));
        byte[] kDate = sign(dateStamp, kSecret, SigningAlgorithm.HmacSHA256);
        byte[] kRegion = sign(regionName, kDate, SigningAlgorithm.HmacSHA256);
        byte[] kService = sign(serviceName, kRegion,
                SigningAlgorithm.HmacSHA256);
        return sign(AWS4_TERMINATOR, kService, SigningAlgorithm.HmacSHA256);
    }
578136
def sign(jwk, plain_text, header = nil)
      protected_binary = JOSE.urlsafe_encode64(to_binary)
      payload = JOSE.urlsafe_encode64(plain_text)
      signing_input = signing_input(plain_text, protected_binary)
      signature = JOSE.urlsafe_encode64(alg.sign(jwk, signing_input))
      return signature_to_map(payload, protected_binary, header, jwk, signature)
    end
1107900
public static byte[] signMessage(RSAPrivateKey key, byte[] message)
            throws InvalidKeyException, NoSuchAlgorithmException, SignatureException {
        return signMessage(key, message, DEFAULT_SIGNATURE_ALGORITHM);
    }
150087
public String sign(BoxSignatureAlgorithm algorithm, String key, String webHookPayload, String deliveryTimestamp) {
        return Base64.encode(this.signRaw(algorithm, key, webHookPayload, deliveryTimestamp));
    }
385603
@VisibleForTesting
    Value getValue(final Key key, boolean useReadOnlyCache) {
        Value payload = null;
        try {
            if (useReadOnlyCache) {
                final Value currentPayload = readOnlyCacheMap.get(key);
                if (currentPayload != null) {
                    payload = currentPayload;
                } else {
                    payload = readWriteCacheMap.get(key);
                    readOnlyCacheMap.put(key, payload);
                }
            } else {
                payload = readWriteCacheMap.get(key);
            }
        } catch (Throwable t) {
            logger.error("Cannot get value for key : {}", key, t);
        }
        return payload;
    }
320669
private byte[] signRaw(BoxSignatureAlgorithm algorithm, String key, String webHookPayload,
            String deliveryTimestamp) {
        Mac mac = MAC_POOL.acquire(algorithm.javaProviderName);
        try {
            mac.init(new SecretKeySpec(key.getBytes(UTF_8), algorithm.javaProviderName));
            mac.update(UTF_8.encode(webHookPayload));
            mac.update(UTF_8.encode(deliveryTimestamp));
            return mac.doFinal();
        } catch (InvalidKeyException e) {
            throw new IllegalArgumentException("Invalid key: ", e);
        } finally {
            MAC_POOL.release(mac);
        }
    }
360868
def _verify_jws(self, payload, key):
        """"""
        jws = JWS.from_compact(payload)

        try:
            alg = jws.signature.combined.alg.name
        except KeyError:
            msg = 'No alg value found in header'
            raise SuspiciousOperation(msg)

        if alg != self.OIDC_RP_SIGN_ALGO:
            msg = "The provider algorithm {!r} does not match the client's " \
                  "OIDC_RP_SIGN_ALGO.".format(alg)
            raise SuspiciousOperation(msg)

        if isinstance(key, six.string_types):
            # Use smart_bytes here since the key string comes from settings.
            jwk = JWK.load(smart_bytes(key))
        else:
            # The key is a json returned from the IDP JWKS endpoint.
            jwk = JWK.from_json(key)

        if not jws.verify(jwk):
            msg = 'JWS token verification failed.'
            raise SuspiciousOperation(msg)

        return jws.payload
216442
private static function createJWSAndSign($payload, JWKInterface $signature_key, array $protected_headers = [], $headers = [])
    {
        $jws = self::createJWS($payload);

        $jws = $jws->addSignatureInformation($signature_key, $protected_headers, $headers);

        $complete_headers = array_merge($protected_headers, $headers);
        Assertion::keyExists($complete_headers, 'alg', 'No "alg" parameter set in the header');
        $signer = Signer::createSigner([$complete_headers['alg']]);
        $signer->sign($jws);

        return $jws;
    }
341507
public static function createJWSToCompactJSON($payload, JWKInterface $signature_key, array $protected_headers, LoggerInterface $logger = null)
    {
        $jws = self::createJWSAndSign($payload, $signature_key, $protected_headers, [], $logger);

        return $jws->toCompactJSON(0);
    }
162485
function generateRsJws(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 RSA private key');
  }
  let signer = crypto.createSign(`SHA${bits}`);
  let signature = buf2b64url(signer.update(protect).sign(key));
  return `${protect}.${signature}`;
}