解析token, 返回解码后的header、payload、signature等
554852
def analysisJWT(self, token):
        
        _header, _payload, _signature = token.split(".")
        data = {
            "header": json.loads(base64.urlsafe_b64decode(str(_header))),
            "payload": json.loads(base64.urlsafe_b64decode(str(_payload))),
            "signature": base64.urlsafe_b64decode(str(_signature))
        }
        logging.debug("analysis token: {0}".format(data))
        return data
832317
def write_basic_header
      HEADER_SIGNATURE.each do |header_item|
        begin
          name, length, type = *header_item
          str = @stream.encode(@obj.header[name], type)
          padded_str = @stream.encode_string_to_length(str, length)
          # puts @stream.index, name, str.unpack(@stream.vr_to_str(type))
          # pp padded_str.unpack(@stream.vr_to_str(type))

          @stream.write padded_str
          @stream.skip length
        rescue StandardError => e
          puts name, length, type, e
          raise e
        end
      end
    end
74989
def sign(self):
        """"""
        payload = self._payload()
        sigin = b'.'.join([self.protected.encode('utf-8'), payload])
        signature = self.engine.sign(self.key, sigin)
        return {'protected': self.protected,
                'payload': payload,
                'signature': base64url_encode(signature)}
1127285
function SignInputPacket(tx, index, coin, ring, type) {
  Packet.call(this);
  this.tx = tx || null;
  this.index = index;
  this.coin = coin || null;
  this.ring = ring || null;
  this.type = type != null ? type : 1;
}
489416
def sign_message(payload, private_key)
      signature_urlencoded = ''

      key = OpenSSL::PKey::RSA.new(private_key)

      payload_decoded = CGI::unescape(payload.chomp('decode'))

      signature = key.sign(OpenSSL::Digest::MD5.new, payload_decoded)
      signature_base64 = Base64.strict_encode64(signature)
      signature_urlencoded = "#{CGI::escape(signature_base64)}decode"

      return signature_urlencoded
    end
816674
def to_s
      # Encode the fixed header
      header = [
        ((type_id.to_i & 0x0F) << 4) |
          (flags[3] ? 0x8 : 0x0) |
          (flags[2] ? 0x4 : 0x0) |
          (flags[1] ? 0x2 : 0x0) |
          (flags[0] ? 0x1 : 0x0)
      ]

      # Get the packet's variable header and payload
      body = encode_body

      # Check that that packet isn't too big
      body_length = body.bytesize
      if body_length > 268_435_455
        raise 'Error serialising packet: body is more than 256MB'
      end

      # Build up the body length field bytes
      loop do
        digit = (body_length % 128)
        body_length = body_length.div(128)
        # if there are more digits to encode, set the top bit of this digit
        digit |= 0x80 if body_length > 0
        header.push(digit)
        break if body_length <= 0
      end

      # Convert header to binary and add on body
      header.pack('C*') + body
    end
233288
@Override
    public String extractSignedToken(String token) {
        String[] chunks = token.split("-", 3);
        if (chunks.length != 3) {
            // Invalid format
            return null;
        }
        String signature = chunks[0];
        String nonce = chunks[1];
        String raw = chunks[2];
        if (constantTimeEquals(signature, sign(nonce + "-" + raw))) {
            return raw;
        } else {
            return null;
        }
    }
733564
function SignPacket(tx, rings, type) {
  Packet.call(this);
  this.tx = tx || null;
  this.rings = rings || [];
  this.type = type != null ? type : 1;
}
966375
function token(len = 20, encoding = 'hex') {
  return randomBytes(len)
    .then((buf) => {
      return buf.toString(encoding);
    });
}
399861
def _oauth10a_signature(
    consumer_token: Dict[str, Any],
    method: str,
    url: str,
    parameters: Dict[str, Any] = {},
    token: Dict[str, Any] = None,
) -> bytes:
    
    parts = urllib.parse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append(
        "&".join(
            "%s=%s" % (k, _oauth_escape(str(v))) for k, v in sorted(parameters.items())
        )
    )

    base_string = "&".join(_oauth_escape(e) for e in base_elems)
    key_elems = [escape.utf8(urllib.parse.quote(consumer_token["secret"], safe="~"))]
    key_elems.append(
        escape.utf8(urllib.parse.quote(token["secret"], safe="~") if token else "")
    )
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1]
216164
def headers
      headers = {}
      headers['Content-Type'] = 'application/octet-stream'
      headers['Ttl']          = ttl
      headers['Urgency']      = urgency

      if @payload.key?(:server_public_key)
        headers['Content-Encoding'] = 'aesgcm'
        headers['Encryption'] = "salt=#{salt_param}"
        headers['Crypto-Key'] = "dh=#{dh_param}"
      end

      if api_key?
        headers['Authorization'] = "key=#{api_key}"
      elsif vapid?
        vapid_headers = build_vapid_headers
        headers['Authorization'] = vapid_headers['Authorization']
        headers['Crypto-Key'] = [headers['Crypto-Key'], vapid_headers['Crypto-Key']].compact.join(';')
      end

      headers
    end
