def main():

    (my_pubkey, my_privkey) = rsa.newkeys(1024)
    message = 'I, Bryan Ngo, signed this message'.encode('utf-8')
    sign = rsa.sign(message, my_privkey, "SHA-256")
    rsa.verify(message, sign, my_pubkey)
    return message, sign, my_pubkey
예제 #2
0
def main():
    (publicKey, privateKey) = rsa.newkeys(1024)

    pub = publicKey.save_pkcs1()
    pubfile = open("public.pem", "w+")
    pubfile.write(pub)
    pubfile.close()

    pri = privateKey.save_pkcs1()
    prifile = open("private.pem", "w+")
    prifile.write(pri)
    prifile.close()

    prifile = open("private.pem", "r")
    p = prifile.read()
    privateKey = rsa.PrivateKey.load_pkcs1(p)
    prifile.close()

    pubfile = open("public.pem", "r")
    p = pubfile.read()
    publicKey = rsa.PublicKey.load_pkcs1(p)
    pubfile.close()

    message = "lalalalal"

    secret = rsa.encrypt(message, publicKey)
    non_secret = rsa.decrypt(secret, privateKey)
    print non_secret

    signature = rsa.sign(message, privateKey, "SHA-1")
    rsa.verify("lalalalal", signature, publicKey)
예제 #3
0
        def do_PUT(self):
            try:
                nonlocal public_key, data

                r_public_key = rsa.PublicKey.load_pkcs1(_readblock(self.rfile), format="DER")
                r_signature = _readblock(self.rfile)
                r_message = _readblock(self.rfile)

                if public_key is not None and public_key != r_public_key:
                    self.send_error(403)
                    return

                try:
                    rsa.verify(r_message, r_signature, r_public_key)
                except rsa.pkcs1.VerificationError:
                    self.send_error(403)
                    return

                public_key = r_public_key
                data = r_message
                _save()

                self.send_response(200)
                self.end_headers()
            except:
                traceback.print_exc()
                self.send_response(500)
                self.end_headers()
예제 #4
0
    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)
예제 #5
0
파일: gevent_test.py 프로젝트: ideascf/play
def do_with_rsa():
    global cnt
    _print('BEFORE sign', cnt)
    ret_sign = rsa.sign(TEST_DATA, g_pri_key, 'SHA-1')
    _print('AFTER sign', cnt)

    _print('BEFORE urlopen', cnt)
    try:
        urllib2.urlopen(
            TEST_URL,
            TEST_DATA,
            # timeout=10
        ).read()
    except Exception as e:
        _print('IN exception', e)
        return False
    _print('AFTER urlopen', cnt)

    _print('BEFORE verify', cnt)
    rsa.verify(TEST_DATA, ret_sign, g_pub_key)
    _print('AFTER verify', cnt)

    cnt += 1

    return True
예제 #6
0
def verify_rsa(message, sign, public_key_path):
    with open(public_key_path) as f:
        public_key = rsa.PublicKey.load_pkcs1_openssl_pem(f.read())
    try:
        rsa.verify(message, sign, public_key)
    except rsa.VerificationError:
        raise Exception('verify failed')
예제 #7
0
파일: oscar.py 프로젝트: wbrxcorp/oscar
def verify_license(license_string, license_signature):
    signature = base64.b64decode(license_signature)
    pubkey = rsa.PublicKey.load_pkcs1(base64.b64decode(_pk), "DER")
    try:
        rsa.verify(license_string, signature, pubkey)
    except:
        return False
    return True
예제 #8
0
 def __verify(self, signature, verify_string):
     """verify the signature"""
     try:
         rsa.verify(verify_string.encode("utf-8"), base64.b64decode(signature), self.__public_key)
         return "Success"
     except rsa.pkcs1.VerificationError:
         print ("Verification Failed")
     return "Failed"
예제 #9
0
def check_buffer_signature(buff, textual_sig, public_key):
    try:
        pubkeyObj = rsa.PublicKey.load_pkcs1(public_key, format='PEM')
        binary_sig = base64.b64decode(textual_sig)
        rsa.verify(buff, binary_sig, pubkeyObj)
        return True
    except Exception:
        return False
예제 #10
0
파일: rsa_test.py 프로젝트: ideascf/play
def test02():
    with open(config.public_key_file) as f:
        pub_key = rsa.PublicKey.load_pkcs1_openssl_pem(f.read())

    with open(config.private_key_file) as f:
        priv_key = rsa.PrivateKey.load_pkcs1(f.read())

    ret_sign = rsa.sign(config.test_data, priv_key, 'SHA-1')
    rsa.verify(config.test_data, ret_sign, pub_key)
예제 #11
0
파일: test01.py 프로젝트: ideascf/play
    def _dumy(self):
        global g_with_rsa, g_cnt

        g_cnt += 1
        # print(g_cnt)

        if g_with_rsa:
            ret_sign = rsa.sign(TEST_DATA, g_pri_key, 'SHA-1')
            rsa.verify(TEST_DATA, ret_sign, g_pub_key)
