Esempio n. 1
0
 def decrypt(self, buff):
     md = SHA256.new(buff[:-0x100])
     verifier = PKCS1_v1_5.new(self._static_pubkey)
     if verifier.verify(md, buff[-0x100:]) == False:
         raise ValueError('Invalid signature in footer.')
     if self._pubkey is not None:
         md = SHA256.new(buff[:-0x200])
         verifier = PKCS1_v1_5.new(self._pubkey)
         if verifier.verify(md, buff[-0x200:-0x100]) == False:
             raise ValueError('Invalid signature in footer.')
     buff = buff[:-0x200]
     nonce = array.array('I', buff[-4:])
     nonce.byteswap()
     length = len(buff) - 4
     buff = array.array('I', buff[:-4] + b'\x00' * (8 - length % 8))
     buff.byteswap()
     counter = Counter.new(32, prefix=nonce.tostring(), initial_value=0, little_endian=True)
     cipher = Blowfish.new(self._key, Blowfish.MODE_CTR, counter=counter)
     buff = array.array('I', cipher.decrypt(buff.tostring()))
     buff.byteswap()
     buff = buff.tostring()[:length]
     md = buff[-20:]
     buff = buff[:-20]
     if md != hashlib.sha1(buff).digest():
         raise ValueError('Invalid SHA1 hash in footer.')
     return buff
Esempio n. 2
0
        def testSignVerify(self):
            rng = Random.new().read
            key = RSA.generate(1024, rng)

            for hashmod in (MD2, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, RIPEMD160):
                hobj = hashmod.new()
                hobj.update(b('blah blah blah'))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)

            # Blake2b has variable digest size
            for digest_bits in (160, 256, 384, 512):
                hobj = BLAKE2b.new(digest_bits=digest_bits)
                hobj.update(b("BLAKE2b supports several digest sizes"))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)

            # Blake2s too
            for digest_bits in (128, 160, 224, 256):
                hobj = BLAKE2s.new(digest_bits=digest_bits)
                hobj.update(b("BLAKE2s supports several digest sizes"))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)
Esempio n. 3
0
    def do(pub_key, priv_key):
        d = SHA.new('hello')

        priv = pkcs.new(priv_key)
        ret_sign = priv.sign(d)

        pub = pkcs.new(pub_key)
        pub.verify(d, ret_sign)
Esempio n. 4
0
def test_rsa_verify(key=KEY, time=TIME, data=DATA):
    """
    RSA Verify (PKCS #1 v1.5)
    """
    time = test_time(time)
    mac = HMAC.new(time, data.encode("ascii"), SHA256)
    mac = SHA256.new(mac.digest())
    key = RSA.importKey(key)
    sig = PKCS1_v1_5.new(key).sign(mac)
    return b"Yes" if PKCS1_v1_5.new(key).verify(mac, sig) else b"No"
Esempio n. 5
0
def main():
    pub_key, priv_key = load_keys()

    d = SHA.new(config.test_data)

    priv = pkcs.new(priv_key)
    ret_sign = priv.sign(d)

    pub = pkcs.new(pub_key)
    pub.verify(d, ret_sign)
Esempio n. 6
0
 def __init__(self, public_key_file, private_key_file):
     with open(public_key_file,'rb') as pkf:
         pubkey_string = pkf.read()
         self.public_key = RSA.importKey(pubkey_string)
     with open(private_key_file,'rb') as pkf:
         privkey_string = pkf.read()
         self.private_key = RSA.importKey(privkey_string)
     self.public = PKCS1_OAEP.new(self.public_key)
     self.private = PKCS1_OAEP.new(self.private_key)
     self.signer = PKCS1_v1_5.new(self.private_key)
     self.verifier = PKCS1_v1_5.new(self.public_key)
Esempio n. 7
0
    def runTest(self):
        key = RSA.importKey(PKCS1_15_NoParams.rsakey)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_v1_5.new(key).sign(hashed)
        verifier = PKCS1_v1_5.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
Esempio n. 8
0
def main_01():
    def do(pub, priv):
        d = SHA.new('hello')

        ret_sign = priv.sign(d)
        pub.verify(d, ret_sign)

    pub = pkcs.new(pub_key)
    priv = pkcs.new(priv_key)

    for _ in range(config.calc_times):
        do(pub, priv)
Esempio n. 9
0
def sign(xml_etree, certificate, der_key, passphrase=None, trusted=None):
    """
    Return xmldsig XML string from xml_string of XML.

    :param xml_etree: etree of the xml to sign
    :param der_key: Private key in DER format
    :param certificate: publicKey Public key

    :returns: signed XML byte string

    """
    # from M2Crypto import RSA as m2cryptoRSA
    # from M2Crypto import EVP as m2cryptoEVP
    # from Crypto.PublicKey import RSA as cryptoRSA
    # path_to_pem="/home/rovskyhp/.virtualenvs/agreement/var/tmp/tmp_60.pem"
    # evp = m2cryptoEVP.load_key(str(path_to_pem)).as_der() # Convert Private key (M2Crypto Object) to  DER format
    # key = cryptoRSA.importKey(evp, passphrase='12345678a')

    if hasattr(certificate, 'key'):
        key_info_xml = _generate_key_info_xml_rsa(certificate.key.n,
certificate.key.e)
        pubkey, hasher = certificate, Hash.SHA1
    else:
        der_cer = certificate.as_der()
        key_info_xml = _generate_key_info_xml_x509(der_cer)
        #pubkey, hasher, serialNumber, subject = _x509_certificate(der_cer=certificate, trusted=trusted)
        pubkey = RSA.importKey(certificate.get_pubkey().as_der())

    signed_info_xml = _generate_signed_info(xml_etree)
    text = c14n(signed_info_xml)

    key = RSA.importKey(der_key, passphrase)
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(Hash.SHA1.new(text))

    verifier = PKCS1_v1_5.new(pubkey)

    if not verifier.verify(Hash.SHA1.new(text), signature):
        raise Exception("Signature verification failure!")

    signature_xml = PTN_SIGNATURE_XML % {
        'signed_info_xml': signed_info_xml,
        'signature_value': binascii.b2a_base64(signature)[:-1],
        'key_info_xml': key_info_xml,
    }
    signature_etree = etree.parse(StringIO(signature_xml))
    xml_etree.append(signature_etree.getroot())

    return xml_etree
Esempio n. 10
0
        def test_wrong_signature(self):
            key = RSA.generate(1024)
            msg_hash = SHA1.new(b("Message"))

            signer = PKCS.new(key)
            s = signer.sign(msg_hash)

            verifier = PKCS.new(key.publickey())

            # The signature s should be OK
            verifier.verify(msg_hash, s)

            # Construct an incorrect signature and ensure that the check fails
            wrong_s = s[:-1] + bchr(bord(s[-1]) ^ 0xFF)
            self.assertRaises(ValueError, verifier.verify, msg_hash, wrong_s)
