Sign is called by the library when the server sends a nonce.
The client's NKey should be used to sign the provided value.

@param nonce the nonce to sign
@return the signature for the nonce
770300
public byte[] sign(byte[] nonce) {
        try {
            char[] keyChars = this.readKeyChars();
            NKey nkey =  NKey.fromSeed(keyChars);
            byte[] sig = nkey.sign(nonce);
            nkey.clear();
            return sig;
        } catch (Exception exp) {
            throw new IllegalStateException("problem signing nonce", exp);
        }
    }
763271
public function verifyClientNonce($cnonce)
    {
        $cnonce_cache_key = 'cnonce__'.$cnonce;

        if (empty($this->cache)) {
            return;
        }

        $cnonce_data = $this->cache->get($cnonce_cache_key);
        if ($cnonce_data == 'USED') {
            throw new NonceException('That nonce has already been used');
        }

        $this->cache->add($cnonce_cache_key, 'USED');
    }
210930
public static String sign(@NotNull String val, @NotNull Mac mac) {
        return val + "." + Base64.getEncoder().encodeToString(val.getBytes());
    }
1098031
public function auth($nonce = null, $params = null)
    {
        $params = $params ?: array();

        $client_id = $this->params['client_id'];
        $client_key = $this->params['client_key'];

        // 1) Get nonce
        $nonce = $nonce ?: $this->server->request('auth');

        // 2) Create key hash
        $key_hash = md5("{$client_id}::{$client_key}");

        // 3) Create auth key
        $auth_key = md5("{$nonce}{$client_id}{$key_hash}");

        // 4) Authenticate with client params
        $params['client'] = $client_id;
        $params['key'] = $auth_key;

        if ($this->params['version']) {
            $params['$v'] = $this->params['version'];
        }
        if ($this->params['api']) {
            $params['$api'] = $this->params['api'];
        }
        if ($this->params['session']) {
            $params['$session'] = $this->params['session'];
        }
        if (isset($this->params['route']['client'])) {
            $params['$route'] = $this->params['route'];
        }
        if (isset($_SERVER['REMOTE_ADDR']) && $ip_address = $_SERVER['REMOTE_ADDR']) {
            $params['$ip'] = $ip_address;
        }
        if ($this->cache) {
            $params['$cached'] = $this->cache->get_versions();
        }

        $this->authed = true;
        
        try {
            return $this->server->request('auth', $params);
        } catch (NetworkException $e) {
            $this->request_rescue($e);
            return $this->auth();
        }
    }
553568
public String sign(final String message) throws EncryptionException {
      try {
         Signature sign = Signature.getInstance("SHA1withRSA");
         sign.initSign(privateKey);
         sign.update(message.getBytes(DEFAULT_CHARSET));

         return new String(Base64.encodeBase64(sign.sign()), DEFAULT_CHARSET);
      } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
         throw new EncryptionException("Unable to sign message: ", e);
      }
   }
1159879
public function setNonce($nonce = null)
    {
        $this->nonce = $nonce;
        if ($nonce === null) {
            $this->nonce = new Nonce();
        }
        return $this;
    }
469602
public static String sign(byte[] data, String privateKey) throws Exception {
        String keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return String.valueOf(Base64Utils.encode(signature.sign()));
    }
1350539
public byte[] getChannelConfigurationSignature(ChannelConfiguration channelConfiguration, User signer)
            throws InvalidArgumentException {

        clientCheck();

        Channel systemChannel = Channel.newSystemChannel(this);
        return systemChannel.getChannelConfigurationSignature(channelConfiguration, signer);

    }
473364
@Override
    public void sign(SignableRequest<?> request, AWSCredentials credentials) throws SdkClientException {
        // annonymous credentials, don't sign
        if ( credentials instanceof AnonymousAWSCredentials ) {
            return;
        }

        AWSCredentials sanitizedCredentials = sanitizeCredentials(credentials);

        SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
        String nonce = UUID.randomUUID().toString();

        int timeOffset = request.getTimeOffset();
        Date dateValue = getSignatureDate(timeOffset);
        String date = DateUtils.formatRFC822Date(dateValue);
        boolean isHttps = false;

        if (overriddenDate != null) date = overriddenDate;
        request.addHeader("Date", date);
        request.addHeader("X-Amz-Date", date);

        // AWS3 HTTP requires that we sign the Host header
        // so we have to have it in the request by the time we sign.
        String hostHeader = request.getEndpoint().getHost();
        if (SdkHttpUtils.isUsingNonDefaultPort(request.getEndpoint())) {
            hostHeader += ":" + request.getEndpoint().getPort();
        }
        request.addHeader("Host", hostHeader);

        if ( sanitizedCredentials instanceof AWSSessionCredentials ) {
            addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials);
        }
        byte[] bytesToSign;
        String stringToSign;
        if (isHttps) {
            request.addHeader(NONCE_HEADER, nonce);
            stringToSign = date + nonce;
            bytesToSign = stringToSign.getBytes(UTF8);
        } else {
            String path = SdkHttpUtils.appendUri(request.getEndpoint().getPath(), request.getResourcePath());

            /*
             * AWS3 requires all query params to be listed on the third line of
             * the string to sign, even if those query params will be sent in
             * the request body and not as a query string. POST formatted query
             * params should *NOT* be included in the request payload.
             */
            stringToSign = request.getHttpMethod().toString() + "\n"
                    + getCanonicalizedResourcePath(path) + "\n"
                    + getCanonicalizedQueryString(request.getParameters()) + "\n"
                    + getCanonicalizedHeadersForStringToSign(request) + "\n"
                    + getRequestPayloadWithoutQueryParams(request);
            bytesToSign = hash(stringToSign);
        }
        if (log.isDebugEnabled())
            log.debug("Calculated StringToSign: " + stringToSign);

        String signature = signAndBase64Encode(bytesToSign,
                sanitizedCredentials.getAWSSecretKey(), algorithm);

        StringBuilder builder = new StringBuilder();
        builder.append(isHttps ? HTTPS_SCHEME : HTTP_SCHEME).append(" ");
        builder.append("AWSAccessKeyId=" + sanitizedCredentials.getAWSAccessKeyId() + ",");
        builder.append("Algorithm=" + algorithm.toString() + ",");

        if (!isHttps) {
            builder.append(getSignedHeadersComponent(request) + ",");
        }

        builder.append("Signature=" + signature);
        request.addHeader(AUTHORIZATION_HEADER, builder.toString());
    }