예제 #12
0
파일: alipay.py 프로젝트: endsh/chiki
 def verify(self, sign, **kwargs):
     keys = sorted(filter(lambda x: x[1], kwargs.iteritems()), key=lambda x: x[0])
     text = '&'.join(['%s=%s' % x for x in keys])
     try:
         rsa.verify(text, base64.b64decode(sign), self.alipay_public_key)
         return True
     except rsa.VerificationError:
         current_app.logger.error('alipay callback verify: %s' % text)
         return False
예제 #13
0
def verifySessionKey():
    if not "application/json" in request.headers["Content-Type"]:
        return None, None, make_response("Expected content-type JSON", 400)

    data = request.json
    for key in ("appid", "key", "_sig"):
        if not key in data:
            return make_response("Missing argument: {key}".format(key=key), 400)

    appid = str(data["appid"])
    if not "appversion" in data:
        appversion = "any"
    else:
        appversion = str(data["appversion"])
    key = str(data["key"])

    # calculate message that was signed
    message = "{appid}:{appversion}:{key}".format(**locals())

    # decode signature
    import base64

    signature = data["_sig"]
    signature = base64.decodestring("\n".join([signature[x : x + 64] for x in range(0, len(signature), 64)]))

    # fetch and validate app information
    lookup_key = appid + ":" + appversion
    apps = _get_registered_apps()
    if not lookup_key in apps or not apps[lookup_key]["enabled"] or not "pubkey" in apps[lookup_key]:
        octoprint.server.appSessionManager.remove(key)
        return make_response("Invalid app: {lookup_key}".format(lookup_key=lookup_key), 401)

    pubkey_string = apps[lookup_key]["pubkey"]
    pubkey_string = "\n".join([pubkey_string[x : x + 64] for x in range(0, len(pubkey_string), 64)])
    try:
        pubkey = rsa.PublicKey.load_pkcs1(
            "-----BEGIN RSA PUBLIC KEY-----\n" + pubkey_string + "\n-----END RSA PUBLIC KEY-----\n"
        )
    except:
        octoprint.server.appSessionManager.remove(key)
        return make_response("Invalid pubkey stored in server", 500)

        # verify signature
    try:
        rsa.verify(message, signature, pubkey)
    except rsa.VerificationError:
        octoprint.server.appSessionManager.remove(key)
        return make_response("Invalid signature", 401)

        # generate new session key and return it
    result = octoprint.server.appSessionManager.verify(key)
    if not result:
        return make_response("Invalid key or already verified", 401)

    verified_key, valid_until = result
    return jsonify(key=verified_key, validUntil=valid_until)
예제 #14
0
def test():
    # 没有找到openssl的公钥加载和校验方式,所以使用rsa 的公钥和校验方式
    with open(config.public_key_file) as f:
        pub_key = rsa.PublicKey.load_pkcs1_openssl_pem(f.read())

    with open(config.private_key_file) as f:
        priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())

    ret_sign = crypto.sign(priv_key, config.test_data, 'sha1')  # 这里的摘要算法为小写,且没有分隔符,这和rsa模块不同
    rsa.verify(config.test_data, ret_sign, pub_key)
예제 #15
0
    def perform_operation(self, indata, pub_key, cli_args):
        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)
예제 #16
0
def verify_signature(data, sign, pubkey_path):
	'verifies if the signature of the data is valid'
	with open(pubkey_path) as f:
		keydata = f.read()
	pubkey = rsa.PublicKey.load_pkcs1(keydata)
	
	try:
		rsa.verify(data, sign, pubkey)
	except rsa.pkcs1.VerificationError:
		return False
	return True
예제 #17
0
파일: tools.py 프로젝트: dijkstr/Cloud
    def test_signature(self,basePath = '', message = ''):
        '''get public key'''
        pubKeyPath = basePath + '/' + 'public.pem'
        (pubkeystr, pubkey) = self.get_rsa_publickey(pubKeyPath)

        '''get private key'''
        priKeyPath = basePath + '/' + 'private.pem'
        (prikeystr, privkey) = self.get_rsa_privatekey(priKeyPath)

        signature = rsa.sign(message, privkey, 'SHA-1')
        rsa.verify(message, signature, pubkey)
예제 #18
0
def verify(message,signature):
	#message = base92.encode(message)
	signature = base92.decode(signature)
	publicfile = FileUtil.open(common.CONFIG_PUBKEY,'r')
	keydata = publicfile.read()
	pubkey = rsa.PublicKey.load_pkcs1(keydata)
	try:
		rsa.verify(message,signature, pubkey)
		return True
	except rsa.pkcs1.VerificationError:
		return False
예제 #19
0
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
def _check_challenge(signature):
    signature = base64.b64decode(signature)
    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.")
예제 #21
0
def verify_sign(plain_text, cipher_text):
    """
    用公钥验证签名
    :param plain_text:
    :param cipher_text:
    :return:
    """
    pub_key = get_pub_key()
    try:
        rsa.verify(plain_text, cipher_text, pub_key)
        return True
    except:
        return False