Esempio n. 11
0
def _get_signature_bytes(credentials, string_to_sign):
    """Uses crypto attributes of credentials to sign a string/bytes.

    :type credentials: :class:`client.SignedJwtAssertionCredentials`,
                       :class:`service_account._ServiceAccountCredentials`,
                       :class:`_GAECreds`
    :param credentials: The credentials used for signing text (typically
                        involves the creation of an RSA key).

    :type string_to_sign: string
    :param string_to_sign: The string to be signed by the credentials.

    :rtype: bytes
    :returns: Signed bytes produced by the credentials.
    """
    if isinstance(credentials, _GAECreds):
        _, signed_bytes = app_identity.sign_blob(string_to_sign)
        return signed_bytes
    else:
        pem_key = _get_pem_key(credentials)
        # Sign the string with the RSA key.
        signer = PKCS1_v1_5.new(pem_key)
        if not isinstance(string_to_sign, six.binary_type):
            string_to_sign = string_to_sign.encode('utf-8')
        signature_hash = SHA256.new(string_to_sign)
        return signer.sign(signature_hash)
Esempio n. 12
0
    def get_new_token(self):
        """
        Get a new token using the email address and RSA Key.

        :return:  Dictionary containing token information
        :rtype:   ``dict``
        """
        # The header is always the same
        header = {'alg': 'RS256', 'typ': 'JWT'}
        header_enc = base64.urlsafe_b64encode(b(json.dumps(header)))

        # Construct a claim set
        claim_set = {'iss': self.user_id,
                     'scope': self.scopes,
                     'aud': 'https://accounts.google.com/o/oauth2/token',
                     'exp': int(time.time()) + 3600,
                     'iat': int(time.time())}
        claim_set_enc = base64.urlsafe_b64encode(b(json.dumps(claim_set)))

        # The message contains both the header and claim set
        message = b'.'.join((header_enc, claim_set_enc))
        # Then the message is signed using the key supplied
        key = RSA.importKey(self.key)
        hash_func = SHA256.new(message)
        signer = PKCS1_v1_5.new(key)
        signature = base64.urlsafe_b64encode(signer.sign(hash_func))

        # Finally the message and signature are sent to get a token
        jwt = b'.'.join((message, signature))
        request = {'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                   'assertion': jwt}

        return self._token_request(request)
Esempio n. 13
0
 def Generate(self):
     if not os.path.exists(self.source_dir_):
         print("The source directory %s is invalid." % self.source_dir_)
         return
     try:
         zip_file = '%s.tmp' % self.output_file_
         self.__Compress(self.source_dir_, zip_file)
         signer = PKCS1_v1_5.new(self.RSAkey)
         zfile = open(zip_file, 'rb')
         sha = SHA.new(zfile.read())
         signature = signer.sign(sha)
         xpk = open(self.output_file_, 'wb')
         zfile.seek(0)
         print('Generating XPK package: %s' % self.output_file_)
         xpk.write('\x43\x72\x57\x6B')
         xpk.write(struct.pack('<I', len(self.pubkey)))
         xpk.write(struct.pack('<I', len(signature)))
         xpk.write(self.pubkey)
         xpk.write(signature)
         xpk.write(zfile.read())
         zfile.close()
         xpk.close()
         print('Generated new XPK package %s successfully.'
               % self.output_file_)
     except IOError:
         if os.path.exists(self.output_file_):
             os.remove(self.output_file_)
         traceback.print_exc()
     finally:
         if os.path.exists(zip_file):
             os.remove(zip_file)
Esempio n. 14
0
def sign(message, sender_private_key):

    h = SHA.new(message)
    signer = PKCS1_v1_5.new(sender_private_key)
    signature = signer.sign(h)
    
    return signature
Esempio n. 15
0
def webhooks_verify(path_pubkey, private_sign, req_data):
    """ path_pubkey : 公钥文件路径,内容为ping++提供的公钥(账户和设置 - Ping++ 公钥)
        private_sign: ping++对应的私钥签名后的字符串
        req_data    : 请求的json格式字符串,不要get_json(),因为会改变字段的顺序,直接获取原始字符串即可
        备注:遇到一个坑,直接从官网上copy公钥时,vim保存文件时会多一个字符,导致验算不通过,推荐notepad++保存
              最后一行不要有换行符
    """
    import base64
    
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256

    def decode_base64(data):
        missing_padding = 4 - len(data) % 4
        if missing_padding:
            data += b'='*missing_padding
        return base64.decodestring(data)

    sig = decode_base64(private_sign)
    req_data = req_data.encode('utf-8')
    digest = SHA256.new(req_data)
    pubkey = RSA.importKey(open(path_pubkey).read())
    pkcs = PKCS1_v1_5.new(pubkey)

    return pkcs.verify(digest, sig)
Esempio n. 16
0
 def verify(self, msg, sig, key):
     h = self.digest.new(msg)
     verifier = PKCS1_v1_5.new(key)
     if verifier.verify(h, sig):
         return True
     else:
         raise BadSignature()
Esempio n. 17
0
def sign_rsa_sha1(base_string, rsa_private_key):
    """**RSA-SHA1**

    Per `section 3.4.3`_ of the spec.

    The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature
    algorithm as defined in `RFC3447, Section 8.2`_ (also known as
    PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5.  To
    use this method, the client MUST have established client credentials
    with the server that included its RSA public key (in a manner that is
    beyond the scope of this specification).

    NOTE: this method requires the python-rsa library.

    .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3
    .. _`RFC3447, Section 8.2`: http://tools.ietf.org/html/rfc3447#section-8.2

    """
    # TODO: finish RSA documentation
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA

    key = RSA.importKey(rsa_private_key)
    if isinstance(base_string, unicode_type):
        base_string = base_string.encode("utf-8")
    h = SHA.new(base_string)
    p = PKCS1_v1_5.new(key)
    return binascii.b2a_base64(p.sign(h))[:-1].decode("utf-8")
Esempio n. 18
0
def rsa_sign(para_str):
    """对请求参数做rsa签名"""
    para_str = para_str.encode('utf-8')
    key = RSA.importKey(settings.ALIPAY_PRIVATE_KEY)
    h = SHA.new(para_str)
    signer = PKCS1_v1_5.new(key)
    return base64.b64encode(signer.sign(h))
Esempio n. 19
0
def verify_hash(pub_algorithm_type, public_key, hash_, values):
    if pub_algorithm_type in (1, 3):
        # RSA
        s = long_to_bytes(values[0])
        return PKCS1_v1_5.new(public_key).verify(hash_, s)
    elif pub_algorithm_type == 20:
        # ELG
        # TODO: Remove dependence on undocumented method
        sig_string = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(
                            hash_, public_key.size())
        return public_key.verify(sig_string, values)
    elif pub_algorithm_type == 17:
        # DSA
        q = public_key.q
        qbits = int(math.floor(float(math.log(q, 2)))) + 1
        qbytes = int(math.ceil(qbits / 8.0))

        digest = hash_.digest()
        # Discard empty leading bytes
        start = 0
        while digest[start] == b'\x00':
            start += 1
        digest = digest[start:start + qbytes]
        return public_key.verify(bytes_to_long(digest), values)
    else:
        # TODO: complete this
        raise ValueError
Esempio n. 20
0
def sign_hash(pub_algorithm_type, secret_key, hash_, k=None):
    if pub_algorithm_type in (1, 3):
        # RSA
        sig_string = PKCS1_v1_5.new(secret_key).sign(hash_)
        return (bytes_to_long(sig_string),)
    elif pub_algorithm_type == 20:
        # ELG
        # TODO: Should only be allowed for test purposes
        if k is None:
            while 1:
                # This can be pretty darn slow
                k = random.StrongRandom().randint(1, secret_key.p - 1)
                if GCD(k, secret_key.p - 1) == 1:
                    break
            print(k)
        # TODO: Remove dependence on undocumented method
        sig_string = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(
                            hash_, secret_key.size())
        return secret_key.sign(sig_string, k)
    elif pub_algorithm_type == 17:
        q = secret_key.q
        qbits = int(math.floor(float(math.log(q, 2)))) + 1
        qbytes = int(math.ceil(qbits / 8.0))
        if k is None:
            k = random.StrongRandom().randint(1, q - 1)

        digest = hash_.digest()[:qbytes]
        return secret_key.sign(bytes_to_long(digest), k)
    else:
        # TODO: complete
        raise ValueError
Esempio n. 21
0
 def _verify_sign(self, public_key, sign_str, sign):
     rsa_key = RSA.importKey(public_key)
     signer = PKCS1_v1_5.new(rsa_key)
     digest = SHA.new(sign_str)
     if signer.verify(digest, base64.decodestring(sign)):
         return True
     return False
Esempio n. 22
0
    def post_results(self, url, content, sign_with=None):
        '''Post the combined results back to the server.'''
        endpoint = '%s/v1/results/' % url
        headers = {'Content-type': 'application/json'}
        data = json.dumps(content)
        self.logger.debug('API request content: %s ' % content)
        if sign_with:
            data_hash = SHA256.new()
            data_hash.update(data.encode('utf-8'))
            with open(sign_with) as key_pair_file:
                try:
                    key = RSA.importKey(key_pair_file.read())
                except (IOError, ValueError) as e:
                    self.logger.info('Error during upload key pair %s'
                                     '' % key_pair_file)
                    self.logger.exception(e)
                    return
            signer = PKCS1_v1_5.new(key)
            sign = signer.sign(data_hash)
            headers['X-Signature'] = binascii.b2a_hex(sign)
            headers['X-Public-Key'] = key.publickey().exportKey('OpenSSH')
        try:
            response = requests.post(endpoint,
                                     data=data,
                                     headers=headers,
                                     verify=not self.args.insecure)
            self.logger.info(endpoint + " Response: " + str(response.text))
        except Exception as e:
            self.logger.info('Failed to post %s - %s ' % (endpoint, e))
            self.logger.exception(e)
            return

        if response.status_code == 201:
            resp = response.json()
            print 'Test results uploaded!\nURL: %s' % resp.get('url', '')
Esempio n. 23
0
def check_signature(baseurl, signature, data, publickey=None):
    if publickey == None:
        if baseurl in publickeys:
            publickey = base64.decodestring(publickeys[baseurl])
        else:
            print >>sys.stderr, "Public key for", baseurl, \
                "not found, specify key file with --publickey"
            # sys.exit(1)
            raise Exception
    (hash_alg, signature_alg, unpacked_signature) = decode_signature(signature)
    assert hash_alg == 4, \
        "hash_alg is %d, expected 4" % (hash_alg,) # sha256
    assert (signature_alg == 3 or signature_alg == 1), \
        "signature_alg is %d, expected 1 or 3" % (signature_alg,) # ecdsa

    if signature_alg == 3:
        vk = ecdsa.VerifyingKey.from_der(publickey)
        vk.verify(unpacked_signature, data, hashfunc=hashlib.sha256,
              sigdecode=ecdsa.util.sigdecode_der)
    else:
        h = SHA256.new(data)

        rsa_key = RSA.importKey(publickey)
        verifier = PKCS1_v1_5.new(rsa_key)
        assert verifier.verify(h, unpacked_signature), \
            "could not verify RSA signature"
Esempio n. 24
0
    def __init__(self, conf, state):
        """
        conf  -- dictionary with configuration variables
        state -- class object with update() function
        """
        self.logger = conf['log']
        self.maxBal = -1
        self.maxVBal = -1       # highest ballot voted in
        self.maxVVal = None     # value voted for maxVBal
        self.avs = []           # msg dict keyed by value
        self.seen = {}          # 1b messages -> use to check if v is safe at b
        self.bmsgs = []         # log of values in 2b messages sent by this instance       
        self.Q = None
        
        with open(conf['keyfile'], 'r') as fh:
            key = RSA.importKey(fh.read())
        self.signer = PKCS1_v1_5.new(key)

        # initialize localgroup
        self.peers = GroupManager(conf)
        self.peers.init_local_group()
        self.state = state
        #self.state.groups['G1'] = self.peers

        self.ctx = get_ssl_context(conf['peer_certs'])
        self.pending = None
Esempio n. 25
0
    def _sign_request(self, info, return_urls):
        """Create and sign payment request data."""
        # Basic fields
        fields = [('VK_SERVICE', u'1002'),
                  ('VK_VERSION', u'008'),
                  ('VK_SND_ID',  self.user),
                  ('VK_STAMP',   '%d' % int(time())),
                  ('VK_AMOUNT',  info.amount),
                  ('VK_CURR',    u'EUR'),
                  ('VK_REF',     info.refnum),
                  ('VK_MSG',     info.message)]

        # Check whether provider supplies extra fields
        if hasattr(self, 'extra_fields'):
            fields.extend(self.extra_fields)

        ## MAC calculation for request 1002
        m = self._build_mac(('SERVICE', 'VERSION', 'SND_ID', 'STAMP', \
                             'AMOUNT', 'CURR', 'REF', 'MSG'), dict(fields))
        # Append mac fields
        fields.append(('VK_MAC', b64encode( \
                    PKCS1_v1_5.new(self.keychain.private_key)
                              .sign(SHA.new(m)))))
        # Append return url field(s)
        fields.append(('VK_RETURN', return_urls['return']))
        return fields
Esempio n. 26
0
    def parse_response(self, form, success=True):
        """Parse and return payment response."""
        fields = {
            # Successful payment
            '1101': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',   #  6..10
                     'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'),    # 11..15
            # Unsuccessful payment
            '1901': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'REF', 'MSG')                                      #  6..7
        }
        # See which response we got
        resp = form.get('VK_SERVICE', None)
        if not resp and resp not in fields:
            raise InvalidResponseError
        success = resp == '1101'

        Random.atfork()

        # Parse and validate MAC
        m = self._build_mac(fields[resp], form)
        f = lambda x: form.get('VK_%s' % x)
        if not PKCS1_v1_5.new(self.keychain.public_key) \
                         .verify(SHA.new(m), b64decode(f('MAC'))):
            raise InvalidResponseError
        # Save payment data
        data = {}
        if success:
            for item in ('T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',
                         'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'):
                data[item] = f(item)
        return PaymentResponse(self, data, success)
