Python rsa.sign() Examples

The following are 30 code examples of rsa.sign(). 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: bcrypt_hash.py    From listen-now with MIT License 6 votes vote down vote up
def Creat_Return_Token(self, token_crypto):

        tag = bytes("NQZ",encoding="utf8")

        # with open('../project/Helper/pubkey.pem','r') as f:
        #     pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())

        with open('../project/Helper/privkey.pem','r') as f:
            privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())
        token_message = token_crypto
        # token_crypto = rsa.encrypt(token_message.encode(), pubkey)
        # 不进行公钥加密
        # 直接反馈加上标准内容的信息
        token_crypto = bytes(token_crypto, encoding='utf8') + tag
        signature = rsa.sign(token_message.encode(), privkey, 'SHA-1')
        print("token message encode = ", token_message.encode())
        # 利用私钥对信息进行签名
        signature = base64.encodestring(signature)
        return (token_crypto, signature)
        # 返回生成的token 和 sign 签名值 
Example #2
Source File: s3boto3.py    From django-storages with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _strip_signing_parameters(self, url):
        # Boto3 does not currently support generating URLs that are unsigned. Instead we
        # take the signed URLs and strip any querystring params related to signing and expiration.
        # Note that this may end up with URLs that are still invalid, especially if params are
        # passed in that only work with signed URLs, e.g. response header params.
        # The code attempts to strip all query parameters that match names of known parameters
        # from v2 and v4 signatures, regardless of the actual signature version used.
        split_url = urlsplit(url)
        qs = parse_qsl(split_url.query, keep_blank_values=True)
        blacklist = {
            'x-amz-algorithm', 'x-amz-credential', 'x-amz-date',
            'x-amz-expires', 'x-amz-signedheaders', 'x-amz-signature',
            'x-amz-security-token', 'awsaccesskeyid', 'expires', 'signature',
        }
        filtered_qs = ((key, val) for key, val in qs if key.lower() not in blacklist)
        # Note: Parameters that did not have a value in the original query string will have
        # an '=' sign appended to it, e.g ?foo&bar becomes ?foo=&bar=
        joined_qs = ('='.join(keyval) for keyval in filtered_qs)
        split_url = split_url._replace(query="&".join(joined_qs))
        return split_url.geturl() 
Example #3
Source File: s3boto3.py    From django-storages with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _use_cryptography_signer():
    # https://cryptography.io as an RSA backend
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding
    from cryptography.hazmat.primitives.serialization import (
        load_pem_private_key
    )

    def _cloud_front_signer_from_pem(key_id, pem):
        key = load_pem_private_key(
            pem, password=None, backend=default_backend())

        return CloudFrontSigner(
            key_id, lambda x: key.sign(x, padding.PKCS1v15(), hashes.SHA1()))

    return _cloud_front_signer_from_pem 
Example #4
Source File: cloudfront.py    From bash-lambda-layer with MIT License 6 votes vote down vote up
def _run_main(self, args, parsed_globals):
        signer = CloudFrontSigner(
            args.key_pair_id, RSASigner(args.private_key).sign)
        date_less_than = parse_to_aware_datetime(args.date_less_than)
        date_greater_than = args.date_greater_than
        if date_greater_than is not None:
            date_greater_than = parse_to_aware_datetime(date_greater_than)
        if date_greater_than is not None or args.ip_address is not None:
            policy = signer.build_policy(
                args.url, date_less_than, date_greater_than=date_greater_than,
                ip_address=args.ip_address)
            sys.stdout.write(signer.generate_presigned_url(
                args.url, policy=policy))
        else:
            sys.stdout.write(signer.generate_presigned_url(
                args.url, date_less_than=date_less_than))
        return 0 
Example #5
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 #6
Source File: signers.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def generate_presigned_url(self, request_dict, operation_name,
                               expires_in=3600, region_name=None,
                               signing_name=None):
        """Generates a presigned url

        :type request_dict: dict
        :param request_dict: The prepared request dictionary returned by
            ``botocore.awsrequest.prepare_request_dict()``

        :type operation_name: str
        :param operation_name: The operation being signed.

        :type expires_in: int
        :param expires_in: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

        :type region_name: string
        :param region_name: The region name to sign the presigned url.

        :type signing_name: str
        :param signing_name: The name to use for the service when signing.

        :returns: The presigned url
        """
        request = create_request_object(request_dict)
        self.sign(operation_name, request, region_name,
                  'presign-url', expires_in, signing_name)

        request.prepare()
        return request.url 
