Parses a countersigned_token and returns the nested recovery token
 WITHOUT verifying any signatures. This should only be used if no user
 context can be identified or if we're extracting issuer information.
173563
def dangerous_unverified_recovery_token(countersigned_token)
      parsed_countersigned_token = RecoveryToken.parse(Base64.strict_decode64(countersigned_token))
      RecoveryToken.parse(parsed_countersigned_token.data)
    end
78064
def verify_token(self, token) -> bool:
        
        try:
            self.data = jwt.decode(Security.decrypt(token), self.app_secret)
            return True
        except (Exception, BaseException) as error:
            self.errors.append(error)
            return False
        return False
570233
def _parse_ident(self):
        
        remainder = self.string[self.pos:]
        ident = re.match(r'\w*', remainder).group(0)
        self.pos += len(ident)
        return ident
477226
def extract_self_cert(signed_raw: str) -> Identity:
        
        lines = signed_raw.splitlines(True)
        n = 0

        version = int(Revocation.parse_field("Version", lines[n]))
        n += 1

        Revocation.parse_field("Type", lines[n])
        n += 1

        currency = Revocation.parse_field("Currency", lines[n])
        n += 1

        issuer = Revocation.parse_field("Issuer", lines[n])
        n += 1

        unique_id = Revocation.parse_field("IdtyUniqueID", lines[n])
        n += 1

        timestamp = Revocation.parse_field("IdtyTimestamp", lines[n])
        n += 1

        signature = Revocation.parse_field("IdtySignature", lines[n])
        n += 1

        return Identity(version, currency, issuer, unique_id, timestamp, signature)
874182
boolean validateIssuer(String consumerConfigId, String issuers, String tokenIssuer) throws InvalidClaimException {
		boolean isIssuer = false;
		if (issuers == null || issuers.isEmpty()) {
			String msg = Tr.formatMessage(tc, "JWT_TRUSTED_ISSUERS_NULL",
					new Object[] { tokenIssuer, consumerConfigId });
			throw new InvalidClaimException(msg);
		}

		StringTokenizer st = new StringTokenizer(issuers, ",");
		while (st.hasMoreTokens()) {
			String iss = st.nextToken().trim();
			if (tc.isDebugEnabled()) {
				Tr.debug(tc, "Trusted issuer: " + iss);
			}
			if (Constants.ALL_ISSUERS.equals(iss) || (tokenIssuer != null && tokenIssuer.equals(iss))) {
				isIssuer = true;
				break;
			}
		}

		if (!isIssuer) {
			String msg = Tr.formatMessage(tc, "JWT_ISSUER_NOT_TRUSTED",
					new Object[] { tokenIssuer, consumerConfigId, issuers });
			throw new InvalidClaimException(msg);
		}
		return isIssuer;
	}
904814
def unparse_signature(signature) :
    ""
    signature = parse_signature(signature)
    if not isinstance(signature, (tuple, list)) :
        signature = [signature]
    #end if
    return \
        DBUS.Signature("".join(t.signature for t in signature))
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]
347930
def verify_signature(self, addr):
        
        return verify(virtualchain.address_reencode(addr), self.get_plaintext_to_sign(), self.sig)
734619
def from_signed_raw(cls: Type[IdentityType], signed_raw: str) -> IdentityType:
        
        n = 0
        lines = signed_raw.splitlines(True)

        version = int(Identity.parse_field("Version", lines[n]))
        n += 1

        Identity.parse_field("Type", lines[n])
        n += 1

        currency = Identity.parse_field("Currency", lines[n])
        n += 1

        pubkey = Identity.parse_field("Issuer", lines[n])
        n += 1

        uid = Identity.parse_field("UniqueID", lines[n])
        n += 1

        ts = BlockUID.from_str(Identity.parse_field("Timestamp", lines[n]))
        n += 1

        signature = Identity.parse_field("Signature", lines[n])

        return cls(version, currency, pubkey, uid, ts, signature)