Esempio n. 27
0
def sign_data(data, key_path):
    with open(key_path, 'r') as f:
        key = RSA.importKey(f.read())
    signer = PKCS1_v1_5.new(key)
    hash = SHA.new(data)
    signature = signer.sign(hash)
    return base64.b64encode(signature)
Esempio n. 28
0
def verify_rsa_sha1(request, rsa_public_key):
    """Verify a RSASSA-PKCS #1 v1.5 base64 encoded signature.

    Per `section 3.4.3`_ of the spec.

    Note this method requires the PyCrypto library.

    .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3

    To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri
    attribute MUST be an absolute URI whose netloc part identifies the
    origin server or gateway on which the resource resides. Any Host
    item of the request argument's headers dict attribute will be
    ignored.

    .. _`RFC2616 section 5.2`: http://tools.ietf.org/html/rfc2616#section-5.2
    """
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA
    key = RSA.importKey(rsa_public_key)
    norm_params = normalize_parameters(request.params)
    uri = normalize_base_string_uri(request.uri)
    message = construct_base_string(request.http_method, uri, norm_params)
    h = SHA.new(message.encode('utf-8'))
    p = PKCS1_v1_5.new(key)
    sig = binascii.a2b_base64(request.signature.encode('utf-8'))
    return p.verify(h, sig)
