If a {@code SignMessage} exists the method will decrypt it (if needed).
328933
@Override
  public void processRequest(ProfileRequestContext<?, ?> context) throws ExternalAutenticationErrorCodeException {

    final String logId = this.getLogString(context);
    boolean isSignatureService = this.isSignatureServicePeer(context);

    SignMessageContext signMessageContext = this.getSignMessageContext(context);
    if (signMessageContext == null) {

      // If the peer is a signature service and has only requested a sigmessage LoA we report an error.
      //
      if (isSignatureService) {
        AuthnContextClassContext authnContextClassContext = this.authnContextService.getAuthnContextClassContext(context);
        for (String loa : authnContextClassContext.getAuthnContextClassRefs()) {
          if (this.isSignMessageURI(loa)) {
            log.info("SP has requested '{}' but did not include SignMessage, removing ... [{}]", loa, logId);
            authnContextClassContext.deleteAuthnContextClassRef(loa);
          }
        }
        if (authnContextClassContext.isEmpty()) {
          final String msg = "No valid AuthnContext URI:s were specified in AuthnRequest";
          log.info("{} - can not proceed [{}]", msg, logId);
          throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
        }
      }
    }
    else {
      // If an ordinary SP included a SignMessage in the request, we simply ignore it.
      //
      if (!isSignatureService) {
        log.warn("Requesting SP is not a signature service, but included SignMessage extension, ignoring ... [{}]", logId);
        AuthenticationContext authnContext = authenticationContextLookupStrategy.apply(context);
        if (authnContext == null) {
          log.error("No AuthenticationContext available [{}]", this.getLogString(context));
          throw new ExternalAutenticationErrorCodeException(AuthnEventIds.INVALID_AUTHN_CTX, "Missing AuthenticationContext");
        }
        authnContext.removeSubcontext(SignMessageContext.class);
      }
      // Else, make additional checks and decrypt.
      //
      else {

        // Decrypt the message
        //
        if (signMessageContext.getSignMessage().getEncryptedMessage() != null) {
          try {
            Message cleartextMessage = this.signatureSupportKeyService.decrypt(signMessageContext.getSignMessage());
            log.debug("SignMessage was successfully decrypted [{}]", logId);
            signMessageContext.setClearTextMessage(cleartextMessage);
          }
          catch (DecryptionException e) {
            final String msg = String.format("Failed to decrypt SignMessage - %s", e.getMessage());
            log.error("{} [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SIGN_MESSAGE_DECRYPTION_ERROR, msg);
          }
        }
        else {
          log.debug("SignMessage was not encrypted [{}]", logId);
        }

        if (!this.supportsMimeType(signMessageContext.getMimeType())) {
          log.warn("IdP does not support display of SignMessage with type '{}' [{}]", signMessageContext.getMimeType(), logId);
          signMessageContext.setDoDisplayMessage(false);

          if (signMessageContext.mustShow()) {
            throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SIGN_MESSAGE_TYPE_NOT_SUPPORTED,
              "Unsupported SignMessage mime type");
          }
        }
        // If the SignMessage element from the signature request includes a MustShow attribute with the value true, the
        // Signature Service MUST require that the provided sign message is displayed by the Identity Provider, by
        // including a sigmessage authentication context URI.
        //
        if (signMessageContext.mustShow()) {
          AuthnContextClassContext authnContextClassContext = this.authnContextService.getAuthnContextClassContext(context);
          for (String loa : authnContextClassContext.getAuthnContextClassRefs()) {
            if (!this.isSignMessageURI(loa)) {
              log.info("SP has requested the SignMessage must be displayed, removing '{}' ... [{}]", loa, logId);
              authnContextClassContext.deleteAuthnContextClassRef(loa);
            }
          }
          if (authnContextClassContext.isEmpty()) {
            final String msg = "No valid sigmessage AuthnContext URI:s were specified in AuthnRequest";
            log.info("{} - can not proceed [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
          }
        }

        signMessageContext.setDoDisplayMessage(true);
      }
    }

  }
208182
private boolean tryCreateSignatureVerifier() {
        long t = System.currentTimeMillis();
        if (t - lastKeyFetchTimestamp < oAuth2Properties.getSignatureVerification().getPublicKeyRefreshRateLimit()) {
            return false;
        }
        try {
            SignatureVerifier verifier = signatureVerifierClient.getSignatureVerifier();
            if (verifier != null) {
                setVerifier(verifier);
                lastKeyFetchTimestamp = t;
                log.debug("Public key retrieved from OAuth2 server to create SignatureVerifier");
                return true;
            }
        } catch (Throwable ex) {
            log.error("could not get public key from OAuth2 server to create SignatureVerifier", ex);
        }
        return false;
    }
609721
def verify_message(self, key_or_address, signature, message=None, msg_hash=None):
        
        if isinstance(key_or_address, str):
            # they gave us a private key or a public key already loaded.
            key = self._network.parse.address(key_or_address)
        else:
            key = key_or_address

        try:
            msg_hash = self.hash_for_signing(message) if message is not None else msg_hash
            pair, is_compressed = self.pair_for_message_hash(signature, msg_hash)
        except EncodingError:
            return False
        return self.pair_matches_key(pair, key, is_compressed)
509384
public boolean detached_verify(byte [] message, byte [] signature) {
            if (signature.length != signatureLength)
                return false;
            if (theirPublicKey.length != publicKeyLength)
                return false;
            byte [] sm = new byte[signatureLength + message.length];
            byte [] m = new byte[signatureLength + message.length];
            for (int i = 0; i < signatureLength; i++)
                sm[i] = signature[i];
            for (int i = 0; i < message.length; i++)
                sm[i + signatureLength] = message[i];
            return (crypto_sign_open(m, -1, sm, 0, sm.length, theirPublicKey) >= 0);
        }
313143
def sign(payload, keypair):
    """"""
    get_ed25519ll()
    #
    header = {
                "alg": ALG,
                "jwk": {
                    "kty": ALG,  # alg -> kty in jwk-08.
                    "vk": native(urlsafe_b64encode(keypair.vk))
                }
             }

    encoded_header = urlsafe_b64encode(binary(json.dumps(header, sort_keys=True)))
    encoded_payload = urlsafe_b64encode(binary(json.dumps(payload, sort_keys=True)))
    secured_input = b".".join((encoded_header, encoded_payload))
    sig_msg = ed25519ll.crypto_sign(secured_input, keypair.sk)
    signature = sig_msg[:ed25519ll.SIGNATUREBYTES]
    encoded_signature = urlsafe_b64encode(signature)

    return {"recipients":
            [{"header": native(encoded_header),
              "signature": native(encoded_signature)}],
            "payload": native(encoded_payload)}
601694
protected void removeSignature(SAMLObject message) {
        if (message instanceof SignableSAMLObject) {
            final SignableSAMLObject signableMessage = (SignableSAMLObject) message;
            if (signableMessage.isSigned()) {
                log.debug("Removing SAML protocol message signature");
                signableMessage.setSignature(null);
            }
        }
    }
664644
public KeyOperationResult sign(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] value) {
        KeyIdentifier id = new KeyIdentifier(keyIdentifier);
        return sign(id.vault(), id.name(), id.version() == null ? "" : id.version(), algorithm, value);
    }