1104650
function findResponder(issuer, certs, raws) {
  var issuerKey = issuer.tbsCertificate.subjectPublicKeyInfo;
  issuerKey = ocsp.utils.toPEM(
    rfc5280.SubjectPublicKeyInfo.encode(issuerKey, 'der'), 'PUBLIC KEY');

  for (var i = 0; i < certs.length; i++) {
    var cert = certs[i];
    var signAlg = ocsp.utils.sign[cert.signatureAlgorithm.algorithm.join('.')];
    if (!signAlg) {
      throw new Error('Unknown signature algorithm ' +
        cert.signatureAlgorithm.algorithm);
    }

    var verify = crypto.createVerify(signAlg);

    verify.update(raws[i]);
    if (!verify.verify(issuerKey, cert.signature.data))
      throw new Error('Invalid signature');

    var certKey = cert.tbsCertificate.subjectPublicKeyInfo;
    certKey = ocsp.utils.toPEM(
      rfc5280.SubjectPublicKeyInfo.encode(certKey, 'der'), 'PUBLIC KEY');
    return certKey;
  }

  return issuerKey;
}
851933
def decrypt(self, token, signature=None):
        
        binary = rsa.decrypt(token, self.my_privkey)
        if signature:
            rsa.verify(binary, signature, self.his_pubkey)
        return binary
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);
    }
799592
def parse_raw_token(self, raw_token):
        ""
        if raw_token is None:
            return (None, None)
        qs = parse_qs(raw_token)
        token = qs.get('oauth_token', [None])[0]
        secret = qs.get('oauth_token_secret', [None])[0]
        return (token, secret)
716286
def ecdsa_recover_compact(msg32, sig):
    
    assert isinstance(msg32, bytes)
    assert len(msg32) == 32
    _check_signature(sig)
    # Check that recid is of valid value
    recid = ord(sig[64:65])

    if not (recid >= 0 and recid <= 3):
        raise InvalidSignatureError()

    # Setting the pubkey array
    pubkey = ffi.new("secp256k1_pubkey *")

    lib.secp256k1_ecdsa_recover(
        ctx,
        pubkey,
        _parse_to_recoverable_signature(sig),
        msg32
    )

    serialized_pubkey = _serialize_pubkey(pubkey)

    buf = ffi.buffer(serialized_pubkey, 65)
    r = buf[:]
    assert isinstance(r, bytes)
    assert len(r) == 65, len(r)
    return r
1101661
def signingPayloadState(self, identifier=None):
        
        if self.operation.get(TXN_TYPE) == ATTRIB:
            d = deepcopy(super().signingPayloadState(identifier=identifier))
            op = d[OPERATION]
            keyName = {RAW, ENC, HASH}.intersection(set(op.keys())).pop()
            op[keyName] = sha256(op[keyName].encode()).hexdigest()
            return d
        return super().signingPayloadState(identifier=identifier)
974113
def parse_signed_request(self, signed_request):
        '''
        
        '''
        def _b64_normalize(s):
            appendix = '=' * (4 - len(s) % 4)
            return s.replace('-', '+').replace('_', '/') + appendix

        sr = str(signed_request)
        logging.info('parse signed request: %s' % sr)
        enc_sig, enc_payload = sr.split('.', 1)
        sig = base64.b64decode(_b64_normalize(enc_sig))
        data = _parse_json(base64.b64decode(_b64_normalize(enc_payload)))
        if data['algorithm'] != u'HMAC-SHA256':
            return None
        expected_sig = hmac.new(self.client_secret, enc_payload, hashlib.sha256).digest()
        if expected_sig == sig:
            data.user_id = data.uid = data.get('user_id', None)
            data.access_token = data.get('oauth_token', None)
            expires = data.get('expires', None)
            if expires:
                data.expires = data.expires_in = time.time() + expires
            return data
        return None
481711
def VerifyGitkitToken(self, jwt):
    
    certs = self.rpc_helper.GetPublicCert()
    crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400  # 30 days
    parsed = None
    for aud in filter(lambda x: x is not None, [self.project_id, self.client_id]):
      try:
        parsed = crypt.verify_signed_jwt_with_certs(jwt, certs, aud)
      except crypt.AppIdentityError as e:
        if "Wrong recipient" not in e.message:
          return None
      if parsed:
        return GitkitUser.FromToken(parsed)
    return None