Example #7
Source File: SignatureUtils.py    From alipay-sdk-python-all with Apache License 2.0 5 votes vote down vote up
def sign_with_rsa(private_key, sign_content, charset):
    if PYTHON_VERSION_3:
        sign_content = sign_content.encode(charset)
    private_key = fill_private_key_marker(private_key)
    signature = rsa.sign(sign_content, rsa.PrivateKey.load_pkcs1(private_key, format='PEM'), 'SHA-1')
    sign = base64.b64encode(signature)
    if PYTHON_VERSION_3:
        sign = str(sign, encoding=charset)
    return sign 
Example #8
Source File: SignatureUtils.py    From alipay-sdk-python-all with Apache License 2.0 5 votes vote down vote up
def sign_with_rsa2(private_key, sign_content, charset):
    if PYTHON_VERSION_3:
        sign_content = sign_content.encode(charset)
    private_key = fill_private_key_marker(private_key)
    signature = rsa.sign(sign_content, rsa.PrivateKey.load_pkcs1(private_key, format='PEM'), 'SHA-256')
    sign = base64.b64encode(signature)
    if PYTHON_VERSION_3:
        sign = str(sign, encoding=charset)
    return sign 
Example #9
Source File: newsmake.py    From File-Maker with GNU Affero General Public License v3.0 5 votes vote down vote up
def write_dictionary(mode):
    for dictionary in dictionaries:
        for name, value in dictionary.items():
            with open(newsfilename + "-1", "ba+") as dest_file:
                dest_file.write(value)

    with open(newsfilename + "-1", "rb") as source_file:
        read = source_file.read()

    with open(newsfilename, "bw+") as dest_file:
        dest_file.write(u32(512))
        dest_file.write(u32(len(read) + 12))
        dest_file.write(binascii.unhexlify(format(binascii.crc32(read) & 0xFFFFFFFF, '08x')))
        dest_file.write(read)

    if config["production"]:
        nlzss.encode_file(newsfilename, newsfilename)

        with open(newsfilename, "rb") as source_file:
            read = source_file.read()

        with open(config["key_path"], "rb") as source_file:
            private_key_data = source_file.read()

        private_key = rsa.PrivateKey.load_pkcs1(private_key_data, "PEM")

        signature = rsa.sign(read, private_key, "SHA-1")

        with open(newsfilename, "wb") as dest_file:
            dest_file.write(binascii.unhexlify("0".zfill(128)))
            dest_file.write(signature)
            dest_file.write(read)

    # Remove the rest of the other files 

    os.remove(newsfilename + "-1")

    print("\n")
    print("Wrote " + newsfilename) 
Example #10
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 #11
Source File: cli.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args):
        """Signs files."""

        hash_method = cli_args[1]
        if hash_method not in HASH_METHODS:
            raise SystemExit('Invalid hash method, choose one of %s' %
                             ', '.join(HASH_METHODS))

        return rsa.sign(indata, priv_key, hash_method) 
Example #12
Source File: rsaencrypt.py    From seecode-scanner with GNU General Public License v3.0 5 votes vote down vote up
def sign(self, message, hash_method=None):
        """

        :param message:
        :param hash_method:
        :return:
        """
        return rsa.sign(message.encode(), self.private_key, hash_method or self.hash_method) 
Example #13
Source File: signers.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def _choose_signer(self, operation_name, signing_type, context):
        """
        Allow setting the signature version via the choose-signer event.
        A value of `botocore.UNSIGNED` means no signing will be performed.

        :param operation_name: The operation to sign.
        :param signing_type: The type of signing that the signer is to be used
            for.
        :return: The signature version to sign with.
        """
        signing_type_suffix_map = {
            'presign-post': '-presign-post',
            'presign-url': '-query'
        }
        suffix = signing_type_suffix_map.get(signing_type, '')

        signature_version = self._signature_version
        if signature_version is not botocore.UNSIGNED and not \
                signature_version.endswith(suffix):
            signature_version += suffix

        handler, response = self._event_emitter.emit_until_response(
            'choose-signer.{0}.{1}'.format(
                self._service_id.hyphenize(), operation_name),
            signing_name=self._signing_name, region_name=self._region_name,
            signature_version=signature_version, context=context)

        if response is not None:
            signature_version = response
            # The suffix needs to be checked again in case we get an improper
            # signature version from choose-signer.
            if signature_version is not botocore.UNSIGNED and not \
                    signature_version.endswith(suffix):
                signature_version += suffix

        return signature_version 
Example #14
Source File: rsa_backend.py    From python-jose with MIT License 5 votes vote down vote up
def _gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, (a % b)
    return a


# Controls the number of iterations rsa_recover_prime_factors will perform
# to obtain the prime factors. Each iteration increments by 2 so the actual
# maximum attempts is half this number. 
Example #15
Source File: signers.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def handler(self, operation_name=None, request=None, **kwargs):
        # This is typically hooked up to the "request-created" event
        # from a client's event emitter.  When a new request is created
        # this method is invoked to sign the request.
        # Don't call this method directly.
        return self.sign(operation_name, request) 