258927
private void parseQuerySignature(boolean lastChunk) {
        ByteBufProcessor processor = null;
        //signature can be any valid JSON item, which get tricky to detect
        //let's try to find out what's the boundary character
        int openPos = responseContent.forEachByte(new WhitespaceSkipper()) - responseContent.readerIndex();
        if (openPos < 0) {
            //only whitespace left in the buffer, need more data
            return;
        }
        char openChar = (char) responseContent.getByte(responseContent.readerIndex() + openPos);
        if (openChar == '{') {
            processor = new ClosingPositionBufProcessor('{', '}', true);
        } else if (openChar == '[') {
            processor = new ClosingPositionBufProcessor('[', ']', true);
        } else if (openChar == '"') {
            processor = new StringClosingPositionBufProcessor();
        } //else this should be a scalar, skip processor

        int closePos;
        if (processor != null) {
            closePos = responseContent.forEachByte(processor) - responseContent.readerIndex();
        } else {
            closePos = findNextChar(responseContent, ',') - 1;
        }
        if (closePos > 0) {
            responseContent.skipBytes(openPos);
            int length = closePos - openPos + 1;
            ByteBuf signature = responseContent.readSlice(length);
            querySignatureObservable.onNext(signature.copy());
        } else {
            //wait for more data
            return;
        }
        //note: the signature section could be absent, so we'll make sure to complete the observable
        // when receiving status since this is in every well-formed response.
        sectionDone();
        queryParsingState = transitionToNextToken(lastChunk);
    }
1234087
def create_token(key, payload):
  
  token = hmac.new(key)
  token.update(json.dumps(payload))
  return token.hexdigest()
222490
def _build_signature(self):
        """"""
        sig_contents = \
            self.payload + "." + \
            b64encode(b"application/xml").decode("ascii") + "." + \
            b64encode(b"base64url").decode("ascii") + "." + \
            b64encode(b"RSA-SHA256").decode("ascii")
        sig_hash = SHA256.new(sig_contents.encode("ascii"))
        cipher = PKCS1_v1_5.new(self.private_key)
        sig = urlsafe_b64encode(cipher.sign(sig_hash))
        key_id = urlsafe_b64encode(bytes(self.author_handle, encoding="utf-8"))
        return sig, key_id
886881
def build_signature(self, user_api_key, user_secret, request):
        """"""
        path = request.get_full_path()
        sent_signature = request.META.get(
            self.header_canonical('Authorization'))
        signature_headers = self.get_headers_from_signature(sent_signature)
        unsigned = self.build_dict_to_sign(request, signature_headers)

        # Sign string and compare.
        signer = HeaderSigner(
            key_id=user_api_key, secret=user_secret,
            headers=signature_headers, algorithm=self.ALGORITHM)
        signed = signer.sign(unsigned, method=request.method, path=path)
        return signed['authorization']
1299523
def _sign_multi(self, payload, signing_keys):
        
        if not isinstance(payload, Mapping):
            raise TypeError('Expecting a mapping object, as only '
                            'JSON objects can be used as payloads.')

        if not isinstance(signing_keys, list):
            raise TypeError("Expecting a list of keys")

        headers = []
        signatures = []
        payload_b64 = base64url_encode(json_encode(payload))

        for sk in signing_keys:
            signing_key = load_signing_key(sk, self.crypto_backend)

            header = self._make_header()
            header_b64 = base64url_encode(json_encode(header))
            signature_b64 = self._make_signature(header_b64, payload_b64, signing_key)

            headers.append(header_b64)
            signatures.append(signature_b64)

        jwt = {
            "header": headers,
            "payload": payload_b64,
            "signature": signatures
        }

        return jwt
1068322
def request_token(self):
        
        client = OAuth1(
            client_key=self._server_cache[self.client.server].key,
            client_secret=self._server_cache[self.client.server].secret,
            callback_uri=self.callback,
        )

        request = {"auth": client}
        response = self._requester(
            requests.post,
            "oauth/request_token",
            **request
        )

        data = parse.parse_qs(response.text)
        data = {
            'token': data[self.PARAM_TOKEN][0],
            'token_secret': data[self.PARAM_TOKEN_SECRET][0]
        }

        return data