예제 #22
0
def main():
	test = "http://115.146.84.143:8080"
	privatefile = open('privateKey.pem')
	keydata = privatefile.read()
	privatekey = rsa.PrivateKey.load_pkcs1(keydata)
	publicfile = open('publicKey.pem')
	pubdata = publicfile.read()
	pubkey = rsa.PublicKey.load_pkcs1(pubdata)
	
	signature = rsa.sign(test, privatekey, 'SHA-1')	

	print rsa.verify(test, signature, pubkey)
	print signature
예제 #23
0
    def decrypt(self, token, signature=None):
        """
        Decrypt binary data.

        **中文文档**

        - 接收消息时只需要自己的privkey
        - 如需使用签名, 则双方都需要持有对方的pubkey
        """
        binary = rsa.decrypt(token, self.my_privkey)
        if signature:
            rsa.verify(binary, signature, self.his_pubkey)
        return binary
예제 #24
0
    def will_accept_signature(self, message, signature):
        try:
            bsig = base64.b64decode(signature)
        except TypeError:
            # Incorrect Padding
            return False

        try:
            rsa.verify(message, bsig, self.public_key)
        except rsa.pkcs1.VerificationError:
            return False
        else:
            return True
예제 #25
0
파일: cli.py 프로젝트: Adelscott/persomov
    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)
예제 #26
0
 def checkSign(self):
     """check if the signature attatched to the Bounty is valid"""
     try:
         from rsa import verify, PublicKey
         safeprint(keyList)
         if self.data.get('cert'):    #where key is (PublicKey.n, PublicKey.e)
             expected = str(self).encode('utf-8')
             n = self.data.get('key')[0]
             e = self.data.get('key')[1]
             if rsa.verify(str((n,e)),self.data.get('cert'),masterKey):
                 return verify(expected,self.data.get('sig'),PublicKey(n,e))
         return False
     except:
         return False
예제 #27
0
def validate_token(token, cache=InMemoryCache(), verify=True):
    """
    Given a request or access token validate it.

    Keyword arguments:
    :param tokens: A signed authentication token which was provided by Nexus

    :raises ValueError: If the signature is invalid, the token is expired or
    the public key could not be gotten.
    """
    unencoded_token = urllib.unquote(token)
    token_map = {}
    for entry in unencoded_token.split('|'):
        key, value = entry.split('=')
        token_map[key] = value

    # If the public key is not already in the cache, cache it keyed by the signing subject.
    if not cache.has_public_key(token_map['SigningSubject']):
        response = requests.get(token_map['SigningSubject'], verify=verify)
        if response.status_code != 200:
            message = "Could not get SigningSubject public key"
            log.debug(message)
            raise ValueError(message)
        key_struct = response.content
        public_key = json.loads(key_struct)['pubkey']
        cache.save_public_key(token_map['SigningSubject'], public_key)

    public_key = cache.get_public_key(token_map['SigningSubject'])
    sig = token_map.pop('sig')
    match = re.match('^(.+)\|sig=.*', unencoded_token)
    signed_data = match.group(1)
    try:
        sig = binascii.a2b_hex(sig)
        rsa.verify(signed_data, sig, public_key)
    except rsa.VerificationError:
        exc_value, exc_traceback = sys.exc_info()[1:]
        log.debug('RSA Verification error')
        log.debug(exc_value)
        log.debug(exc_traceback)
        raise ValueError('Invalid Signature')
    now = time.mktime(datetime.utcnow().timetuple())
    if token_map['expiry'] < now:
        raise ValueError('TokenExpired')
    urlparts = urlparse.urlparse(token_map['SigningSubject'])
    return (
        token_map['un'],
        token_map['client_id'],
        urlparts.hostname
    )
예제 #28
0
파일: Block.py 프로젝트: jlbrownc/freecoin
 def tx_inputs_signed(self,tx):
     for input in tx['ins']:
         msg = tx['time'] + input['tx'] + input['tx_i'] + input['out_i']
         _output = tx['outs'][int(input['out_i'])] 
         msg += _output['address'] + util.padint(_output['amount'])
         try:
             input_trans = self.get_tx_h(input['tx'])
             pubkey = input_trans['outs'][int(input['tx_i'])]['address']
         except TypeError:
             raise NoSuchInputException('Input nonexistant: ' + input['tx'] + "-" + input['tx_i'])
         try:
             rsa.verify(unhexlify(msg), unhexlify(input['sig']), rsa.PublicKey(int(pubkey,16), crypto.PUBLIC_EXPONENT))
         except rsa.pkcs1.VerificationError:
             raise SignatureVerificationException("False signature: " + input['sig'])
     return True
예제 #29
0
def heartbeat():
    values = request.get_json()

    cdata = bytes(values.get('data'))
    sign = bytes(values.get('sign'))
    node_id = values.get('id')
    data = rsa.decrypt(cdata, blockchain.prikey)

    if not rsa.verify(data, sign, blockchain.nodes[node_id][1]):
        print("VERIFY ERROR")
        response = {'message': "Verify Error"}
        return jsonify(response), 400

    data = literal_eval(data.decode('utf8'))
    heartbeat_idx = data.get('heartbeat')

    if heartbeat_idx != blockchain.heartbeat + 1:
        print("HEARTBEAT INDEX ERROR")
        response = {'message': "Heartbeat Error"}
        return jsonify(response), 400

    # Reset timer
    blockchain.timer_chk = True

    response = {'message': 'Get heartbeat'}
    return jsonify(response), 201