Esempio n. 29
0
    def sign(cls, string):
        """Returns the signature of a string.

        This signature is generated using the singleton private key, then
        base64-encoded. It's of the form expected by Google Cloud Storage query
        string authentication. See
        https://developers.google.com/storage/docs/accesscontrol#Signed-URLs.
        """

        # All Google API keys have "notasecret" as their passphrase
        value = cls.get_oauth()
        if value is None: raise "Private key has not been set."
        if handlers.is_production():
            # TODO(nweiz): This currently doesn't work on the development server
            # without adding 'AESCipher', 'blockalgo', and '_AES' to the
            # __CRYPTO_CIPHER_ALLOWED_MODULES constant in
            # google/appengine/tools/dev_appserver_import_hook.py. However, it
            # does work in production, so to make it work locally, we just do a
            # dumb hash of the private key and the string.
            #
            # See http://code.google.com/p/googleappengine/issues/detail?id=8188
            key = RSA.importKey(value, passphrase='notasecret')
            return base64.b64encode(PKCS1_v1_5.new(key).sign(SHA256.new(string)))
        else:
            m = hashlib.md5()
            m.update(value)
            m.update(string)
            return base64.b64encode(m.digest())
def sign_file(f):
    # TODO: For Part 2, you'll use public key crypto here
    # The existing scheme just ensures the updates start with the line 'Caesar'
    # This is naive -- replace it with something better!
    
    # Generate key pairs
    key = RSA.generate(2048)
    
    # Export public key to file
    export_pukey = key.publickey().exportKey('PEM')
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "wb")
    publickey_file.write(export_pukey)
    publickey_file.close()
    
    # Create RSA object from public key
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "rb").read()
    public_key = RSA.importKey(publickey_file)
    
    # Hash message
    hashed_m = SHA256.new(f)
    
    # Encrypt message using public key
    cipher = PKCS1_cipher.new(public_key)
    ciphertext = cipher.encrypt(f+hashed_m.digest())
    
    # Export private key to be prefixed to ciphertext
    export_prkey = key.exportKey('PEM')
    
    # Sign message using private key
    prkey = RSA.importKey(export_prkey)
    signer = PKCS1_v1_5.new(prkey)
    signature = signer.sign(hashed_m)
    
    # Return private key and ciphertext, as well as signature separately
    return export_prkey + b"\n" + ciphertext, signature
Esempio n. 31
0
def rsa_sign(s, key, mod=SHA256):
    key = RSA.importKey(key)
    hash = mod.new(s)
    return PKCS1_v1_5_SIG.new(key).sign(hash)
Esempio n. 32
0
def update():
    #print "got form",request.form

    validate_uuid = UUID(request.form['uuid'])
    uuid = str(validate_uuid)
    session = ws.hashlib.sha256(config.SESSION_SECRET + uuid).hexdigest()

    email = request.form['email'] if 'email' in request.form else None
    wallet = request.form['wallet'] if 'wallet' in request.form else None

    secret = request.form['mfasecret'] if 'mfasecret' in request.form else None
    token = request.form['mfatoken'] if 'mfatoken' in request.form else None
    action = request.form['mfaaction'] if 'mfaaction' in request.form else None

    question = unicode(
        str(request.form['question'])[:64],
        errors='replace') if 'question' in request.form else None
    answer = unicode(str(request.form['answer'])[:32],
                     errors='replace') if 'answer' in request.form else None

    if config.LOCALDEVBYPASSDB:
        session_challenge = session + "_challenge"
        session_pubkey = session + "_public_key"

        if session_challenge not in session_store:
            print 'Challenge not in session'
            abort(403)

        if session_pubkey not in session_store:
            print 'Public key not in session'
            abort(403)

        challenge = session_store.get(session_challenge)
        signature = request.form['signature']
        pubkey = session_store.get(session_pubkey)

        key = RSA.importKey(pubkey)
        h = SHA.new(challenge)
        verifier = PKCS1_v1_5.new(key)

        if not verifier.verify(h, signature.decode('hex')):
            print 'Challenge signature not verified'
            abort(403)

        session_store.delete(session_challenge)
    else:
        ROWS = dbSelect(
            "select challenge,pubkey from sessions where sessionid=%s",
            [session])
        if len(ROWS) == 0 or ROWS[0][0] == None:
            print 'Challenge not in session'
            abort(403)

        if len(ROWS) == 0 or ROWS[0][1] == None:
            print 'Public key not in session'
            abort(403)

        challenge = ROWS[0][0]
        signature = request.form['signature']
        pubkey = ROWS[0][1]

        key = RSA.importKey(pubkey)
        h = SHA.new(challenge)
        verifier = PKCS1_v1_5.new(key)

        if not verifier.verify(h, signature.decode('hex')):
            print 'Challenge signature not verified'
            abort(403)

        dbExecute(
            "update sessions set challenge=NULL, timestamp=DEFAULT where sessionid=%s",
            [session])
        dbCommit()

    ret = False
    if wallet != None:
        if email != None:
            ret = write_wallet(uuid, wallet, email)
        else:
            ret = write_wallet(uuid, wallet)
    elif None not in [token, action]:
        ret = update_mfa(uuid, token, action, secret)
        if ret and action == 'add':
            data = {'question': question, 'answer': answer}
            encdata = encrypt_value(json.dumps(data))
            if encdata[0]:
                if not (set_setting(uuid, 'asq', encdata[1])):
                    print "Error setting ASQ:", uuid, encdata
            else:
                print "Error setting ASQ:", uuid, data, encdata

    response = {'updated': ret}
    print response

    return jsonify(response)
