Python rsa.PrivateKey() Examples

The following are 9 code examples of rsa.PrivateKey(). 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: rsa_backend.py    From python-jose with MIT License 6 votes vote down vote up
def to_pem(self, pem_format='PKCS8'):

        if isinstance(self._prepared_key, pyrsa.PrivateKey):
            der = self._prepared_key.save_pkcs1(format='DER')
            if pem_format == 'PKCS8':
                pkcs8_der = rsa_private_key_pkcs1_to_pkcs8(der)
                pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker='PRIVATE KEY')
            elif pem_format == 'PKCS1':
                pem = pyrsa_pem.save_pem(der, pem_marker='RSA PRIVATE KEY')
            else:
                raise ValueError("Invalid pem format specified: %r" % (pem_format,))
        else:
            if pem_format == 'PKCS8':
                pkcs1_der = self._prepared_key.save_pkcs1(format="DER")
                pkcs8_der = rsa_public_key_pkcs1_to_pkcs8(pkcs1_der)
                pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker='PUBLIC KEY')
            elif pem_format == 'PKCS1':
                der = self._prepared_key.save_pkcs1(format='DER')
                pem = pyrsa_pem.save_pem(der, pem_marker='RSA PUBLIC KEY')
            else:
                raise ValueError("Invalid pem format specified: %r" % (pem_format,))
        return pem 
Example #2
Source File: gen_cmd.py    From credssp with MIT License 6 votes vote down vote up
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)
    replaceKey(certFile,a._save_pkcs1_der()) 
Example #3
Source File: security.py    From heralding with GNU General Public License v3.0 5 votes vote down vote up
def PrivateKey(d, n):
  """
    @param d: {long | str}private exponent
    @param n: {long | str}modulus
    """
  if isinstance(d, bytes):
    d = rsa.transform.bytes2int(d)
  if isinstance(n, bytes):
    n = rsa.transform.bytes2int(n)
  return {'d': d, 'n': n} 
Example #4
Source File: security.py    From heralding with GNU General Public License v3.0 5 votes vote down vote up
def decryptRSA(message, privateKey):
  """
    @summary: wrapper around rsa.core.decrypt_int function
    @param message: {str} source message
    @param publicKey: {rsa.PrivateKey}
    """
  return rsa.transform.int2bytes(
      rsa.core.decrypt_int(
          rsa.transform.bytes2int(message), privateKey['d'], privateKey['n'])) 
Example #5
Source File: security.py    From heralding with GNU General Public License v3.0 5 votes vote down vote up
def getServerCertBytes(self):
    sigHash = signRSA(
        self.getSignatureHash()[::-1],
        PrivateKey(
            d=ServerSecurity._TERMINAL_SERVICES_PRIVATE_EXPONENT_[::-1],
            n=ServerSecurity._TERMINAL_SERVICES_MODULUS_[::-1]))[::-1]
    sigBlobProps = b'\x08\x00\x48\x00'
    return ServerSecurity.SERVER_PUBKEY_PROPS_1+ServerSecurity.SERVER_PUBKEY_PROPS_2 + \
        self._exponentBytes+self._modulusBytes+ServerSecurity.PADDING+sigBlobProps+sigHash+ServerSecurity.PADDING 
Example #6
Source File: licensing.py    From fbs with GNU General Public License v3.0 5 votes vote down vote up
def pack_license_key(data, privkey_args):
    """
    Pack a dictionary of license key data to a string. You typically call this
    function on a server, when a user purchases a license. Eg.:

        lk_contents = pack_license_key({'email': 'some@user.com'}, ...)

    The parameter `privkey_args` is a dictionary containing values for the RSA
    fields "n", "e", "d", "p" and "q". You can generate it with fbs's command
    `init_licensing`.

    The resulting string is signed to prevent the end user from changing it.
    Use the function `unpack_license_key` below to reconstruct `data` from it.
    This also verifies that the string was not tampered with.

    This function has two non-obvious caveats:

    1) It does not obfuscate the data. If `data` contains "key": "value", then
       "key": "value" is also visible in the resulting string.

    2) Calling this function twice with the same arguments will result in the
    same string. This may be undesirable when you generate multiple license keys
    for the same user. A simple workaround for this is to add a unique parameter
    to `data`, such as the current timestamp.
    """
    data_bytes = _dumpb(data)
    signature = rsa.sign(data_bytes, PrivateKey(**privkey_args), 'SHA-1')
    result = dict(data)
    if 'key' in data:
        raise ValueError('Data must not contain an element called "key"')
    result['key'] = b64encode(signature).decode('ascii')
    return json.dumps(result) 