Example #16
Source File: s3boto3.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _use_rsa_signer():
    # https://stuvel.eu/rsa as an RSA backend
    import rsa

    def _cloud_front_signer_from_pem(key_id, pem):
        key = rsa.PrivateKey.load_pkcs1(pem)
        return CloudFrontSigner(key_id, lambda x: rsa.sign(x, key, 'SHA-1'))

    return _cloud_front_signer_from_pem 
Example #17
Source File: sign_pythonrsa.py    From python-adb with Apache License 2.0 5 votes vote down vote up
def Sign(self, data):
        return rsa.sign(data, self.priv_key, 'SHA-1-PREHASHED') 
Example #18
Source File: cli.py    From opsbro with MIT License 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args):
        '''Decrypts files.'''

        hash_method = cli_args[1]
        if hash_method not in HASH_METHODS:
            raise SystemExit('Invalid hash method, choose one of %s' % 
                    ', '.join(HASH_METHODS))

        return rsa.sign(indata, priv_key, hash_method) 
Example #19
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 sign(self, message, priv_key=None, hash_method='SHA-1'):
        """
        生成明文的哈希签名以便还原后对照
        :param message: str
        :param priv_key:
        :param hash_method: 哈希的模式
        :return:
        """
        if None == priv_key:
            priv_key = self.privkey
        return rsa.sign(message.encode(), priv_key, hash_method) 
Example #20
Source File: forecast.py    From File-Maker with GNU Affero General Public License v3.0 5 votes vote down vote up
def sign_file(file, local_name, server_name):
    log("Processing " + local_name + " ...", "VERBOSE")
    crc32 = format(binascii.crc32(file) & 0xFFFFFFFF, '08x')
    size = len(file) + 12
    dest = open(local_name, 'wb')
    dest.write(u32(0))
    dest.write(u32(size))
    dest.write(binascii.unhexlify(crc32))
    dest.write(file)
    dest.close()
    log("Compressing ...", "VERBOSE")
    nlzss.encode_file(local_name, local_name)
    file = open(local_name, 'rb')
    new = file.read()
    file.close()
    dest = open(local_name, 'wb')
    log("RSA Signing ...", "VERBOSE")
    signature = rsa.sign(new, private_key, "SHA-1")  # Makes a SHA1 with ASN1 padding. Beautiful.
    dest.write(pad(64))  # Padding. This is where data for an encrypted WC24 file would go (such as the header and IV), but this is not encrypted so it's blank.
    dest.write(signature)
    dest.write(new)
    dest.close()
    # Create directory if it does not exist
    path = "{}/{}/{}".format(config["file_path"], language_code, str(country_code).zfill(3))
    pathlib.Path(path).mkdir(parents=True, exist_ok=True)
    shutil.copy2(local_name, path+"/"+server_name)
    os.remove(local_name) 
Example #21
Source File: cli.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args):
        '''Decrypts files.'''

        hash_method = cli_args[1]
        if hash_method not in HASH_METHODS:
            raise SystemExit('Invalid hash method, choose one of %s' % 
                    ', '.join(HASH_METHODS))

        return rsa.sign(indata, priv_key, hash_method) 
Example #22
Source File: oauth.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _make_signed_jwt(payload, pkey):
  """Wraps |payload| dict into signed JSON Web Token."""
  # See http://self-issued.info/docs/draft-jones-json-web-token.html.
  as_json = lambda d: json.dumps(d, sort_keys=True, separators=(',', ':'))
  b64encode = lambda d: base64.urlsafe_b64encode(d).rstrip('=')
  to_sign = '%s.%s' % (
      b64encode(as_json({'typ': 'JWT', 'alg': 'RS256'})),
      b64encode(as_json(payload)))
  signature = rsa.sign(to_sign, pkey, 'SHA-256')
  return '%s.%s' % (to_sign, b64encode(signature))


# The chunk of code below is based on oauth2client.tools module, but adapted for
# usage of _fetch_service_config, our command line arguments, and so on. 
Example #23
Source File: sign_pythonrsa.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def Sign(self, data):
    return rsa.sign(data, self.priv_key, 'SHA-1-PREHASHED') 