230005
SignerInfo verify(PKCS7 block, InputStream inputStream)
    throws NoSuchAlgorithmException, SignatureException, IOException {

       try {

            ContentInfo content = block.getContentInfo();
            if (inputStream == null) {
                inputStream = new ByteArrayInputStream(content.getContentBytes());
            }

            String digestAlgname = getDigestAlgorithmId().getName();

            InputStream dataSigned;

            // if there are authenticate attributes, get the message
            // digest and compare it with the digest of data
            if (authenticatedAttributes == null) {
                dataSigned = inputStream;
            } else {

                // first, check content type
                ObjectIdentifier contentType = (ObjectIdentifier)
                       authenticatedAttributes.getAttributeValue(
                         PKCS9Attribute.CONTENT_TYPE_OID);
                if (contentType == null ||
                    !contentType.equals(content.contentType))
                    return null;  // contentType does not match, bad SignerInfo

                // now, check message digest
                byte[] messageDigest = (byte[])
                    authenticatedAttributes.getAttributeValue(
                         PKCS9Attribute.MESSAGE_DIGEST_OID);

                if (messageDigest == null) // fail if there is no message digest
                    return null;

                MessageDigest md = MessageDigest.getInstance(
                        convertToStandardName(digestAlgname));

                byte[] buffer = new byte[4096];
                int read = 0;
                while ((read = inputStream.read(buffer)) != -1) {
                  md.update(buffer, 0 , read);
                }
                byte[] computedMessageDigest = md.digest();

                if (messageDigest.length != computedMessageDigest.length)
                    return null;
                for (int i = 0; i < messageDigest.length; i++) {
                    if (messageDigest[i] != computedMessageDigest[i])
                        return null;
                }

                // message digest attribute matched
                // digest of original data

                // the data actually signed is the DER encoding of
                // the authenticated attributes (tagged with
                // the "SET OF" tag, not 0xA0).
                dataSigned = new ByteArrayInputStream(authenticatedAttributes.getDerEncoding());
            }

            // put together digest algorithm and encryption algorithm
            // to form signing algorithm
            String encryptionAlgname =
                getDigestEncryptionAlgorithmId().getName();

            // Workaround: sometimes the encryptionAlgname is actually
            // a signature name
            String tmp = AlgorithmId.getEncAlgFromSigAlg(encryptionAlgname);
            if (tmp != null) encryptionAlgname = tmp;
            String algname = AlgorithmId.makeSigAlg(
                    digestAlgname, encryptionAlgname);

            Signature sig = Signature.getInstance(algname);
            X509Certificate cert = getCertificate(block);

            if (cert == null) {
                return null;
            }
            if (cert.hasUnsupportedCriticalExtension()) {
                throw new SignatureException("Certificate has unsupported "
                                             + "critical extension(s)");
            }

            // Make sure that if the usage of the key in the certificate is
            // restricted, it can be used for digital signatures.
            // XXX We may want to check for additional extensions in the
            // future.
            boolean[] keyUsageBits = cert.getKeyUsage();
            if (keyUsageBits != null) {
                KeyUsageExtension keyUsage;
                try {
                    // We don't care whether or not this extension was marked
                    // critical in the certificate.
                    // We're interested only in its value (i.e., the bits set)
                    // and treat the extension as critical.
                    keyUsage = new KeyUsageExtension(keyUsageBits);
                } catch (IOException ioe) {
                    throw new SignatureException("Failed to parse keyUsage "
                                                 + "extension");
                }

                boolean digSigAllowed = ((Boolean)keyUsage.get(
                        KeyUsageExtension.DIGITAL_SIGNATURE)).booleanValue();

                boolean nonRepuAllowed = ((Boolean)keyUsage.get(
                        KeyUsageExtension.NON_REPUDIATION)).booleanValue();

                if (!digSigAllowed && !nonRepuAllowed) {
                    throw new SignatureException("Key usage restricted: "
                                                 + "cannot be used for "
                                                 + "digital signatures");
                }
            }

            PublicKey key = cert.getPublicKey();
            sig.initVerify(key);

            byte[] buffer = new byte[4096];
            int read = 0;
            while ((read = dataSigned.read(buffer)) != -1) {
              sig.update(buffer, 0 , read);
            }
            if (sig.verify(encryptedDigest)) {
                return this;
            }

        } catch (IOException e) {
            throw new SignatureException("IO error verifying signature:\n" +
                                         e.getMessage());

        } catch (InvalidKeyException e) {
            throw new SignatureException("InvalidKey: " + e.getMessage());

        }
        return null;
    }