Example #7
Source File: rsa_backend.py    From python-jose with MIT License 5 votes vote down vote up
def _process_jwk(self, jwk_dict):
        if not jwk_dict.get('kty') == 'RSA':
            raise JWKError("Incorrect key type. Expected: 'RSA', Received: %s" % jwk_dict.get('kty'))

        e = base64_to_long(jwk_dict.get('e'))
        n = base64_to_long(jwk_dict.get('n'))

        if 'd' not in jwk_dict:
            return pyrsa.PublicKey(e=e, n=n)
        else:
            d = base64_to_long(jwk_dict.get('d'))
            extra_params = ['p', 'q', 'dp', 'dq', 'qi']

            if any(k in jwk_dict for k in extra_params):
                # Precomputed private key parameters are available.
                if not all(k in jwk_dict for k in extra_params):
                    # These values must be present when 'p' is according to
                    # Section 6.3.2 of RFC7518, so if they are not we raise
                    # an error.
                    raise JWKError('Precomputed private key parameters are incomplete.')

                p = base64_to_long(jwk_dict['p'])
                q = base64_to_long(jwk_dict['q'])
                return pyrsa.PrivateKey(e=e, n=n, d=d, p=p, q=q)
            else:
                p, q = _rsa_recover_prime_factors(n, e, d)
                return pyrsa.PrivateKey(n=n, e=e, d=d, p=p, q=q) 
Example #8
Source File: sign_pythonrsa.py    From adb_shell with Apache License 2.0 5 votes vote down vote up
def _load_rsa_private_key(pem):
    """PEM encoded PKCS#8 private key -> ``rsa.PrivateKey``.

    ADB uses private RSA keys in pkcs#8 format. The ``rsa`` library doesn't
    support them natively.  Do some ASN unwrapping to extract naked RSA key
    (in der-encoded form).

    See:

    * https://www.ietf.org/rfc/rfc2313.txt
    * http://superuser.com/a/606266

    Parameters
    ----------
    pem : str
        The private key to be loaded

    Returns
    -------
    rsa.key.PrivateKey
        The loaded private key

    """
    try:
        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') 
Example #9
Source File: rsa_backend.py    From python-jose with MIT License 4 votes vote down vote up
def __init__(self, key, algorithm):
        if algorithm not in ALGORITHMS.RSA:
            raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)

        self.hash_alg = {
            ALGORITHMS.RS256: self.SHA256,
            ALGORITHMS.RS384: self.SHA384,
            ALGORITHMS.RS512: self.SHA512
        }.get(algorithm)
        self._algorithm = algorithm

        if isinstance(key, dict):
            self._prepared_key = self._process_jwk(key)
            return

        if isinstance(key, (pyrsa.PublicKey, pyrsa.PrivateKey)):
            self._prepared_key = key
            return

        if isinstance(key, six.string_types):
            key = key.encode('utf-8')

        if isinstance(key, six.binary_type):
            try:
                self._prepared_key = pyrsa.PublicKey.load_pkcs1(key)
            except ValueError:
                try:
                    self._prepared_key = pyrsa.PublicKey.load_pkcs1_openssl_pem(key)
                except ValueError:
                    try:
                        self._prepared_key = pyrsa.PrivateKey.load_pkcs1(key)
                    except ValueError:
                        try:
                            der = pyrsa_pem.load_pem(key, b'PRIVATE KEY')
                            try:
                                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)
            return
        raise JWKError('Unable to parse an RSA_JWK from key: %s' % key)