예제 #30
0
 def verify_by_public_key(self, message, signature):
     """公钥验签.
         :param message: 验签的内容.
         :param signature: 对验签内容签名的值(签名之后,会进行b64encode转码,所以验签前也需转码).
     """
     signature = base64.b64decode(signature)
     return rsa.verify(message, signature, self.public_key)
예제 #31
0
def checkSign(data):
    temp = {k: v for k, v in data.items()}
    sign = temp.pop('sign')
    sign_type = temp.pop('sign_type')
    if not sign_type or sign_type.lower() == 'md5':
        mysign = makeSign(temp, sign_type)
        ret = 0 if sign == mysign else 1
    elif sign_type.lower() == 'rsa':
        ks = temp.keys()
        ks.sort()
        ls = []
        for k in ks:
            if temp[k] not in (None, ''):
                if isinstance(temp[k], unicode):
                    ls.append('{k}={v}'.format(k=k, v=temp[k].encode('utf8')))
                else:
                    ls.append('{k}={v}'.format(k=k, v=temp[k]))
        s = '&'.join(ls)
        try:
            sh = base64.b64decode(urllib.unquote(sign))
            public_key = rsa.PublicKey.load_pkcs1_openssl_pem(
                AliPayConfig.ALI_RSA_PUBLIC_KEY)
            ret = 0 if rsa.verify(s, sh, public_key) else 1
        except VerificationError as e:
            logging.exception(e)
            ret = 1
    else:
        raise ValueError()

    if ret != 0:
        logging.exception('check sign faied')
        logging.exception(data)
        logging.exception('the other sign:' + sign)
    return ret
def verify_signature(file,signature,public_key):
    hashed = hash.hash_file(file).encode()
    sign = file_open(signature)
    print(sign)
    pubkey = rsa.PublicKey.load_pkcs1(file_open(public_key))
    print(pubkey)
    verification = rsa.verify(hashed,sign,pubkey)
예제 #33
0
def verifyData():
    user_id = request.json["userId"]
    signedUserId = request.json["signedUserId"]
    publicKeyFile = request.json["publicKeyFile"]

    user_id_hash = rsa.compute_hash(user_id.encode("utf-8"), HASH_METHOD)

    with open(publicKeyFile, 'r', encoding="ascii") as f:
        file_data = f.read()

    publicKey = rsa.PublicKey.load_pkcs1(file_data)
    signedUserId = base64.decodestring(signedUserId.encode("ascii"))

    try:
        verify = rsa.verify(user_id.encode("utf-8"), signedUserId, publicKey)
        verifyResult = "Success"
    except rsa.pkcs1.VerificationError as e:
        verifyResult = "Failed"

    res = {
        "userId": user_id,
        # "userIdHash": base64.encodestring(user_id_hash).decode("ascii"),
        "publicKeyFile": publicKeyFile,
        # "signedUserId": base64.encodestring(signedUserId).decode("ascii"),
        "verifyResult": verifyResult
    }

    return json.dumps(res)
예제 #34
0
def verify(walletName, statement):

    pubkey = loadWallet(walletName)[0]

    f = open(statement, 'r')
    ledgerFile = open('ledger.txt', 'a')
    src = f.readline().split(' ')[1]
    dest = f.readline().split(' ')[1]
    amt = f.readline().split(' ')[1]
    dateParts = f.readline().split(' ')
    date = dateParts[1] + ' ' + dateParts[2]
    f.readline()  ## skip blank space
    signature = f.readline().split(' ')[0]
    try:
        if src == 'ZSociety':
            print('%.16s transferred %s to %.16s on %s \n' %
                  (src, amt, dest, date),
                  file=ledgerFile)
            print('Funding Transactions are always valid.')
        elif rsa.verify(
            ('From: %.16s \nTo: %.16s \nAmount: %.2f \nDate: %s \n' %
             (src[:16], dest[:16], float(amt), date)).encode('ascii'),
                stringToBytes(signature[2:260]), pubkey):
            print('%.16s transferred %s to %.16s on %s \n' %
                  (src, amt, dest, date),
                  file=ledgerFile)
            print('Transaction Verified.')
        else:
            print('Invalid Transaction')
    except:
        print("Invalid Transaction")
    ledgerFile.close()
    f.close()