Esempio n. 33
0
 def verify(self, msg, sig):
     try:
         return PKCS1_v1_5.new(self.prepared_key).verify(
             self.hash_alg.new(msg), sig)
     except Exception as e:
         return False
Esempio n. 34
0
 def _download_manifest_info(self):
     """Download and cache the manifest information."""
     self.template = requests.get(settings.fake_manifest.url).content
     self.signing_key = requests.get(settings.fake_manifest.key_url).content
     self.signature = PKCS1_v1_5.new(RSA.importKey(self.signing_key))
Esempio n. 35
0
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA

message = open('./signingText').read()
key = RSA.importKey(open('private.pem').read())
h = SHA.new(message)
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)

open('./pycryptoSignature', 'w').write(signature)

key = RSA.importKey(open('public.pem').read())
h = SHA.new(message)
verifier = PKCS1_v1_5.new(key)
if verifier.verify(h, signature):
    print "The signature is authentic."
else:
    print "The signature is not authentic."
Esempio n. 36
0
encrypted_message = json.dumps(encrypted_message).encode('utf-8')
encryptor = PKCS1_OAEP.new(pubKey)
encrypted = encryptor.encrypt(encrypted_message)

# Example signed message
message_to_sign = {
    'auth': auth_token.decode('utf-8'),
    'patient_info': patient_info,
    't_start': t_start
}

message_to_sign = json.dumps(message_to_sign).encode('utf-8')

digest = SHA256.new()
digest.update(message_to_sign)
signer = PKCS1_v1_5.new(keyPair)
signed_message = signer.sign(digest)

breakglass_validation_time = {}

SECRET_KEY = settings.SECRET_KEY

for i in range(100000):
    start = timer()

    # RA must verify the signature
    verifier = PKCS1_v1_5.new(pubKey)
    verified = verifier.verify(digest, signed_message)

    # Decrypt the message and the token, to retrieve the team and patient info
    decryptor = PKCS1_OAEP.new(keyPair)
Esempio n. 37
0
 def sign(self, msg):
     try:
         return PKCS1_v1_5.new(self.prepared_key).sign(
             self.hash_alg.new(msg))
     except Exception as e:
         raise JWKError(e)
Esempio n. 38
0
			       			dec_session_key = rsa_cipher.decrypt(enc_session_key)

			       			#Decrypt encrypted signed message
			       			iv = Random.new().read(AES.block_size)
			       			aes_cipher = AES.new(dec_session_key, AES.MODE_CFB, iv)
			       			dec_signed_msg =aes_cipher.decrypt(enc_message)
			       			ret = str(dec_signed_msg)
			       			dec_signed_msg = ret[AES.block_size:]

			       			# Verify Signature
			       			message = dec_signed_msg.split(delimiter)[0]
			       			signature = dec_signed_msg.split(delimiter)[1]

			       			s_public_key = RSA.importKey(open('server_pubkey.pem').read())
						message_hash = SHA256.new(message)
						verifier = PKCS1_v1_5.new(s_public_key)
						if verifier.verify(message_hash, signature):
						   		print "The signature is authentic."
					 	  		print("Data Received:")
						   		print(message)
						else:
					 	   		print "The signature is not authentic."
						f.write(data)

			except:
		       		pass
			f.close()
			if data != "nill" :
				print('Successfully got the file')
				sock.close()
				print('connection closed')
Esempio n. 39
0
print(type(private_key))
msg = b"secrect"
digest = SHA512.new()
print("digest: ", digest)
digest.update(msg)
print("digest update : ", digest)
# msg = hashlib.sha512(msg).digest()
# print("msg : ",digest.digest())

with open('msg.txt', 'wb') as f:
    f.write(msg)

with open('message.txt', 'wb') as f:
    f.write(digest.digest())

signer = PKCS1_v1_5.new(private_key)
sig = signer.sign(digest)

# encrypt text with privateKey
# cipher = private_key.encrypt(
#     msg,
#     padding.OAEP(
#         mgf=padding.MGF1(
#             algorithm=hashes.SHA512()),
#             algorithm=hashes.SHA512(),
#             label=None
#     )
# )

# cipher = private_key.sign(
#     msg,
Esempio n. 40
0
def verify_file_signature(hash_value, signature_bin, publicrsa_key):
    verifier = PKCS1_v1_5.new(publicrsa_key)
    if verifier.verify(hash_value, signature_bin):
        return True
    else:
        return False
Esempio n. 41
0
		'patient_id' : patient_id,
		'team_id' : team_id,
		't_rev' : t_rev
	}

	message = json.dumps(message).encode('utf-8')

	encryptor = PKCS1_OAEP.new(pubKey)
	encrypted = encryptor.encrypt(message)

	# Example sign message
	message_to_sign = {
		'auth_token' : auth_token.decode('utf-8'),
		'request' : "RevokeTeam",
		'patient_id' : patient_id,
		'team_id' : team_id,
		't_rev' : t_rev

	}

	message = json.dumps(message_to_sign).encode('utf-8')
	digest = SHA256.new()
	digest.update(message)

	signer = PKCS1_v1_5.new(keyPair)
	sig = signer.sign(digest)

	enc_and_sign_time[i] = round(timer() - start, 7)

with open('m10_100K.json', 'w') as f:
    json.dump(enc_and_sign_time, f)