606445
public String sign(String msg) {
        try {
            RSAPrivateKey key = getPrivateKey();
            Signature sig = Signature.getInstance(SIGNING_ALGORITHM + "with" + key.getAlgorithm());
            sig.initSign(key);
            sig.update(msg.getBytes(StandardCharsets.UTF_8));
            return hudson.remoting.Base64.encode(sig.sign());
        } catch (GeneralSecurityException e) {
            throw new SecurityException(e);
        }
    }
739590
@Override
    public String sign(String message, byte[] key) {
        Preconditions.checkNotNull(message);
        Preconditions.checkNotNull(key);
        try {
            // Get an hmac_sha1 key from the raw key bytes
            SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA_1);

            // Get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance(HMAC_SHA_1);
            mac.init(signingKey);

            // Compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(message.getBytes(Charsets.UTF_8));

            // Convert raw bytes to Hex
            return hexToString(rawHmac);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
384192
def generate_nonce():
        
        nonce = ''.join([str(randint(0, 9)) for i in range(8)])
        return HMAC(
            nonce.encode(),
            "secret".encode(),
            sha1
        ).hexdigest()
499997
@Nonnull
  public CSP2SourceList addNonce (@Nonnull @Nonempty final byte [] aNonceValue)
  {
    ValueEnforcer.notEmpty (aNonceValue, "NonceValue");
    return addNonce (Base64.safeEncodeBytes (aNonceValue));
  }
553206
public byte[] sign(byte[] message) {
		try {
			// this way signatureInstance should be thread safe
			final Signature signatureInstance = ((provider == null) || (provider.length() == 0)) ? Signature
					.getInstance(algorithm) : Signature.getInstance(algorithm, provider);
			signatureInstance.initSign(privateKey);
			signatureInstance.update(message);
			return signatureInstance.sign();
		} catch (Exception e) {
			throw new SignatureException("error generating the signature: algorithm=" + algorithm, e);
		}
	}
937559
@SdkProtectedApi
    public static Signer createSigner(String signerType, SignerParams params) {
        Signer signer = createSigner(signerType);

        if (signer instanceof ServiceAwareSigner) {
            ((ServiceAwareSigner) signer).setServiceName(params.getServiceName());
        }

        if (signer instanceof RegionAwareSigner) {
            ((RegionAwareSigner) signer).setRegionName(params.getRegionName());
        }

        return signer;
    }
898669
public byte[] getUpdateChannelConfigurationSignature(UpdateChannelConfiguration updateChannelConfiguration, User signer) throws InvalidArgumentException {

        userContextCheck(signer);

        if (null == updateChannelConfiguration) {

            throw new InvalidArgumentException("channelConfiguration is null");

        }

        try {

            TransactionContext transactionContext = getTransactionContext(signer);

            final ByteString configUpdate = ByteString.copyFrom(updateChannelConfiguration.getUpdateChannelConfigurationAsBytes());

            ByteString sigHeaderByteString = getSignatureHeaderAsByteString(signer, transactionContext);

            ByteString signatureByteSting = transactionContext.signByteStrings(new User[] {signer},
                    sigHeaderByteString, configUpdate)[0];

            return ConfigSignature.newBuilder()
                    .setSignatureHeader(sigHeaderByteString)
                    .setSignature(signatureByteSting)
                    .build().toByteArray();

        } catch (Exception e) {

            throw new InvalidArgumentException(e);
        } finally {
            logger.debug("finally done");
        }
    }
562131
public static boolean checkSignature(String token, String signature,
                                         String timestamp, String nonce) {
        if (hasBlank(token, signature, timestamp, nonce)) {
            return false;
        }
        String[] arr = new String[]{token, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (String anArr : arr) {
            content.append(anArr);
        }
        MessageDigest md;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes("UTF-8"));
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("加密方式异常", e);
        } catch (UnsupportedEncodingException e) {
            LOG.error("编码格式不支持", e);
        }
        return tmpStr != null && tmpStr.equalsIgnoreCase(signature);
    }