예제 #35
0
def rsa_demo():
    (pubkey, privkey) = rsa.newkeys(1024)
    print('pubkey >>>> {}'.format(pubkey))
    print('privkey >>>> {}'.format(privkey))
    with open('pub.pem', 'w') as f:
        f.write(pubkey.save_pkcs1().decode())

    with open('priva.pem', 'w') as f:
        f.write(privkey.save_pkcs1().decode())

    message = 'Kill bill tonight'
    print("message encode {}".format(message.encode()))
    crypto = rsa.encrypt(message.encode(), pubkey)

    print('密文{}'.format(crypto))

    # 解密
    e_message = rsa.decrypt(crypto, privkey)
    print("解密后{}".format(e_message.decode()))

    private_sign = rsa.sign(message.encode(), privkey, 'SHA-1')
    print('签名:{}'.format(private_sign))

    print('验证签名')
    print(rsa.verify(message.encode(), private_sign, pubkey))
예제 #36
0
def AliParamVerify(args, publicKey=""):
    from urllib import unquote
    import rsa
    import base64
    sign = base64.b64decode(args["sign"])
    paymentObj = {}
    for key, value in args.items():
        if key != "sign" and key != "sign_type":
            if not isinstance(value, str):
                value = str(value)
            paymentObj[key] = unquote(value)

    noEmpty = {}
    for key, value in paymentObj.items():
        if value != "" and value is not None:
            noEmpty[key] = value
    if PY2:
        keys = noEmpty.keys()
    else:
        keys = list(noEmpty.keys())
    keys.sort()
    argsString = ""
    args = []
    for key in keys:
        value = noEmpty[key]
        args.append(key + "=" + value)
    argsString = "&".join(args)
    message = argsString
    # print("++++++++++")
    # print(args)
    # print(message)

    publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----"
    pubKey = rsa.PublicKey.load_pkcs1_openssl_pem(publicKey)
    return rsa.verify(message, sign, pubKey)
예제 #37
0
def create_signature(file):
    hashed = hash.hash_file(file).encode()
    (pubkey, privkey) = rsa.newkeys(528)
    signature = rsa.sign(hashed, privkey, 'SHA-1')
    verification = rsa.verify(hashed, signature, privkey)

    return signature, pubkey
예제 #38
0
 def verify(self, sign):
     """
     签名验证
     :param sign:
     :return:
     """
     # self.pubkey = load_key()[0]
     # return verify(pubkey_str(), sign, self.get('pubkey'))
     if isinstance(sign, str):
         sign = bytes(sign, encoding='utf-8')
     try:
         rsa.verify(self.pubkey.encode(), sign,
                    rsa.PublicKey.load_pkcs1(self.pubkey.encode()))
         return True
     except rsa.pkcs1.VerificationError:
         return False
예제 #39
0
def verify(data, signature, filename):
    with open(filename, 'rb') as publicfile:
        public_key = rsa.PublicKey.load_pkcs1(publicfile.read())
    try:
        return rsa.verify(data, signature, public_key)
    except rsa.VerificationError:
        raise
예제 #40
0
    def verify(data, signature, pubkey):
        """
        验证签名
        :param data:
        :param signature:
        :param pubkey:
        :return:
        """
        if data is None or signature is None or pubkey is None:
            return False
        try:
            rsa.verify(data, signature, pubkey)
        except rsa.pkcs1.VerificationError:
            return False

        return True
    def run(self):

        self.m_args = self.m_parser.parse_args()

        self.m_msg_hex = open(self.m_args.message,
                              'r').read().replace(' ', '').replace('\n',
                                                                   '').strip()
        self.m_msg_bin = binascii.unhexlify(self.m_msg_hex)

        self.m_sig_hex = open(self.m_args.signature,
                              'r').read().replace(' ', '').replace('\n',
                                                                   '').strip()
        self.m_sig_bin = binascii.unhexlify(self.m_sig_hex)

        key = rsa.PublicKey.load_pkcs1_openssl_pem(
            open(self.m_args.key, 'rb').read())

        try:
            good_sig = rsa.verify(self.m_msg_bin, self.m_sig_bin, key)
        except rsa.pkcs1.VerificationError:
            good_sig = False

        if good_sig:
            print("Good signature in", self.m_args.signature, "for",
                  self.m_args.message)
        else:
            print("Signature verification failed")
예제 #42
0
def createToken(name, sig):
    sig = base64.urlsafe_b64decode(sig)
    if (rsa.verify(name.encode('utf-8'), sig, pubkey)):
        token_id = base64.urlsafe_b64encode(uuid.uuid4().bytes).decode()
        entry = {'token_id': token_id, 'name': name, 'collected': False}
        db.insert(entry)
        return [token_id]
예제 #43
0
파일: test_vmcp.py 프로젝트: fiorda/pybossa
    def test_sign(self):
        """Test sign works."""
        # rsa_pk = M2Crypto.RSA.gen_key(2048, 65537)
        rsa_keys = rsa.newkeys(2048, 65537)
        rsa_pk = rsa_keys[1]
        rsa_pub = rsa_keys[0]
        salt = 'salt'
        data = {"flags": 8,
                "name": "MyAwesomeVM",
                "ram": 512,
                "secret": "mg041na39123",
                "userData": "[amiconfig]\nplugins=cernvm\n[cernvm]\nusers=user:users;password",
                "vcpus": 1,
                "version": "1.5"}
        strBuffer = vmcp.calculate_buffer(data, salt)
        
        with patch('rsa.PrivateKey.load_pkcs1', return_value=rsa_pk):
            with patch('pybossa.vmcp.open', mock_open(read_data=''), create=True) as m:
                out = vmcp.sign(data, salt, 'testkey')
                err_msg = "There should be a key named signature"
                assert out.get('signature'), err_msg

                err_msg = "The signature should not be empty"
                assert out['signature'] is not None, err_msg
                assert out['signature'] != '', err_msg

                err_msg = "The signature should be the same"
                signature = base64.b64decode(out['signature'])
                assert rsa.verify(strBuffer, signature, rsa_pub) == 1, err_msg

                # The output must be convertible into json object
                import json
                assert_not_raises(Exception, json.dumps, out)
