Python rsa.PublicKey() Examples

The following are 30 code examples of rsa.PublicKey(). 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: parse-aboot.py    From aboot-parser with Apache License 2.0 6 votes vote down vote up
def parse_cert(raw_bytes):
    result = CertInfo()

    certType = rfc2459.Certificate(); 
    cert, rest = decoder.decode(raw_bytes, asn1Spec=certType)
    subj_pub_key_bytes = frombits(cert.getComponentByName('tbsCertificate').getComponentByName('subjectPublicKeyInfo').getComponentByName('subjectPublicKey'))
    SUBJECT = cert.getComponentByName('tbsCertificate').getComponentByName('subject')
    for rdn in SUBJECT[0]:
        for nv in rdn: 
            name = nv.getComponentByName('type')
            value = nv.getComponentByName('value')
            # could pick up regular OUs too
            if name == rfc2459.id_at_organizationalUnitName:
                #print 'name: %s' % name
                #print 'value: [%s] (%s)' % (str(value).strip(), type(value))
                result.control_fields.append(str(value).strip())

    rsaType = rfc2437.RSAPublicKey();
    rsadata,rsadata_rest = decoder.decode(subj_pub_key_bytes, asn1Spec=rsaType)
    mod = rsadata.getComponentByName("modulus")
    pub_exp = rsadata.getComponentByName("publicExponent")
    result.pub_key = rsa.PublicKey(long(mod), long(pub_exp))

    return result 
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: baidupan.py    From DecryptLogin with MIT License 6 votes vote down vote up
def __unpaddingRSA(self, publickkey_modulus, publickkey_exponent, message):
        def padMSG(message, target_length):
            message = message[::-1]
            max_msglength = target_length - 11
            msglength = len(message)
            padding = b''
            padding_length = target_length - msglength - 3
            for i in range(padding_length):
                padding += b'\x00'
            return b''.join([b'\x00\x00', padding, b'\x00', message])
        def encrypt(message, pubkey):
            keylength = rsa.common.byte_size(pubkey.n)
            padded = padMSG(message, keylength)
            payload = rsa.transform.bytes2int(padded)
            encrypted = rsa.core.encrypt_int(payload, pubkey.e, pubkey.n)
            block = rsa.transform.int2bytes(encrypted, keylength)
            return block
        m = int(publickkey_modulus, 16)
        e = int(publickkey_exponent, 16)
        rsa_pubkey = rsa.PublicKey(m, e)
        crypto = encrypt(message.encode('utf-8'), rsa_pubkey)
        return crypto.hex() 
Example #4
Source File: SDK基类.py    From TSDK with MIT License 5 votes vote down vote up
def RSAencrypt(self,public_key:'公钥',sign_str:str,salt:'盐'=''):
        '''通过字符串公钥提取模数和指数生成公钥去加密'''
        modulus_num , exponent_num = self.str2key(public_key)
        modulus = int(modulus_num,16)
        exponent = int(exponent_num,16)
        rsa_pubkey = rsa.PublicKey(modulus,exponent)
        crypto = rsa.encrypt(sign_str.encode(),rsa_pubkey)
        crypto = b64encode(crypto)
        return crypto.decode() 
Example #5
Source File: pykakao.py    From pykakao with MIT License 5 votes vote down vote up
def enc_rsa(self, data):
        N = 0xaf0dddb4de63c066808f08b441349ac0d34c57c499b89b2640fd357e5f4783bfa7b808af199d48a37c67155d77f063ddc356ebf15157d97f5eb601edc5a104fffcc8895cf9e46a40304ae1c6e44d0bcc2359221d28f757f859feccf07c13377eec2bf6ac2cdd3d13078ab6da289a236342599f07ffc1d3ef377d3181ce24c719
        E = 3

        pub_key = rsa.PublicKey(N, E)

        return rsa.encrypt(data, pub_key) 