Example #24
Source File: signers.py    From aws-extender with MIT License 5 votes vote down vote up
def _choose_signer(self, operation_name, signing_type, context):
        """
        Allow setting the signature version via the choose-signer event.
        A value of `botocore.UNSIGNED` means no signing will be performed.

        :param operation_name: The operation to sign.
        :param signing_type: The type of signing that the signer is to be used
            for.
        :return: The signature version to sign with.
        """
        signing_type_suffix_map = {
            'presign-post': '-presign-post',
            'presign-url': '-query'
        }
        suffix = signing_type_suffix_map.get(signing_type, '')

        signature_version = self._signature_version
        if signature_version is not botocore.UNSIGNED and not \
                signature_version.endswith(suffix):
            signature_version += suffix

        handler, response = self._event_emitter.emit_until_response(
            'choose-signer.{0}.{1}'.format(self._service_name, operation_name),
            signing_name=self._signing_name, region_name=self._region_name,
            signature_version=signature_version, context=context)

        if response is not None:
            signature_version = response
            # The suffix needs to be checked again in case we get an improper
            # signature version from choose-signer.
            if signature_version is not botocore.UNSIGNED and not \
                    signature_version.endswith(suffix):
                signature_version += suffix

        return signature_version 
Example #25
Source File: signers.py    From aws-extender with MIT License 5 votes vote down vote up
def handler(self, operation_name=None, request=None, **kwargs):
        # This is typically hooked up to the "request-created" event
        # from a client's event emitter.  When a new request is created
        # this method is invoked to sign the request.
        # Don't call this method directly.
        return self.sign(operation_name, request) 
Example #26
Source File: distribution.py    From aws-extender with MIT License 5 votes vote down vote up
def _sign_string(message, private_key_file=None, private_key_string=None):
        """
        Signs a string for use with Amazon CloudFront.
        Requires the rsa library be installed.
        """
        try:
            import rsa
        except ImportError:
            raise NotImplementedError("Boto depends on the python rsa "
                                      "library to generate signed URLs for "
                                      "CloudFront")
        # Make sure only one of private_key_file and private_key_string is set
        if private_key_file and private_key_string:
            raise ValueError("Only specify the private_key_file or the private_key_string not both")
        if not private_key_file and not private_key_string:
            raise ValueError("You must specify one of private_key_file or private_key_string")
        # If private_key_file is a file name, open it and read it
        if private_key_string is None:
            if isinstance(private_key_file, six.string_types):
                with open(private_key_file, 'r') as file_handle:
                    private_key_string = file_handle.read()
            # Otherwise, treat it like a file
            else:
                private_key_string = private_key_file.read()

        # Sign it!
        private_key = rsa.PrivateKey.load_pkcs1(private_key_string)
        signature = rsa.sign(str(message), private_key, 'SHA-1')
        return signature 
Example #27
Source File: distribution.py    From aws-extender with MIT License 5 votes vote down vote up
def _create_signing_params(self, url, keypair_id,
                          expire_time=None, valid_after_time=None,
                          ip_address=None, policy_url=None,
                          private_key_file=None, private_key_string=None):
        """
        Creates the required URL parameters for a signed URL.
        """
        params = {}
        # Check if we can use a canned policy
        if expire_time and not valid_after_time and not ip_address and not policy_url:
            # we manually construct this policy string to ensure formatting
            # matches signature
            policy = self._canned_policy(url, expire_time)
            params["Expires"] = str(expire_time)
        else:
            # If no policy_url is specified, default to the full url.
            if policy_url is None:
                policy_url = url
            # Can't use canned policy
            policy = self._custom_policy(policy_url, expires=expire_time,
                                         valid_after=valid_after_time,
                                         ip_address=ip_address)

            encoded_policy = self._url_base64_encode(policy)
            params["Policy"] = encoded_policy
        #sign the policy
        signature = self._sign_string(policy, private_key_file, private_key_string)
        #now base64 encode the signature (URL safe as well)
        encoded_signature = self._url_base64_encode(signature)
        params["Signature"] = encoded_signature
        params["Key-Pair-Id"] = keypair_id
        return params 
Example #28
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 #29
Source File: SignatureUtils.py    From alipay-sdk-python with Apache License 2.0 5 votes vote down vote up
def sign_with_rsa2(private_key, sign_content, charset):
    if PYTHON_VERSION_3:
        sign_content = sign_content.encode(charset)
    private_key = fill_private_key_marker(private_key)
    signature = rsa.sign(sign_content, priv_key=rsa.PrivateKey.load_pkcs1(private_key, format='PEM'), hash='SHA-256')
    sign = base64.b64encode(signature)
    if PYTHON_VERSION_3:
        sign = str(sign, encoding=charset)
    return sign 
Example #30
Source File: SignatureUtils.py    From alipay-sdk-python with Apache License 2.0 5 votes vote down vote up
def sign_with_rsa(private_key, sign_content, charset):
    if PYTHON_VERSION_3:
        sign_content = sign_content.encode(charset)
    private_key = fill_private_key_marker(private_key)
    signature = rsa.sign(sign_content, priv_key=rsa.PrivateKey.load_pkcs1(private_key, format='PEM'), hash='SHA-1')
    sign = base64.b64encode(signature)
    if PYTHON_VERSION_3:
        sign = str(sign, encoding=charset)
    return sign