예제 #44
0
    def verify(indata, ret_sign, verify_key, sign_type):
        """
        对indata使用sign_type和verify_key以及ret_sign进行签名验证。

        :attention 当indata中也有sign_type时,优先使用param的sign_type。
        :param dict indata: 要验证签名的dict数据
        :param str ret_sign: indata的签名
        :param str verify_key: 用来校验的key
        :param str sign_type: 签名方式
        :return:
        """

        _log_alipay_codec_v2.debug("indata: %s, ret_sign: %s, sign_type: %s", indata, ret_sign, sign_type)

        if sign_type == SIGN_TYPE_MD5:
            return ret_sign == Alipay.make_sign(indata, verify_key, sign_type)
        elif sign_type == SIGN_TYPE_RSA:
            pub_key = RSA.importKey(
                rsa.pem.save_pem(
                    contents=base64.decodestring(verify_key),
                    pem_marker='RSA PUBLIC KEY'
                )
            )
            unverify_str = Alipay._make_pre_signed_str(indata)
            return rsa.verify(unverify_str, base64.b64decode(ret_sign), pub_key)
        else:
            raise AlipayNotSupportSignTypeError('{sign_type} is not implement.'.format(sign_type=sign_type))
예제 #45
0
파일: utils.py 프로젝트: esrefozturk/poa
def validate_block(data):
    sha = hasher.sha256()
    sha.update(
        str(data['index']) + str(data['timestamp']) + str(data['payload']) +
        str(data['previous_hash']))
    hash = sha.hexdigest()

    if hash != data['hash']:
        return False

    PUB = PublicKey.load_pkcs1('''
        -----BEGIN RSA PUBLIC KEY-----
        {p}
        -----END RSA PUBLIC KEY-----
        '''.format(p='\n'.join(
        [data['miner'][i:i + 64] for i in range(0, len(data['miner']), 64)])))

    if not verify(hash, data['sign'].decode('hex'), PUB):
        return False

    MINER_PUBS = loads(Block.objects.get(index=0).payload)['miners']
    if not data['miner'] in MINER_PUBS:
        return False

    for i in data['transactions']:
        validate_transaction(i)

    return True
예제 #46
0
def verify(data, sign):
    try:
        if rsa.verify(data.encode('utf-8'), base64.b64decode(sign),
                      pubkey) == True:
            return "签名验证成功:" + data
    except Exception as e:
        return "签名验证失败", e, sign, data.encode(),
 def __broadcastBlock(request, f):
     try:
         A = json.loads(request)
         if type(A) == dict:
             sig = A.pop('sig')
             id = A.pop('id')
             if rsa.verify(sig, json.dumps(A, sort_keys=True),
                           A['public key']):
                 A['sig'] = sig
                 for k, v in A['transactions'].items():
                     if not self.__validateOfficerSignatures(v):
                         f('NOT OK')
                         return
                 self._chainMutex.acquire()
                 ret = self._chain.addBlock(A)
                 node.mutexReleaser(self._chainMutex)
                 if ret:
                     A = dict(A)
                     A['id'] = self.id()
                     f('OK')
                     self.__broadcastUtil(A, 'broadcast_block', id)
                     return
     except:
         pass
     f('NOT OK')
예제 #48
0
    def checkLicense(self):
        try:
            self.fromLicenseFile()
        except Exception as e:
            print("license file 1", e, ProgramPath(), sys.argv)
            self.registor = False
            return

        macs = [i for i in getAllMacAddress()]
        if self.mac not in [i[0] for i in macs]:
            self.registor = False
            self.ip = '0.0.0.0'
            return
        self.ip = [i[1] for i in macs if i[0] == self.mac][0]
        try:
            f = StringIO.StringIO(self.pubkey)
            key = pickle.load(f)
            f.close()
            s = str(self)
            verstr = rsa.verify(self.rc, key)
            if verstr == s:
                self.registor = True
            else:
                print("check failed 2")
                self.registor = False
        except Exception as e:
            print('4', e)
            print('exception 3', e)
            self.registor = False
            return
예제 #49
0
    def _check_sign(self, message, sign, **kwargs):
        message = self._sort(message)
        data = '{'
        for key, value in message.items():
            data += '"{}":"{}",'.format(key, value)
        data = data[:-1] + '}'
        sign = base64.b64decode(sign)
        public_key = rsa.PublicKey.load_pkcs1_openssl_pem(
            kwargs.get('public_key', None) or self.public_key)

        try:
            rsa.verify(data.encode(), sign, public_key)
            return True
        except Exception as e:
            print("出现如下异常%s" % e)
            return False