Esempio n. 42
0
def miner(privatekey_readable, public_key_hashed, address, miners,
          resultQueue):
    from Crypto.PublicKey import RSA
    Random.atfork()
    key = RSA.importKey(privatekey_readable)
    rndfile = Random.new()
    tries = 0
    firstrun = True
    begin = time.time()

    if pool_conf == 1:
        #do not use pools public key to sign, signature will be invalid

        self_address = address
        address = pool_address

        #ask for diff percentage
        s_pool = socks.socksocket()
        s_pool.settimeout(0.3)
        if tor_conf == 1:
            s_pool.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
        s_pool.connect((pool_ip_conf, 8525))  # connect to pool
        print("Connected")

        print(
            "Miner: Asking pool for share qualification difficulty requirement"
        )
        connections.send(s_pool, "diffp", 10)
        pool_diff_percentage = int(connections.receive(s_pool, 10))
        print(
            "Miner: Received pool for share qualification difficulty requirement: {}%"
            .format(pool_diff_percentage))
        s_pool.close()
        #ask for diff percentage

    q = 0

    # OpenCL Hash parameters
    for m in miners:
        m.setHeader(address.encode('utf-8'))
    db_block_hash = ""
    diff = 0
    old_hashes = []
    # OpenCL Hash parameters

    start = time.time()
    while True:
        try:
            # OpenCL Hash parameters
            old_diff = diff
            old_db = db_block_hash
            # OpenCL Hash parameters

            # calculate new hash
            nonces = 0
            # calculate difficulty
            s_node = socks.socksocket()
            if tor_conf == 1:
                s_node.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
            s_node.connect((node_ip_conf, int(port)))  # connect to local node

            connections.send(s_node, "blocklast", 10)
            blocklast = connections.receive(s_node, 10)
            db_block_hash = blocklast[7]

            connections.send(s_node, "diffget", 10)
            diff = connections.receive(s_node, 10)
            s_node.close()

            diff = int(diff[1])

            diff_real = int(diff)

            if pool_conf == 0:
                diff = int(diff)
            else:  # if pooled
                diff_pool = diff_real
                diff = percentage(pool_diff_percentage, diff_real)

                if diff > diff_pool:
                    diff = diff_pool

            mining_condition = bin_convert(db_block_hash)[0:diff]

            # block_hash = hashlib.sha224(str(block_send) + db_block_hash).hexdigest()

            # OpenCL Hash parameters
            if old_db == db_block_hash:
                if old_diff > diff:
                    for hash in old_hashes:
                        resultQueue.pushCandidate([hash, 0])
            else:
                old_hashes = []

            if opencl_full_check == 1:
                searchKey = np.uint32(int(diff))
                print("Difficulty: {}".format(searchKey))
            else:
                searchKey = np.uint32(int(db_block_hash[:8], 16))
                print("Search key: {:x}".format(searchKey))

            for m in miners:
                m.setTail(db_block_hash.encode('utf-8'))
                m.setKernelParams(searchKey)
                m.startMining()
            elapsed = 0
            # OpenCL Hash parameters

            while True:

                cand, onlist = resultQueue.getNextCandidate(opencl_timeout -
                                                            elapsed)

                end = time.time()

                if cand is None:
                    print("Thread{} {} @ Update blockchain (timeout {} sec)".
                          format(q, db_block_hash[:10], opencl_timeout))
                    break

                candidate = cand[0]
                old_hashes.append(candidate)
                q = cand[1]
                elapsed += (end - start)
                print(
                    "Thread{} {} @ {:,.4f} sec to find a candidate ({} waiting to process)"
                    .format(q, db_block_hash[:10], end - start, onlist))
                start = time.time()

                nonce = candidate.tobytes('C').hex()
                np.set_printoptions(formatter={'int': hex})
                print("(python) Nonce: {}".format(nonce))
                seeder = db_block_hash.encode("utf-8")
                print("(python) Seeder: {}".format(seeder))
                debug_hash = hashlib.sha224(
                    (address + nonce +
                     db_block_hash).encode("utf-8")).hexdigest()
                print("(python) Hash            : {}".format(debug_hash))
                print("(python) address: {}".format(address))
                print("(python) mining_condition: {}".format(
                    db_block_hash[0:int(diff / 8) + 1]))

                mining_condition = bin_convert(db_block_hash)[0:diff]
                mining_hash = bin_convert(
                    hashlib.sha224(
                        (address + nonce +
                         db_block_hash).encode("utf-8")).hexdigest())
                tries = tries + 1

                print("Hashrate: {} hash/sec".format(
                    tries * opencl_hash_count / elapsed))
                #print(mining_hash)
                #print(mining_condition)
                if mining_condition in mining_hash:

                    print("Thread {} found a good block hash in {} cycles".
                          format(q, tries))
                    tries = 0

                    # serialize txs

                    block_send = []
                    del block_send[:]  # empty
                    removal_signature = []
                    del removal_signature[:]  # empty

                    s_node = socks.socksocket()
                    if tor_conf == 1:
                        s_node.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1",
                                        9050)
                    s_node.connect((node_ip_conf,
                                    int(port)))  # connect to config.txt node
                    connections.send(s_node, "mpget", 10)
                    data = connections.receive(s_node, 10)
                    s_node.close()

                    if data != "[]":
                        mempool = data

                        for mpdata in mempool:
                            transaction = (str(mpdata[0]), str(mpdata[1][:56]),
                                           str(mpdata[2][:56]),
                                           '%.8f' % float(mpdata[3]),
                                           str(mpdata[4]), str(mpdata[5]),
                                           str(mpdata[6]), str(mpdata[7])
                                           )  # create tuple
                            # print transaction
                            block_send.append(
                                transaction
                            )  # append tuple to list for each run
                            removal_signature.append(
                                str(mpdata[4]
                                    ))  # for removal after successful mining

                    # claim reward
                    block_timestamp = '%.2f' % time.time()
                    transaction_reward = (str(block_timestamp),
                                          str(address[:56]), str(address[:56]),
                                          '%.8f' % float(0), "0", str(nonce)
                                          )  # only this part is signed!
                    # print transaction_reward

                    h = SHA.new(str(transaction_reward).encode("utf-8"))
                    signer = PKCS1_v1_5.new(key)
                    signature = signer.sign(h)
                    signature_enc = base64.b64encode(signature)

                    if signer.verify(h, signature) == True:
                        print("Signature valid")

                        block_send.append(
                            (str(block_timestamp), str(address[:56]),
                             str(address[:56]), '%.8f' % float(0),
                             str(signature_enc.decode("utf-8")),
                             str(public_key_hashed), "0", str(nonce),
                             db_block_hash))  # mining reward tx
                        #print("Block to send: {}".format(block_send))

                        if not any(
                                isinstance(el, list) for el in block_send
                        ):  # if it's not a list of lists (only the mining tx and no others)
                            new_list = []
                            new_list.append(block_send)
                            block_send = new_list  # make it a list of lists

                        #  claim reward
                        # include data

                        # submit mined block to node

                        if sync_conf == 1:
                            check_uptodate(300)

                        if pool_conf == 1:
                            #mining_condition = bin_convert(db_block_hash)[0:diff_real]
                            #if mining_condition in mining_hash:
                            #    print("Miner: Submitting block to all nodes, because it satisfies real difficulty too")
                            #    threading.Thread( target=nodes_block_submit, args=(block_send, ) ).start()

                            try:
                                s_pool = socks.socksocket()
                                s_pool.settimeout(0.3)
                                if tor_conf == 1:
                                    s_pool.setproxy(socks.PROXY_TYPE_SOCKS5,
                                                    "127.0.0.1", 9050)
                                s_pool.connect(
                                    (pool_ip_conf, 8525))  # connect to pool
                                print("Connected")

                                print(
                                    "Miner: Proceeding to submit mined block to pool"
                                )

                                connections.send(s_pool, "block", 10)
                                connections.send(s_pool, self_address, 10)
                                connections.send(s_pool, block_send, 10)
                                s_pool.close()

                                print("Miner: Block submitted to pool")

                            except Exception as e:
                                print("Miner: Could not submit block to pool")
                                pass

                        if pool_conf == 0:
                            threading.Thread(target=nodes_block_submit,
                                             args=(block_send, )).start()
                    else:
                        print("Invalid signature")

        except Exception as e:
            print(e)
            time.sleep(0.1)
            if debug_conf == 1:
                raise
            else:
                pass