Example #6
Source File: WeiboSuperCommentScrapy.py    From WeiboSuperSpider with Apache License 2.0 5 votes vote down vote up
def get_password(self, servertime, nonce, pubkey):
        """对密码进行 RSA 的加密"""
        rsaPublickey = int(pubkey, 16)
        key = rsa.PublicKey(rsaPublickey, 65537)  # 创建公钥
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(self.password)  # 拼接明文js加密文件中得到
        message = message.encode("utf-8")
        passwd = rsa.encrypt(message, key)  # 加密
        passwd = binascii.b2a_hex(passwd)  # 将加密信息转换为16进制。
        return passwd 
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: rsa_backend.py    From python-jose with MIT License 5 votes vote down vote up
def is_public(self):
        return isinstance(self._prepared_key, pyrsa.PublicKey) 
Example #9
Source File: rsa_backend.py    From python-jose with MIT License 5 votes vote down vote up
def public_key(self):
        if isinstance(self._prepared_key, pyrsa.PublicKey):
            return self
        return self.__class__(pyrsa.PublicKey(n=self._prepared_key.n, e=self._prepared_key.e), self._algorithm) 
Example #10
Source File: auth.py    From AsyncLine with MIT License 5 votes vote down vote up
def __rsa_crypt(self, message,RSA):
		pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
		crypto  = rsa.encrypt(message, pub_key)
		return crypto 
Example #11
Source File: rsa_encrypt.py    From NJUPT-API with MIT License 5 votes vote down vote up
def encrypt(self, message):
        mm = int(self.m, 16)
        ee = int(self.e, 16)
        rsa_pubkey = rsa.PublicKey(mm, ee)
        crypto = self._encrypt(message.encode(), rsa_pubkey)
        return crypto.hex() 
Example #12
Source File: Talk.py    From LineChivas with GNU General Public License v3.0 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto 
Example #13
Source File: auth.py    From ndrive with MIT License 5 votes vote down vote up
def encrypt(keystring, uid, upw):
    sessionkey, keyname, e_str, n_str = keystring.split(',')
    e, n = int(e_str, 16), int(n_str, 16)

    message = nidStringJoin([sessionkey, uid, upw])

    pubkey = rsa.PublicKey(e, n)
    encrypted = rsa.encrypt(message, pubkey)

    return keyname, encrypted.encode('hex') 
Example #14
Source File: weibo.py    From spider-practice with MIT License 5 votes vote down vote up
def get_sp(password, pubkey, servertime, nonce):
    # rsa加密
    key = rsa.PublicKey(int(pubkey, 16), 65537)
    message = str(servertime) + '\t' + str(nonce) + '\n' + password
    passwd = rsa.encrypt(message.encode("utf8"), key)
    # 将加密信息转换成16进制
    sp = binascii.b2a_hex(passwd)
    # print(sp)
    return sp


# 获取验证码 
Example #15
Source File: accountlib.py    From sina_weibo_crawler with Apache License 2.0 5 votes vote down vote up
def encode_pwd(self, password, servertime, nonce, pubkey):
        rsaPublickey = int(pubkey, 16)
        key = rsa.PublicKey(rsaPublickey, 65537)  # 创建公钥
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(password)  # 拼接明文js加密文件中得到
        passwd = rsa.encrypt(message, key)  # 加密
        passwd = binascii.b2a_hex(passwd)  # 将加密信息转换为16进制。
        return passwd

    # 对用户名进行编码 