예제 #50
0
    def new_transaction(self, fdata):
        """
        Creates a new transaction to go into the next mined Block

        :param sender: Address of the Sender
        :param receiver: Address of the Receiver
        :param sign: Sign of Sender
        :return: The index of the Block that will hold this transaction
        """
        # transaction append
        cdata = bytes(fdata['data'])
        sign = bytes(fdata['sign'])

        # Error
        if not rsa.verify(cdata, sign, self.auth['pubkey']):
            pass

        data = rsa.decrypt(cdata, self.prikey)
        data = literal_eval(data.decode('utf8'))
        rand_id = data['rand_id']
        candidate = data['candidate']

        tx = {'sender': rand_id, 'receiver': candidate}
        if tx in self.transactions_buffer:
            return False

        if self.valid_transaction(rand_id):
            self.transactions_buffer.append(tx)
            return True
        else:
            return False
예제 #51
0
    def decrypt_message(self, private_vf, ciphertext):

        try:
            # break message into parts, 1st part is cipher text next is the signature
            signature = ciphertext[344:344 + 344]
            ciphertext = ciphertext[0:344]

            # decrypt cipher text
            plaintext = rsa.decrypt(b64decode(ciphertext), private_vf)

            plaintext = plaintext.split(":")

            name = plaintext[0]
            reg_no = plaintext[1]
            stage = plaintext[2]
            extension = plaintext[3]

            public_cl = self.load_public(name + "_" + reg_no + "_" + "public")

            # verify signature first
            verify = rsa.verify(name, b64decode(signature), public_cl)

            if verify == False:
                return (False, name, reg_no, stage, extension)

            return (True, name, reg_no, stage, extension)

        except Exception as e:
            print "EXCEPTION ! Invalid key, decrypt_message"
            print e
            return (False, '', '', '', '')
예제 #52
0
def tx_resolve():
    values = request.get_json()
    print("test", values)

    cdata = bytes(values.get('data'))
    sign = bytes(values.get('sign'))
    node_id = values.get('id')
    data = rsa.decrypt(cdata, blockchain.prikey)

    if not rsa.verify(data, sign, blockchain.nodes[node_id][1]):
        print("VERIFY ERROR")
        response = {'message': "Verify Error"}
        return jsonify(response), 400

    data = literal_eval(data.decode('utf8'))
    txs = data.get('txs')

    if str(txs) in blockchain.resolve_cnt:
        blockchain.resolve_cnt[str(txs)] += 1
    else:
        blockchain.resolve_cnt[str(txs)] = 1

    if len(blockchain.nodes) < blockchain.resolve_cnt[str(txs)] * 2:
        blockchain.transactions_buffer += txs
        blockchain.resolve_cnt = {}

    response = {'message': 'Tx resolve'}
    return jsonify(response), 201
예제 #53
0
def rsa_verify(message, signature, public_key):
	if not isinstance(message, bytes):
		message = encode(message)
	try:
		return rsa.verify(message, signature, public_key)
	except rsa.pkcs1.VerificationError:
		return False
예제 #54
0
def handshake():
    (result, handshake) = generate_handshake()
    result = str(result)
    result = result.encode('utf-8')

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('localhost', 8000))
    s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)

    handshake = rsa.encrypt(bytes(handshake, 'utf-8'), server_public_key)
    handshake_length = 256

    post_request = 'POST /handshake HTTP/1.1\r\nHost: localhost:8000\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n'.format(
        handshake_length)
    b = bytes(post_request, 'utf-8')
    b += handshake

    s.sendall(b)

    i = 0
    while True:
        buffer = s.recv(4096)
        if buffer:
            if i is 1:
                server_answer = rsa.verify(result, buffer, server_public_key)
            i = i + 1
        else:
            s.close()
            break

    if server_answer:
        print("Handshake complete")
    else:
        sys.exit(1)
예제 #55
0
 def verify_sign(self, msg, sign, sender):
     pubkey_send = rsa.key.PublicKey.load_pkcs1(self.active_users[sender])
     try:
         used_hash = rsa.verify(msg, bytes.fromhex(sign), pubkey_send)
         return True
     except rsa.VerificationError:
         return False
예제 #56
0
def decryptMessage():
    global publicKey
    global privateKey
    global Message
    encrypted, signature = Message.split(b'pdrp51')
    arrDecrypted = []
    encrypted = [encrypted[i:i + 172] for i in range(0, len(encrypted), 172)]
    for i in encrypted:
        try:
            arrDecrypted.append(rsa.decrypt(b64decode(i), privateKey))
        except:
            messagebox.showinfo(
                "Part Modified",
                "Block Ignore\nCan't decrypt complete message")
    verify = rsa.verify(arrDecrypted[0], b64decode(signature), publicKey)
    path = asksaveasfilename(initialfile='decryptedMessage.txt',
                             filetypes=(("TXT File", "*.txt"), ("All Files",
                                                                "*.*")),
                             title="Choose a path.")
    f = open(path, 'wb')
    f.write((b''.join([i for i in arrDecrypted])))
    if (verify):
        messagebox.showinfo("Message decrypted",
                            "Process terminated\nMessage is verified")
    else:
        messagebox.showinfo("Message decrypted",
                            "Process terminated\nMessage is not verified")