984719
public boolean containsSignatureDef(
      java.lang.String key) {
    if (key == null) { throw new java.lang.NullPointerException(); }
    return internalGetSignatureDef().getMap().containsKey(key);
  }
289903
function decrypt(message) {
  if (this.secure && this.cipher && this.secret) {
    if (this.secret === 'secret') {
      console.warn('PLEASE change default secret password!');
    }
    debug('%s decrypt message with %s', this.name, this.cipher);
    var decipher = crypto.createDecipher(this.cipher, this.secret);
    return Buffer.concat([decipher.update(message), decipher.final()]);
  }
  return message;
}
1176028
def sign_message(self, key, message, verbose=False):
        
        secret_exponent = key.secret_exponent()
        if not secret_exponent:
            raise ValueError("Private key is required to sign a message")

        addr = key.address()

        msg_hash = self.hash_for_signing(message)
        is_compressed = key.is_compressed()

        sig = self.signature_for_message_hash(secret_exponent, msg_hash, is_compressed)

        if not verbose or message is None:
            return sig

        return self.signature_template.format(
            msg=message, sig=sig, addr=addr,
            net_name=self._network_name.upper())
273693
public byte[] crypt(final byte[] msg) {
		final ReadLock readLock = this.lock.readLock();
		readLock.lock();
		byte[] code;
		try {
			final int[] sbox = this.sbox.clone();
			code = new byte[msg.length];
			int i = 0;
			int j = 0;
			for (int n = 0; n < msg.length; n++) {
				i = (i + 1) % SBOX_LENGTH;
				j = (j + sbox[i]) % SBOX_LENGTH;
				swap(i, j, sbox);
				int rand = sbox[(sbox[i] + sbox[j]) % SBOX_LENGTH];
				code[n] = (byte) (rand ^ msg[n]);
			}
		} finally {
			readLock.unlock();
		}
		return code;
	}