Esempio n. 43
0
 def applyCertificateChain(self, message, PKI_object):
     hash_message = SHA256.new(message)
     signature = PKCS1_v1_5.new(self.key).sign(hash_message)
     return PKI_object.applyCertificateChain(message, self.publicKey, signature)
Esempio n. 44
0
def rsa_verify(s, key, sig, mod=SHA256):
    key = RSA.importKey(key)
    hash = mod.new(s)
    return PKCS1_v1_5_SIG.new(key).verify(hash, sig)
Esempio n. 45
0
 def applyToRootCA(self, message, intermedia):
     hash_message = SHA256.new(message);
     signature = PKCS1_v1_5.new(self.key).sign(hash_message)
     return intermedia.applyCertificateChain(message, self.publicKey, signature)
 def sign_transaction(self):
     private_key = RSA.importKey(binascii.unhexlify(
         self.sender_private_key))
     signer = PKCS1_v1_5.new(private_key)
     h = SHA.new(str(self.to_dict()).encode('utf8'))
     return binascii.hexlify(signer.sign(h)).decode('ascii')
Esempio n. 47
0
def get_sha512_signature (private_key):
	global hash
	signer = PKCS1_v1_5.new(private_key)
	#signature = signer.sign(hash)
	return signer.sign(hash)
Esempio n. 48
0
 def applyCertificateChain(self, message, public_key, signature):
     hash_message = SHA256.new(message);
     verified = PKCS1_v1_5.new(public_key).verify(hash_message, signature)
     if verified == True:
         return self.generateCertiChain(public_key);
Esempio n. 49
0
def rsaSign(key, message):
    h = SHA256.new(str(message).encode('ascii'))
    signer = PKCS1_v1_5.new(key)
    return signer.sign(h)
Esempio n. 50
0
def rsaVerify(key, message, signature):
    h = SHA256.new(str(message).encode('ascii'))
    verifier = PKCS1_v1_5.new(key)
    return verifier.verify(h, signature)
Esempio n. 51
0
def sign(message, priv_key):
    global hash
    signer = PKCS1_v1_5.new(priv_key)
    digest = SHA256.new()
    digest.update(message)
    return b64encode(signer.sign(digest))
Esempio n. 52
0
def verify(message, signature, pub_key):
    signer = PKCS1_v1_5.new(pub_key)
    digest = SHA256.new()
    digest.update(message)
    return signer.verify(digest, b64decode(signature))
Esempio n. 53
0
 def sign(self, msg, key):
     h = self.digest.new(msg)
     signer = PKCS1_v1_5.new(key)
     return signer.sign(h)
Esempio n. 54
0
 def __init__(self):
     random = Crypto.Random.new().read
     self._private_key = RSA.generate(1024, random)
     self._public_key = self._private_key.publickey()
     self._signer = PKCS1_v1_5.new(self._private_key)
Esempio n. 55
0
def query(action=None,
          command=None,
          args=None,
          method='GET',
          location=None,
          data=None):
    '''
    Make a web call to Joyent
    '''
    user = config.get_cloud_config_value('user',
                                         get_configured_provider(),
                                         __opts__,
                                         search_global=False)

    password = config.get_cloud_config_value('password',
                                             get_configured_provider(),
                                             __opts__,
                                             search_global=False)

    verify_ssl = config.get_cloud_config_value('verify_ssl',
                                               get_configured_provider(),
                                               __opts__,
                                               search_global=False,
                                               default=True)

    ssh_keyfile = config.get_cloud_config_value('private_key',
                                                get_configured_provider(),
                                                __opts__,
                                                search_global=False,
                                                default=True)

    ssh_keyname = config.get_cloud_config_value('keyname',
                                                get_configured_provider(),
                                                __opts__,
                                                search_global=False,
                                                default=True)

    if not location:
        location = get_location()

    api_host_suffix = config.get_cloud_config_value(
        'api_host_suffix',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default=JOYENT_API_HOST_SUFFIX)

    path = get_location_path(location=location,
                             api_host_suffix=api_host_suffix)

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('User: \'{0}\' on PATH: {1}'.format(user, path))

    timenow = datetime.datetime.utcnow()
    timestamp = timenow.strftime('%a, %d %b %Y %H:%M:%S %Z').strip()
    with salt.utils.fopen(ssh_keyfile, 'r') as kh_:
        rsa_key = RSA.importKey(kh_)
    rsa_ = PKCS1_v1_5.new(rsa_key)
    hash_ = SHA256.new()
    hash_.update(timestamp)
    signed = base64.b64encode(rsa_.sign(hash_))
    keyid = '/{0}/keys/{1}'.format(user, ssh_keyname)

    headers = {
        'Content-Type':
        'application/json',
        'Accept':
        'application/json',
        'X-Api-Version':
        JOYENT_API_VERSION,
        'Date':
        timestamp,
        'Authorization':
        'Signature keyId="{0}",algorithm="rsa-sha256" {1}'.format(
            keyid, signed),
    }

    if not isinstance(args, dict):
        args = {}

    # post form data
    if not data:
        data = json.dumps({})

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        header_dict=headers,
        data=data,
        decode=False,
        text=True,
        status=True,
        headers=True,
        verify_ssl=verify_ssl,
        opts=__opts__,
    )
    log.debug('Joyent Response Status Code: {0}'.format(result['status']))
    if 'Content-Length' in result['headers']:
        content = result['text']
        return_content = yaml.safe_load(content)

    return [result['status'], return_content]
