How to use the rsa.PrivateKey function in rsa

To help you get started, we’ve selected a few rsa examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rancher / rancher / tests / validation / lib / View on Github external
def decrypt_windows_password(self, instance_id):
        password = ""
        password_data = self._client. \
        if password_data:
            password = base64.b64decode(password_data)
            with open(self.get_ssh_key_path(AWS_SSH_KEY_NAME), 'r') \
                    as privkeyfile:
                priv = rsa.PrivateKey.load_pkcs1(
                password = rsa.decrypt(password, priv).decode('utf-8')

        return password
github JeffLIrion / adb_shell / adb_shell / auth / View on Github external
The loaded private key

        der = rsa.pem.load_pem(pem, 'PRIVATE KEY')
        keyinfo, _ = decoder.decode(der)

        if keyinfo[1][0] != univ.ObjectIdentifier('1.2.840.113549.1.1.1'):
            raise ValueError('Not a DER-encoded OpenSSL private RSA key')

        private_key_der = keyinfo[2].asOctets()

    except IndexError:
        raise ValueError('Not a DER-encoded OpenSSL private RSA key')

    return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER')
github ansible / awx / awx / lib / site-packages / boto / cloudfront / View on Github external
# 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, basestring):
                with open(private_key_file, 'r') as file_handle:
                    private_key_string =
            # Otherwise, treat it like a file
                private_key_string =

        # Sign it!
        private_key = rsa.PrivateKey.load_pkcs1(private_key_string)
        signature = rsa.sign(str(message), private_key, 'SHA-1')
        return signature
github playniuniu / python-unionpay / src / unionpay / View on Github external
def initSignCert(certPath, certPwd):
        if certPath is None or certPwd is None:
            logging.error("signCertPath or signCertPwd is none, exit initSignCert")
            return None"读取签名证书 ...")
        with open(certPath, 'rb') as fs:
            pkcs12 = crypto.load_pkcs12(, certPwd.encode('ascii'))

        if pkcs12 is None:
            logging.error("load pkcs12 error")
            return None

        pkey = pkcs12.get_privatekey()
        pkey = CertUtil.pkcs8_to_pkcs1(pkey)
        pkey = rsa.PrivateKey.load_pkcs1(pkey, 'PEM')

        cert = Cert()
        cert.key = pkey
        cert.certId = str(pkcs12.get_certificate().get_serial_number())
        cert.cert = pkcs12.get_privatekey()
        CertUtil.__signCerts[certPath] = cert"签名证书读取成功, 序列号: " + cert.certId)
        return cert
github google / python-adb / adb / View on Github external
def _load_rsa_private_key(pem):
    """PEM encoded PKCS#8 private key -> rsa.PrivateKey."""
    # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support
    # them natively. Do some ASN unwrapping to extract naked RSA key
    # (in der-encoded form). See
    # Also
        der = rsa.pem.load_pem(pem, 'PRIVATE KEY')
        keyinfo, _ = decoder.decode(der)
        if keyinfo[1][0] != univ.ObjectIdentifier(
                '1.2.840.113549.1.1.1'):  # pragma: no cover
            raise ValueError('Not a DER-encoded OpenSSL private RSA key')
        private_key_der = keyinfo[2].asOctets()
    except IndexError:  # pragma: no cover
        raise ValueError('Not a DER-encoded OpenSSL private RSA key')
    return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER')
github ospaceteam / outerspace / server / lib / rsa / View on Github external
def perform_operation(self, indata, pub_key, cli_args=None):
        '''Encrypts files.'''

        return rsa.encrypt(indata, pub_key)

class DecryptOperation(CryptoOperation):
    '''Decrypts a file.'''

    keyname = 'private'
    description = ('Decrypts a file. The original file must be shorter than '
            'the key length in order to have been encrypted. For larger '
            'files, use the pyrsa-decrypt-bigfile command.')
    operation = 'decrypt'
    operation_past = 'decrypted'
    operation_progressive = 'decrypting'
    key_class = rsa.PrivateKey

    def perform_operation(self, indata, priv_key, cli_args=None):
        '''Decrypts files.'''

        return rsa.decrypt(indata, priv_key)

class SignOperation(CryptoOperation):
    '''Signs a file.'''

    keyname = 'private'
    usage = 'usage: %%prog [options] private_key hash_method'
    description = ('Signs a file, outputs the signature. Choose the hash '
            'method from %s' % ', '.join(HASH_METHODS))
    operation = 'sign'
    operation_past = 'signature'
    operation_progressive = 'Signing'
github preempt / credssp / bin / View on Github external
def genCertAndPriv(certFile, privFile, e, n, d):
    e = E
    p = n - 1
    q = n - 1
    exp1 = e
    exp2 = d
    coef = e
    r = rsa.PrivateKey(n, e, d, p, q, exp1=e, exp2=e,coef=e)
    r.exp1 = 0
    r.exp2 = 0
    r.coef = 0
    r.p = 0
    r.q = 0
    open(privFile, 'wt').write(r.save_pkcs1())
    a =rsa.PublicKey(n,e)
github zenomt / webid-auth-nginx / View on Github external
parser.add_argument('-a', '--app-id', default="https://app.example/oauth/code",
	help="application id (default %(default)s)")
parser.add_argument('-i', '--issuer', default="",
	help="id_token issuer (default %(default)s)")
parser.add_argument('-K', '--key-id', help="JWK kid (default %(default)s)")
parser.add_argument('-A', '--app-auth', help="app authorizations URI (use multiple times)", action='append')
parser.add_argument('-t', '--token-only', action='store_true',
	help="output the bare access token instead of the full JSON response")
parser.add_argument('-d', '--debug', action='store_true')
parser.add_argument('uri', help="URI to access")

args = parser.parse_args()

is_self_issued = args.issuer == ""

privateKey = rsa.PrivateKey.load_pkcs1(open(args.private_key, "rb").read())

def b64u_encode(s):
	return base64.urlsafe_b64encode(s).rstrip('=')

def compact_json(obj):
	return json.dumps(obj, indent=None, separators=(',', ':'))

def urlencode(query):
	# urllib.urlencode will encode a None value as a string None.
	# this will suppress None and empty values.
	rv = []
	for k, v in query.iteritems():
		if v:
			rv.append('%s=%s' % (urllib.quote_plus(str(k)), urllib.quote(str(v), '')))
	return '&'.join(rv)
github mpdavis / python-jose / jose / backends / View on Github external
                    self._prepared_key = pyrsa.PublicKey.load_pkcs1_openssl_pem(key)
                except ValueError:
                        self._prepared_key = pyrsa.PrivateKey.load_pkcs1(key)
                    except ValueError:
                            der = pyrsa_pem.load_pem(key, b'PRIVATE KEY')
                                pkcs1_key = rsa_private_key_pkcs8_to_pkcs1(der)
                            except PyAsn1Error:
                                # If the key was encoded using the old, invalid,
                                # encoding then pyasn1 will throw an error attempting
                                # to parse the key.
                                pkcs1_key = _legacy_private_key_pkcs8_to_pkcs1(der)
                            self._prepared_key = pyrsa.PrivateKey.load_pkcs1(pkcs1_key, format="DER")
                        except ValueError as e:
                            raise JWKError(e)
        raise JWKError('Unable to parse an RSA_JWK from key: %s' % key)