806125
@Override
    public String sign(String message) {
        return sign(message, secret.getBytes(Charsets.UTF_8));
    }
791759
@Override
    public Cipher decrypt() {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getKey());
            return cipher;
        } catch (GeneralSecurityException e) {
            throw new AssertionError(e);
        }
    }
1229220
def sign(self, msg):
        '''
        
        '''
        # Allocate a buffer large enough for the signature. Freed by ctypes.
        buf = create_string_buffer(libcrypto.RSA_size(self._rsa))
        msg = salt.utils.stringutils.to_bytes(msg)
        size = libcrypto.RSA_private_encrypt(len(msg), msg, buf, self._rsa, RSA_X931_PADDING)
        if size < 0:
            raise ValueError('Unable to encrypt message')
        return buf[0:size]
333407
def sign(self, msg):
        '''
        
        '''
        if self.__signingkey is None:
            raise KeyTypeError('Wrong key type for operation')
        sig = ffi.new(C_SIGNATURE)
        lib.ed25519_SignMessage(
            sig, self.__signingkey, ffi.NULL, msg, len(msg))
        return ffi.get_bytes(sig)
527962
public boolean verify(byte[] message, byte[] signature) {
		try {
			// this way signatureInstance should be thread safe
			final Signature signatureInstance = ((provider == null) || (provider.length() == 0)) ? Signature
					.getInstance(algorithm) : Signature.getInstance(algorithm, provider);
			signatureInstance.initVerify(publicKey);
			signatureInstance.update(message);
			return signatureInstance.verify(signature);
		} catch (java.security.SignatureException e) {
			return false;
		} catch (Exception e) {
			throw new SignatureException("error verifying signature", e);
		}
	}