예제 #57
0
 def _verify(pubkey: rsa.PublicKey, name: str, time: int,
             signature: str) -> bool:
     try:
         cur_time0 = time
         cur_time1 = utils.curr_time()
         if -1200 <= cur_time0 - cur_time1 <= 1200:
             # 缺省name表示为super_admin,需要使用超管签名校验,其他的用管理员校验
             text = f'Hello World. This is {name} at {cur_time0}.'.encode(
                 'utf-8')
             rsa.verify(text, base64.b64decode(signature.encode('utf8')),
                        pubkey)
             return True
         else:
             raise RsaHandlerTimeError()
     except rsa.VerificationError:
         raise RsaHandlerVerificationError()
예제 #58
0
    def authorize(self, public_key_string, signature_base64, message,
                  signer_public_key_string, filepath):
        for ak in self._config["authorized_keys"]:
            if ak["key"] == public_key_string:
                return True

        if not signature_base64 or not message or not signer_public_key_string:
            return False

        found = False
        for ak in self._config["authorized_keys"]:
            if ak["key"] == signer_public_key_string:
                found = True
                break
        if not found:
            return False

        now = int(time.time())
        if message["public_key"] != public_key_string:
            return False
        if message["start_time"] > now or message["end_time"] < now:
            return False

        message_string = signatureMessageToString(message)
        try:
            signer_public_key = pemStringToPublicKey(signer_public_key_string)
        except:
            return False
        try:
            signature = base64.b64decode(signature_base64)
        except:
            return False

        correct_modifier = True
        if message["modifiers"] != "":
            correct_modifier = False
            try:
                modifiers = parseModifiers(message["modifiers"])
                if modifiers is None:
                    return False  # could not modifiers
                if "cda" in modifiers and "encrypted_id" in modifiers["cda"]:
                    encrypted_id = modifiers["cda"]["encrypted_id"]
                    tree = ET.parse(filepath)
                    patient_roles = tree.find("patientRole")
                    for patientid in patient_roles.findall("id"):
                        id_root = patientid.attrib[
                            "root"] + "-" + patientid.attrib["extension"]
                        if bcrypt.checkpw(id_root.encode("utf-8"),
                                          encrypted_id.encode("utf-8")):
                            correct_modifier = True
                            break
                else:
                    return False  # invalid modifier
            except:
                return False
        if not correct_modifier:
            return False

        return False if rsa.verify(message_string.encode("utf-8"), signature,
                                   signer_public_key) == False else True
예제 #59
0
파일: autonome.py 프로젝트: sayge/autono-me
	def fetch_stream(self, privatekey, remotesharecache, remotestream, remoteid=""):
		""" Fetch shared items from a remote stream, and update remote share cache with them"""
		(remoteprofile, remoteshares) = self.load_and_check_publicstream(remotestream)
		if remoteprofile != False: #Has it loaded correctly (signed correctly, etc)
			if remoteid=="" or remoteid == remoteprofile["id"]: #Check if remote profile id matches stored ID (=key hash) to confirm continued identity
				#TODO Update profile; alt-urls -> in followlist, sharelist
				for share in remoteshares: #go through each share to see whether we can read it
					content1 = None
					try:
						#First, try to load public content
						content1 = json.loads(share)
					except:
						# decrypt the share with our private key
						unencshare = rsa.decrypt(str(share), privatekey) #Try whether we can
						try:
							#remember, we have three iterations of json-as-string-in-json here!
							content1 = json.loads(unencshare)
						except ValueError, e:
							logging.debug("Obviously a share is not meant for us...:")
							logging.debug(e)
					if content1 != None:
						content2m = hashlib.md5()
						content2m.update(content1["content"])
						chash = content2m.hexdigest()
						#check hash
						if chash == rsa.verify(str(content1["signature"]), json.loads(remoteprofile["pubkey"].decode("hex"))):
							content3 =json.loads(content1["content"])
							#update cache with found item
							self.addtoremotesharecache(remotesharecache, {"content":content3, "profile":remoteprofile})  #content3 is still un-de-jsoned
			else:
				logging.warning("Stored ID "+remoteid+" for "+remotestream+" does not match ID in remote file which is "+remoteprofile["id"])
예제 #60
0
파일: PGP.py 프로젝트: ekivolowitz/Misc
def verifyAndReadIncomingMessage(incomingMessage = None, privateKey = None):
        '''
        :param msg: (signed and encrypted message, signature, sender public key)
        :return: Verified message
        '''
        if rsa.verify(incomingMessage[0], incomingMessage[1], incomingMessage[2]):
            return rsa.decrypt(incomingMessage[0], privateKey)