Example #16
Source File: LineApi.py    From BotProtectLine with GNU General Public License v3.0 5 votes vote down vote up
def _login(self, email, passwordd, certificate=None, loginName=url.systemname):
        self._thriftTransport.targetPath(url.LINE_AUTH_QUERY_PATH)
        session_json = url.get_json(url.parseUrl(url.LINE_SESSION_LINE_QUERY_PATH))
        self.certificate = certificate
        session_key = session_json['session_key']
        message = (chr(len(session_key)) + session_key +
                   chr(len(email)) + email +
                   chr(len(passwordd)) + passwordd).encode('utf-8')
        keyname, n, e = session_json['rsa_key'].split(",")
        pub_key = rsa.PublicKey(int(n, 16), int(e, 16))
        crypto = rsa.encrypt(message, pub_key).encode('hex')
        self._thriftTransport.targetPath(url.LINE_AUTH_QUERY_PATH)
        result = self._client.loginWithIdentityCredentialForCertificate(
            IdentityProvider.LINE, keyname, crypto, True, '127.0.0.1', loginName, certificate)

        if result.type == 3:
            url._pincode = result.pinCode
            self.callback.Pinverified(url._pincode)
            getAccessKey = url.get_json(
                url.parseUrl(url.LINE_CERTIFICATE_PATH), allowHeader=True)
            self.verifier = getAccessKey['result']['verifier']
            result = self._client.loginWithVerifierForCerificate(self.verifier)
            self.certificate = result.certificate
            self.authToken = result.authToken
            self.urls.set_Headers('X-Line-Access', result.authToken)

            self._thriftTransport.setAccesskey(self.authToken)
            self.onLogin()
            self._thriftTransport.targetPath(url.LINE_API_QUERY_PATH_FIR)

        elif result.type == 2:
            pass

        elif result.type == 1:
            self.authToken = result.authToken
            self.urls.set_Headers('X-Line-Access', result.authToken)
            self._thriftTransport.setAccesskey(self.authToken)
            self.onLogin()
            self._thriftTransport.targetPath(url.LINE_API_QUERY_PATH_FIR) 
Example #17
Source File: sinal2.py    From sinal2 with MIT License 5 votes vote down vote up
def encrypt_passwd(self, passwd, pubkey, servertime, nonce):
        key = rsa.PublicKey(int(pubkey, 16), int('10001', 16))
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(passwd)
        passwd = rsa.encrypt(message.encode('utf-8'), key)
        return binascii.b2a_hex(passwd) 
Example #18
Source File: Sina.py    From dHydra with Apache License 2.0 5 votes vote down vote up
def get_sp(self, passwd, pubkey, servertime, nonce):
        key = rsa.PublicKey(int(pubkey, 16), int('10001', 16))
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(passwd)
        passwd = rsa.encrypt(message.encode('utf-8'), key)
        return binascii.b2a_hex(passwd).decode('ascii') 
Example #19
Source File: Sina.py    From dHydra with Apache License 2.0 5 votes vote down vote up
def get_sp(self, passwd, pubkey, servertime, nonce):
        key = rsa.PublicKey(int(pubkey, 16), int('10001', 16))
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(passwd)
        passwd = rsa.encrypt(message.encode('utf-8'), key)
        return binascii.b2a_hex(passwd).decode('ascii') 
Example #20
Source File: Talk.py    From linezx with MIT License 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto 
Example #21
Source File: Talk.py    From CyberTK-Self with GNU General Public License v2.0 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto 
Example #22
Source File: cookies.py    From WeiboSpider with Apache License 2.0 5 votes vote down vote up
def get_password(self):
        # 创建公钥。
        key = rsa.PublicKey(int(self.pre_login_data[2], 16), 65537)
        # 先对 message 加密,然后将结果的每一个字节转换为一个十六进制数。
        message = ('\t'.join([str(self.pre_login_data[0]), self.pre_login_data[1]]) + '\n' + self.raw_password).encode('utf-8')
        # print(message)

        self.password = binascii.b2a_hex(rsa.encrypt(message, key))
        # print(self.password) 
Example #23
Source File: serve.py    From starctf2018 with MIT License 5 votes vote down vote up
def addr_to_pubkey(address):
	return rsa.PublicKey(int(address, 16), 65537) 
