Python rsa.verify() Examples

The following are 29 code examples of rsa.verify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rsa , or try the search function .
Example #1
Source File: valid_token.py    From listen-now with MIT License 6 votes vote down vote up
def valid_token():
    resp = requests.get(url = "http://zlclclc.cn/get_token")
    s = eval(resp.json()["signature"])
    signature = base64.decodestring(s)

    crypto = resp.json()["token_message"]
    message = crypto[2:-6]+'\n'

    with open('/home/mmmsc/listen-now/project/Helper/pubkey.pem','r') as f:
        pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())        
    
    v = rsa.verify(message.encode(), signature, pubkey)     
    
    try:
        rsa.verify(message.encode(), signature, pubkey)
        sign_valid = 1
    except:

        sign_valid = 0
    #token = crypto[:110]+'\n'+crypto[112:115]
    token_message = crypto[2:110]+r'\n'+crypto[112:115]      
    parameter = {"sign_valid":sign_valid,"token":token_message}
    valid_key = requests.post(url = "http://zlclclc.cn/exist_token",data = json.dumps(parameter))
    return token_message
#print(valid_token()) 
Example #2
Source File: rsaencrypt.py    From seecode-scanner with GNU General Public License v3.0 6 votes vote down vote up
def verify(self, message, signature, hash_method=None):
        """

        :param message:
        :param signature:
        :param hash_method:
        :return:
        """
        try:
            compare_hash_method = hash_method or self.hash_method
            hash_m = rsa.verify(message.encode(), signature, self.public_key)
            if hash_m == compare_hash_method:
                return True
            else:
                return False
        except:
            return False 
Example #3
Source File: googleplay.py    From InAppPy with MIT License 6 votes vote down vote up
def verify(self, purchase_token: str, product_sku: str, is_subscription: bool = False) -> dict:
        service = build("androidpublisher", "v3", http=self.http)

        if is_subscription:
            result = self.check_purchase_subscription(purchase_token, product_sku, service)
            cancel_reason = int(result.get("cancelReason", 0))

            if cancel_reason != 0:
                raise GoogleError("Subscription is canceled", result)

            ms_timestamp = result.get("expiryTimeMillis", 0)

            if self._ms_timestamp_expired(ms_timestamp):
                raise GoogleError("Subscription expired", result)
        else:
            result = self.check_purchase_product(purchase_token, product_sku, service)
            purchase_state = int(result.get("purchaseState", 1))

            if purchase_state != 0:
                raise GoogleError("Purchase cancelled", result)

        return result 
Example #4
Source File: security.py    From openunipay with MIT License 6 votes vote down vote up
def verify_ali_data(valueDict):
    logger.info('verifying data from ali')
    sign = valueDict['sign']
    # remove sign and sign_type
    del valueDict['sign']
    if 'sign_type' in valueDict:
        del valueDict['sign_type']
    # contact string need to verify
    temp = []
    for key in sorted(valueDict):
        if not valueDict[key]:
            continue
        temp.append('{}={}'.format(key, valueDict[key]))
    tempStr = '&'.join(temp)
    logger.info('string to verify:{}'.format(tempStr))
    return verify(tempStr, sign, settings.ALIPAY['ali_public_key_pem']) 
Example #5
Source File: cli.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        """Verifies files."""

        signature_file = cli_args[1]

        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #6
Source File: cli.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        """Verifies files."""

        signature_file = cli_args[1]

        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #7
Source File: SignatureUtils.py    From alipay-sdk-python-all with Apache License 2.0 5 votes vote down vote up
def verify_with_rsa(public_key, message, sign):
    public_key = fill_public_key_marker(public_key)
    sign = base64.b64decode(sign)
    return bool(rsa.verify(message, sign, rsa.PublicKey.load_pkcs1_openssl_pem(public_key))) 
Example #8
Source File: cli.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        """Verifies files."""

        signature_file = cli_args[1]

        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #9
Source File: cli.py    From plugin.video.bdyun with GNU General Public License v3.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        """Verifies files."""

        signature_file = cli_args[1]

        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #10
Source File: security.py    From openunipay with MIT License 5 votes vote down vote up
def verify(data, sign, pemKeyfile):
    sign = base64.b64decode(sign)
    pubKey = _load_public_key(pemKeyfile)
    result = False
    try:
        rsa.verify(data.encode(), sign, pubKey)
    except rsa.pkcs1.VerificationError:
        result = False
    else:
        result = True
    return result 
Example #11
Source File: googleplay.py    From pyinapp with MIT License 5 votes vote down vote up
def _validate_signature(self, receipt, signature):
        try:
            sig = base64.standard_b64decode(signature)
            return rsa.verify(receipt.encode(), sig, self.public_key)
        except (rsa.VerificationError, TypeError):
            return False 
Example #12
Source File: rsa_backend.py    From python-jose with MIT License 5 votes vote down vote up
def verify(self, msg, sig):
        if not self.is_public():
            warnings.warn("Attempting to verify a message with a private key. "
                          "This is not recommended.")
        try:
            pyrsa.verify(msg, sig, self._prepared_key)
            return True
        except pyrsa.pkcs1.VerificationError:
            return False 
Example #13
Source File: cli.py    From opsbro with MIT License 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        '''Decrypts files.'''

        signature_file = cli_args[1]
        
        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #14
Source File: cli.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        '''Decrypts files.'''

        signature_file = cli_args[1]
        
        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #15
Source File: SignatureUtils.py    From alipay-sdk-python with Apache License 2.0 5 votes vote down vote up
def verify_with_rsa(public_key, message, sign):
    public_key = fill_public_key_marker(public_key)
    sign = base64.b64decode(sign)
    return rsa.verify(message, sign, rsa.PublicKey.load_pkcs1_openssl_pem(public_key)) 
Example #16
Source File: cli.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        """Verifies files."""

        signature_file = cli_args[1]

        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #17
Source File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py    From R-A-M-D-D3-S-M-H with MIT License 5 votes vote down vote up
def checkSign(self, mess, result, pubkey=None):
        """
        验证签名:传入解密后明文、签名、公钥,验证成功返回哈希方法,失败则报错
        :param mess: str
        :param result: bytes
        :param pubkey: 
        :return: str
        """
        if None == pubkey:
            pubkey = self.privkey
        try:
            result = rsa.verify(mess, result, pubkey)
            return result
        except:
            return False 
Example #18
Source File: rpc_client.py    From Mobile-Security-Framework-MobSF with GNU General Public License v3.0 5 votes vote down vote up
def _check_challenge(signature):
    signature = base64.b64decode(signature.data)
    try:
        rsa.verify(challenge.encode('utf-8'), signature, pub_key)
        print('[*] Challenge successfully verified.')
        _revoke_challenge()
    except rsa.pkcs1.VerificationError:
        print('[!] Received wrong signature for challenge.')
        raise Exception('Access Denied.')
    except (TypeError, AttributeError):
        print('[!] Challenge already unset.')
        raise Exception('Access Denied.') 
Example #19
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def to_verify_with_public_key(cls, message, signature, public_path=None, public_key=None):
        # 公钥验签
        public_key_obj = cls.load_public_key(public_path, public_key)
        message = cls.check_message(message)
        result = rsa.verify(message, signature, public_key_obj)
        return result 
Example #20
Source File: validation.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def setup_services(self, parsed_globals):
        self._source_region = parsed_globals.region
        # Use the the same region as the region of the CLI to get locations.
        self.s3_client_provider = S3ClientProvider(
            self._session, self._source_region)
        client_args = {'region_name': parsed_globals.region,
                       'verify': parsed_globals.verify_ssl}
        if parsed_globals.endpoint_url is not None:
            client_args['endpoint_url'] = parsed_globals.endpoint_url
        self.cloudtrail_client = self._session.create_client(
            'cloudtrail', **client_args) 
Example #21
Source File: validation.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def validate(self, bucket, key, public_key, digest_data, inflated_digest):
        """Validates a digest file.

        Throws a DigestError when the digest is invalid.

        :param bucket: Bucket of the digest file
        :param key: Key of the digest file
        :param public_key: Public key bytes.
        :param digest_data: Dict of digest data returned when JSON
            decoding a manifest.
        :param inflated_digest: Inflated digest file contents as bytes.
        """
        try:
            decoded_key = base64.b64decode(public_key)
            public_key = rsa.PublicKey.load_pkcs1(decoded_key, format='DER')
            to_sign = self._create_string_to_sign(digest_data, inflated_digest)
            signature_bytes = binascii.unhexlify(digest_data['_signature'])
            rsa.verify(to_sign, signature_bytes, public_key)
        except PyAsn1Error:
            raise DigestError(
                ('Digest file\ts3://%s/%s\tINVALID: Unable to load PKCS #1 key'
                 ' with fingerprint %s')
                % (bucket, key, digest_data['digestPublicKeyFingerprint']))
        except rsa.pkcs1.VerificationError:
            # Note from the Python-RSA docs: Never display the stack trace of
            # a rsa.pkcs1.VerificationError exception. It shows where in the
            # code the exception occurred, and thus leaks information about
            # the key.
            raise DigestSignatureError(bucket, key) 
Example #22
Source File: cli.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        """Verifies files."""

        signature_file = cli_args[1]

        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #23
Source File: cli.py    From baidupan_shell with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        '''Decrypts files.'''

        signature_file = cli_args[1]
        
        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #24
Source File: cli.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args):
        """Verifies files."""

        signature_file = cli_args[1]

        with open(signature_file, 'rb') as sigfile:
            signature = sigfile.read()

        try:
            rsa.verify(indata, signature, pub_key)
        except rsa.VerificationError:
            raise SystemExit('Verification failed.')

        print('Verification OK', file=sys.stderr) 
Example #25
Source File: googleplay.py    From InAppPy with MIT License 5 votes vote down vote up
def verify_with_result(
        self, purchase_token: str, product_sku: str, is_subscription: bool = False
    ) -> GoogleVerificationResult:
        """Verifies by returning verification result instead of raising an error,
        basically it's and better alternative to verify method."""
        service = build("androidpublisher", "v3", http=self.http)
        verification_result = GoogleVerificationResult({}, False, False)

        if is_subscription:
            result = self.check_purchase_subscription(purchase_token, product_sku, service)
            verification_result.raw_response = result

            cancel_reason = int(result.get("cancelReason", 0))
            if cancel_reason != 0:
                verification_result.is_canceled = True

            ms_timestamp = result.get("expiryTimeMillis", 0)
            if self._ms_timestamp_expired(ms_timestamp):
                verification_result.is_expired = True
        else:
            result = self.check_purchase_product(purchase_token, product_sku, service)
            verification_result.raw_response = result

            purchase_state = int(result.get("purchaseState", 1))
            if purchase_state != 0:
                verification_result.is_canceled = True

        return verification_result 
Example #26
Source File: googleplay.py    From InAppPy with MIT License 5 votes vote down vote up
def _validate_signature(self, receipt: str, signature: str) -> bool:
        try:
            sig = base64.standard_b64decode(signature)
            return rsa.verify(receipt.encode(), sig, self.public_key)
        except (rsa.VerificationError, TypeError, ValueError, BaseException):
            return False 
Example #27
Source File: licensing.py    From fbs with GNU General Public License v3.0 5 votes vote down vote up
def unpack_license_key(key_str, pubkey_args):
    """
    Decode a string of license key data produced by `pack_license_key`. In other
    words, this function is the inverse of `pack_...` above:

        data == unpack_license_key(pack_license_key(data, ...), ...)

    If the given string is not a valid key, `InvalidKey` is raised.

    The parameter `pubkey_args` is a dictionary containing values for the RSA
    fields "n" and "e". It can be generated with fbs's command `init_licensing`.
    """
    try:
        result = json.loads(key_str)
    except ValueError:
        raise InvalidKey() from None
    try:
        signature = result.pop('key')
    except KeyError:
        raise InvalidKey() from None
    try:
        signature_bytes = b64decode(signature.encode('ascii'))
    except ValueError:
        raise InvalidKey() from None
    try:
        rsa.verify(_dumpb(result), signature_bytes, PublicKey(**pubkey_args))
    except VerificationError:
        raise InvalidKey() from None
    return result 
Example #28
Source File: serve.py    From starctf2018 with MIT License 5 votes vote down vote up
def verify_utxo_signature(address, utxo_id, signature):
	try:
		return rsa.verify(utxo_id, signature.decode('hex'), addr_to_pubkey(address))
	except:
		return False 
Example #29
Source File: serve.py    From starctf2018 with MIT License 5 votes vote down vote up
def verifySRCTokenUtxoPayload(self, payload, signature):
		try:
			return rsa.verify(payload, signature.decode('hex'), addr_to_pubkey(self.addr))
		except:
			return False