Esempio n. 56
0
def send(amount_input, recipient_input, keep_input, openfield_input):
    try:
        key
    except:
        top5 = Toplevel()
        top5.title("Locked")

        Label(top5, text="Wallet is locked", width=20).grid(row=0, pady=0)

        done = Button(top5, text="Cancel", command=top5.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    app_log.info("Received tx command")

    try:
        float(amount_input)
    except:
        top7 = Toplevel()
        top7.title("Invalid amount")
        Label(top7, text="Amount must be a number", width=20).grid(row=0,
                                                                   pady=0)
        done = Button(top7, text="Cancel", command=top7.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    if encode_var.get() == 1:
        openfield_input = str(base64.b64encode(openfield_input))

    # alias check
    if alias_cb_var.get() == 1:
        conn = sqlite3.connect('static/ledger.db')
        conn.text_factory = str
        c = conn.cursor()
        c.execute(
            "SELECT address FROM transactions WHERE openfield = ? ORDER BY block_height ASC, timestamp ASC LIMIT 1;",
            ("alias=" + recipient_input, ))  #asc for first entry
        recipient_input = c.fetchone()[0]
        conn.close()
        app_log.info("Fetched the following alias recipient: {}".format(
            recipient_input))

    # alias check

    if len(recipient_input) != 56:
        top6 = Toplevel()
        top6.title("Invalid address")
        Label(top6, text="Wrong address length", width=20).grid(row=0, pady=0)
        done = Button(top6, text="Cancel", command=top6.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))
    else:

        app_log.info("Amount: {}".format(amount_input))
        app_log.info("Recipient: {}".format(recipient_input))
        app_log.info("Keep Forever: {}".format(keep_input))
        app_log.info("OpenField Data: {}".format(openfield_input))

        timestamp = '%.2f' % time.time()
        transaction = (timestamp, address, recipient_input,
                       '%.8f' % float(amount_input), keep_input,
                       openfield_input)  #this is signed
        #print transaction

        h = SHA.new(str(transaction))
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(h)
        signature_enc = base64.b64encode(signature)
        app_log.info("Client: Encoded Signature: {}".format(signature_enc))

        verifier = PKCS1_v1_5.new(key)
        if verifier.verify(h, signature) == True:
            if float(amount_input) < 0:
                app_log.info(
                    "Client: Signature OK, but cannot use negative amounts")

            elif (float(amount_input) > float(balance)):
                app_log.info("Mempool: Sending more than owned")

            else:
                app_log.info(
                    "Client: The signature is valid, proceeding to save transaction, signature, new txhash and the public key to mempool"
                )

                mempool = sqlite3.connect('mempool.db')
                mempool.text_factory = str
                m = mempool.cursor()

                m.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)",
                          (timestamp, address, recipient_input,
                           '%.8f' % float(amount_input), signature_enc,
                           public_key_hashed, keep_input, openfield_input))
                mempool.commit()  # Save (commit) the changes
                mempool.close()
                app_log.info(
                    "Client: Mempool updated with a received transaction")
                #refresh() experimentally disabled
        else:
            app_log.info("Client: Invalid signature")
        #enter transaction end
        refresh()
Esempio n. 57
0
 def Sign(self, data):
     h = FakeSHA1(data)
     return PKCS1_v1_5.new(self.rsa_key).sign(h)
Esempio n. 58
0
def base64sign(plaintext, private_key):
    """Function used to sign the URLs."""
    shahash = SHA256.new(plaintext.encode('utf8'))
    signer = PKCS1_v1_5.new(private_key)
    signature_bytes = signer.sign(shahash)
    return base64.b64encode(signature_bytes)
Esempio n. 59
0
save_to_file('encodemessage.txt', cipher_text)

#ghost使用自己的私钥对内容进行解密
with open('ghost-private.pem') as f:
    key = f.read()
    rsakey = RSA.importKey(key)
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)
print text

#master使用自己的公钥对内容进行签名
with open('master-private.pem') as f:
    key = f.read()
    rsakey = RSA.importKey(key)
    signer = Signature_pkcs1_v1_5.new(rsakey)
    digest = SHA.new()
    digest.update(message)
    sign = signer.sign(digest)
    signature = base64.b64encode(sign)
save_to_file('signer.txt', signature)
'''
#验证签名
with open('master-public.pem')as f:
    key=f.read()
    rsakey=RSA.importKey(key)
    verifier=Signature_pkcs1_v1_5.new(rsakey)
    digest-SHA.new()
    #假定数据是基于base64编码的
    digest.update(message)
    is_verify=signer.verify(digest,base64.b64decode(signature))
Esempio n. 60
0
def send(amount_input, recipient_input, keep_input, openfield_input):
    try:
        key
    except:
        top5 = Toplevel()
        top5.title("Locked")

        Label(top5, text="Wallet is locked", width=20).grid(row=0, pady=0)

        done = Button(top5, text="Cancel", command=top5.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    app_log.warning("Received tx command")

    try:
        float(amount_input)
    except:
        top7 = Toplevel()
        top7.title("Invalid amount")
        Label(top7, text="Amount must be a number", width=20).grid(row=0,
                                                                   pady=0)
        done = Button(top7, text="Cancel", command=top7.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    # alias check

    # alias check

    if len(recipient_input) != 56:
        top6 = Toplevel()
        top6.title("Invalid address")
        Label(top6, text="Wrong address length", width=20).grid(row=0, pady=0)
        done = Button(top6, text="Cancel", command=top6.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))
    else:

        app_log.warning("Amount: {}".format(amount_input))
        app_log.warning("Recipient: {}".format(recipient_input))
        app_log.warning("Keep Forever: {}".format(keep_input))
        app_log.warning("OpenField Data: {}".format(openfield_input))

        timestamp = '%.2f' % time.time()
        transaction = (str(timestamp), str(myaddress), str(recipient_input),
                       '%.8f' % float(amount_input), str(keep_input),
                       str(openfield_input))  # this is signed

        h = SHA.new(str(transaction).encode("utf-8"))
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(h)
        signature_enc = base64.b64encode(signature)
        app_log.warning("Client: Encoded Signature: {}".format(
            signature_enc.decode("utf-8")))

        verifier = PKCS1_v1_5.new(key)
        if verifier.verify(h, signature) == True:
            fee = fee_calculate(openfield_input, keep_var.get())

            if float(amount_input) < 0:
                app_log.warning(
                    "Client: Signature OK, but cannot use negative amounts")

            elif (float(amount_input) + float(fee) > float(balance)):
                app_log.warning("Mempool: Sending more than owned")

            else:
                app_log.warning(
                    "Client: The signature is valid, proceeding to save transaction, signature, new txhash and the public key to mempool"
                )

                # print(str(timestamp), str(address), str(recipient_input), '%.8f' % float(amount_input),str(signature_enc), str(public_key_hashed), str(keep_input), str(openfield_input))
                tx_submit = (str(timestamp), str(myaddress),
                             str(recipient_input),
                             '%.8f' % float(amount_input),
                             str(signature_enc.decode("utf-8")),
                             str(public_key_hashed.decode("utf-8")),
                             str(keep_input), str(openfield_input))

                while True:
                    connections.send(s, "mpinsert", 10)
                    connections.send(
                        s, [tx_submit], 10
                    )  # change address here to view other people's transactions
                    reply = connections.receive(s, 10)
                    app_log.warning("Client: {}".format(reply))
                    break
        else:
            app_log.warning("Client: Invalid signature")