Example #24
Source File: weibo_util.py    From hexo_weibo_image with MIT License 5 votes vote down vote up
def generate_form_data(nonce, pubkey, servertime, rsakv, username, password):
    rsa_public_key = int(pubkey, 16)
    key = rsa.PublicKey(rsa_public_key, 65537)
    message = str(servertime) + '\t' + str(nonce) + '\n' + str(password)
    passwd = rsa.encrypt(message, key)
    passwd = binascii.b2a_hex(passwd)
    username = urllib2.quote(username)
    username = base64.encodestring(username)
    form_data = {
        'entry': 'weibo',
        'gateway': '1',
        'from': '',
        'savestate': '7',
        'useticket': '1',
        'pagerefer': 'http://weibo.com/p/1005052679342531/home?from=page_100505&mod=TAB&pids=plc_main',
        'vsnf': '1',
        'su': username,
        'service': 'miniblog',
        'servertime': servertime,
        'nonce': nonce,
        'pwencode': 'rsa2',
        'rsakv': rsakv,
        'sp': passwd,
        'sr': '1366*768',
        'encoding': 'UTF-8',
        'prelt': '115',
        'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
        'returntype': 'META'
    }
    form_data = urllib.urlencode(form_data)
    return form_data 
Example #25
Source File: userencode.py    From SinaMicroblog_Creeper-Spider_VerificationCode with GNU General Public License v2.0 5 votes vote down vote up
def get_pwd(password, servertime, nonce, pubkey):
    rsaPublickey = int(pubkey, 16)
    key = rsa.PublicKey(rsaPublickey,65537)#create public key
    message = str(servertime) + '\t' + str(nonce) + '\n' + str(password)#create clear text
    passwd = rsa.encrypt(message, key)#cipher text
    passwd = binascii.b2a_hex(passwd)#convert the cipher text into hexadecimal
    return passwd 
Example #26
Source File: LineApi.py    From LineVodka with GNU General Public License v3.0 5 votes vote down vote up
def _login(self, email, passwordd, certificate=None, loginName=url.systemname):
        self._thriftTransport.targetPath(url.LINE_AUTH_QUERY_PATH)
        session_json = url.get_json(url.parseUrl(url.LINE_SESSION_LINE_QUERY_PATH))
        self.certificate = certificate
        session_key = session_json['session_key']
        message = (chr(len(session_key)) + session_key +
                   chr(len(email)) + email +
                   chr(len(passwordd)) + passwordd).encode('utf-8')
        keyname, n, e = session_json['rsa_key'].split(",")
        pub_key = rsa.PublicKey(int(n, 16), int(e, 16))
        crypto = rsa.encrypt(message, pub_key).encode('hex')
        self._thriftTransport.targetPath(url.LINE_AUTH_QUERY_PATH)
        result = self._client.loginWithIdentityCredentialForCertificate(
            IdentityProvider.LINE, keyname, crypto, True, '127.0.0.1', loginName, certificate)

        if result.type == 3:
            url._pincode = result.pinCode
            self.callback.Pinverified(url._pincode)
            getAccessKey = url.get_json(
                url.parseUrl(url.LINE_CERTIFICATE_PATH), allowHeader=True)
            self.verifier = getAccessKey['result']['verifier']
            result = self._client.loginWithVerifierForCerificate(self.verifier)
            self.certificate = result.certificate
            self.authToken = result.authToken
            self.urls.set_Headers('X-Line-Access', result.authToken)

            self._thriftTransport.setAccesskey(self.authToken)
            self.onLogin()
            self._thriftTransport.targetPath(url.LINE_API_QUERY_PATH_FIR)

        elif result.type == 2:
            pass

        elif result.type == 1:
            self.authToken = result.authToken
            self.urls.set_Headers('X-Line-Access', result.authToken)
            self._thriftTransport.setAccesskey(self.authToken)
            self.onLogin()
            self._thriftTransport.targetPath(url.LINE_API_QUERY_PATH_FIR) 
Example #27
Source File: Talk.py    From Chuckyfix with MIT License 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto 
Example #28
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 #29
Source File: Talk.py    From Proself with GNU General Public License v3.0 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto 
Example #30
Source File: Talk.py    From Proself with GNU General Public License v3.0 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto