Пример #1
0
def settlement(req,number):
    if req.method == 'GET':
        req.session['number']=number
        chain= req.session['chain']
        read = req.session['read']
        write= req.session['write']
        user = req.session['uid']
        txid = req.session['tx_id']
        uid  = req.session['uid']

        dic={}
        view = list_Bid.objects.filter(number=number)
        pi = Bid.objects.get(number=number)
        c1=pyelliptic.ECC(pubkey=bytes.fromhex(pi.pub_key1),privkey=bytes.fromhex(pi.pri_key1),curve="secp256k1")
        
        c2=pyelliptic.ECC(pubkey=bytes.fromhex(pi.pub_key2),privkey=bytes.fromhex(pi.pri_key2),curve="secp256k1")
        for b in view:
            tx = bitcoin_rpc('gettransaction', b.list_id)
            if not tx:
                raise Http404('Token錯誤')
            raw = tx.get('hex')
            op_returns = []
            if raw:
                decode = tx['decode'] = bitcoin_rpc('decoderawtransaction', raw)

                for out in decode.get('vout'):
                    script = out.get('scriptPubKey')
                    if not script:
                        continue

                    type_ = script.get('type')
                    if type_ != 'nulldata':
                        continue

                    asm = script.get('asm')
                    if not asm.startswith('OP_RETURN'):
                        continue

                    code = asm.split()[-1]
                    a=json.loads(unhexlify(code).decode())
                    p1=bytes.fromhex(a['Price'])
                    de_data=int(c1.decrypt(p1).decode("utf-8"))
                    b={b.list_id:de_data}
                    dic.update(b)

        dict= sorted(dic.items(), key=lambda d:d[1], reverse = True)
        try:
            txid=dict[0][0]
            price=int(dict[0][1])
            test1=gettx(pi.txid)
            real=bytes.fromhex(test1[0]['Real_price'])
            r_price=int(c2.decrypt(real).decode("utf-8"))
            print(r_price)
        except:
            message = '無人投標 流標!'
        #print(test1[0]['Number'])
        
        template = get_template('settlement.html')
        html = template.render(locals())
        return HttpResponse(html)
Пример #2
0
 def setUpClass(cls):
     cls.alice = ec.ECC(curve=crypto_util.BTC_CURVE)
     cls.bob = ec.ECC(curve=crypto_util.BTC_CURVE)
     cls.bob_pubkey = cls.bob.get_pubkey()
     cls.bob_privkey = cls.bob.get_privkey()
     cls.alice_pubkey = cls.alice.get_pubkey()
     cls.data = "YELLOW SUBMARINE"
Пример #3
0
 def setUpClass(cls):
     cls.ecc_curve = "secp256k1"
     cls.alice = ec.ECC(curve=cls.ecc_curve)
     cls.bob = ec.ECC(curve=cls.ecc_curve)
     cls.bob_pubkey = cls.bob.get_pubkey()
     cls.bob_privkey = cls.bob.get_privkey()
     cls.alice_pubkey = cls.alice.get_pubkey()
     cls.data = "YELLOW SUBMARINE"
Пример #4
0
 def generate_ecc_instance(self):
     if self.__private_key__ is None or self.__public_key__ is None:
         print "ECC keys not provided.  Generating ECC keys"
         ecc = pyelliptic.ECC(curve='secp256k1')
         self.__private_key__ = ecc.get_privkey()
         self.__public_key__ = ecc.get_pubkey()
     else:
         ecc = pyelliptic.ECC(curve='secp256k1', privkey=self.__private_key__, pubkey=self.__public_key__)
     return ecc
Пример #5
0
def send_bid(req):
    if req.method == 'GET':
        return render(req,'hello.html')
    if 'chain' in req.session:
        chain= req.session['chain']
        read = req.session['read']
        write= req.session['write']
        user = req.session['uid']
        txid = req.session['tx_id']
        uid  = req.session['uid']
    
    u = req.POST['user']
    c = req.POST['chain']
    #n = req.POST['number']
    n =''.join([random.choice(string.digits) for _ in range(4)])
    s = req.POST['start_price']
    r = req.POST['real_price']
    pro = req.POST['product']
    exp = req.POST['exp']
    days=range(1,30)

    curve = "secp256k1"
    key1= pyelliptic.ECC(curve=curve)
    key2 = pyelliptic.ECC(curve=curve)
    
    pubkey1=key1.get_pubkey().hex()
    prikey1=key1.get_privkey().hex()
    pubkey2=key2.get_pubkey().hex()
    prikey2=key2.get_privkey().hex()

    s2=key1.encrypt(s, key1.get_pubkey()).hex()
    r2=key2.encrypt(r, key2.get_pubkey()).hex()
    
    today=datetime.date.today()
   # exp_time = str(date(today.year,today.month,today.day+int(exp)))
    exp_time=str(datetime.date.today() + datetime.timedelta(days=int(exp)))


    message={"Type":"bid","User":u,"Chain":c,"Number":n,"Start_price":s2,"Real_price":r2,"Expiration_date":exp_time}
    me=json.dumps(message)
    result= OP_RETURN_store(me)
    re = result['txids'][0]
    #a=(date(today.year,today.month,today.day+int(exp)))
    #a=datetime.date.today() + datetime.timedelta(days=int(exp))
    aa=datetime.datetime.combine(datetime.date.today()+ datetime.timedelta(days=int(exp)), datetime.time.max)
    da=timestamp = time.mktime(aa.timetuple())
    bi,_ = Bid.objects.get_or_create(chain = c ,number = n,txid = re,pub_key1 = pubkey1,pri_key1 = prikey1,pub_key2 = pubkey2, pri_key2 = prikey2,exp_time = da,product = pro)
    bi.save()
    a=1
    template = get_template('bid.html')
    html= template.render(locals())
    return HttpResponse(html)
Пример #6
0
    def test_encrypt_is_static(self):
        obj_agent1 = ec.ECC(curve=crypto_util.BTC_CURVE)
        obj_agent2 = ec.ECC(curve='sect283k1')
        cls_agent3 = ec.ECC

        encd1 = obj_agent1.encrypt(self.data, self.bob_pubkey)
        encd2 = obj_agent2.encrypt(self.data, self.bob_pubkey)
        encd3 = cls_agent3.encrypt(self.data, self.bob_pubkey)

        dcd1 = self.bob.decrypt(encd1)
        dcd2 = self.bob.decrypt(encd2)
        dcd3 = self.bob.decrypt(encd3)

        self.assertEqual(dcd1, dcd2)
        self.assertEqual(dcd2, dcd3)
Пример #7
0
def bidding(req,number):
    if 'chain' in req.session:
        chain= req.session['chain']
        read = req.session['read']
        write= req.session['write']
        user = req.session['uid']
        txid= req.session['tx_id']

    try:
        b = Bid.objects.get(number=number)
        c1=pyelliptic.ECC(pubkey=bytes.fromhex(b.pub_key1),privkey=bytes.fromhex(b.pri_key1),curve="secp256k1")
        start=gettx(b.txid)
        #print(start[0]['Start_price'])
        sp=bytes.fromhex(start[0]['Start_price'])
        #print(sp)
        s_price=int(c1.decrypt(sp).decode("utf-8"))
        req.session['number']=number
        if write=='yes':
            a=5
        else:
            a=3
    except:
        raise Http404('找不到標案編號')
    #template = get_template('price.html')
    #html= template.render(locals())
    #return HttpResponse(html)

    return render(req,'price.html',{'b':b,'user':user,'s_price':s_price,'chain':chain,'read':read,'write':write,'txid':txid,'a':a})
Пример #8
0
    def addMixpeer(self, id, rank, p2p_host, p2p_port, web_addr, public_key):
        """ Add a mixing peer to a mixnet's protocol state.

            Expected parameters:
            - id            The peer's ID
            - rank          The peer's rank within the particular mixnet
            - p2p_host      Hostname of the peer's P2P server
            - p2p_port      Port used by the peer's P2P server
            - web_addr      Address of the peer's web interface, without "https://"
            - public_key    Hexadecimal presentation of the peer's EC public key
        """
        crypt = pyelliptic.ECC(curve='secp256k1',
                               pubkey=public_key.decode('hex'))
        peer = {
            'id': id,
            'rank': rank,
            'web':
            'http://' + web_addr,  # FIXME: Use https when TLS is in place!
            'host': p2p_host,
            'port': p2p_port,
            'pub': public_key,
            'crypt': crypt,
            'instance': None
        }
        self._mixing_peers[rank] = peer
 def __init__(self, my_ip, my_port, store_file):
     TransportLayer.__init__(self, my_ip, my_port)
     self._myself = ec.ECC(curve='secp256k1')
     self.nick_mapping = {}
     self.nickname, self.secret, self.pubkey = self.load_crypto_details(
         store_file)
     self._log = logging.getLogger(self.__class__.__name__)
Пример #10
0
def main():
    if len(sys.argv) < 4:
        #print ("usage: python push-encryption.py <client-pub-key> <server-auth> <message>")
        sys.exit(1)

    # generate ephemerial public key using ecdh
    serverECDH = pyelliptic.ECC(curve="prime256v1")
    serverPubKey = b64e(serverECDH.get_pubkey()[1:])

    http_ece.keys[serverPubKey] = serverECDH
    http_ece.labels[serverPubKey] = "P-256"

    salt = os.urandom(16)

    clientPubKey64 = sys.argv[1]
    clientPubKey = base64.urlsafe_b64decode(clientPubKey64)

    clientAuthSecret64 = sys.argv[2]
    clientAuthSecret = base64.urlsafe_b64decode(clientAuthSecret64)

    messageRaw = sys.argv[3]
    messageRaw = messageRaw.encode('utf8')
    messageRaw = buffer(messageRaw)

    messageEncrypted = http_ece.encrypt(messageRaw,
                                        salt=salt,
                                        keyid=serverPubKey,
                                        dh=clientPubKey,
                                        authSecret=clientAuthSecret)

    print("%s,%s,%s" % (base64.urlsafe_b64encode(salt),
                        base64.urlsafe_b64encode(serverECDH.get_pubkey()),
                        base64.b64encode(messageEncrypted)),
          end="")
Пример #11
0
    def __init__(self, my_ip, my_port, market_id, store_file):

        TransportLayer.__init__(self, my_ip, my_port)

        self._myself = ec.ECC(curve='secp256k1')

        self.nick_mapping = {}

        # load nickname, secret and pubkey from store_file, which is a JSON file in ppl
        self.nickname, self.secret, self.pubkey = self.load_crypto_details(store_file)

        # Connect to database
        MONGODB_URI = 'mongodb://localhost:27017'
        _dbclient = MongoClient()
        self._db = _dbclient.openbazaar

        self.settings = self._db.settings.find_one({'id':"%s"%market_id})
        self.market_id = market_id
        # commented out to test entangled
        """
        if self.settings:
            self.nickname = self.settings['nickname'] if self.settings.has_key("nickname") else ""
            self.secret = self.settings['secret']
            self.pubkey = self.settings['pubkey']
        else:
            self.nickname = 'Default'
            key = bitcoin.EllipticCurveKey()
            key.new_key_pair()
            hexkey = key.secret.encode('hex')
            self._db.settings.insert({"id":'%s'%market_id, "secret":hexkey, "pubkey":bitcoin.GetPubKey(key._public_key.pubkey, False).encode('hex')})
            self.settings = self._db.settings.find_one({'id':"%s"%market_id})
        """
        self._log = logging.getLogger(self.__class__.__name__)
Пример #12
0
    def __init__(self, pubkey_hex=None, privkey_hex=None):
        """
        Convert the keys and initialize the cryptor implementation.

        @param pubkey_hex: Uncompressed BTC public key in hex format.
        @type pubkey_hex: str

        @param privkey_hex: Compressed BTC private key in hex format.
        @type privkey_hex: str
        """
        if privkey_hex is None and pubkey_hex is None:
            raise ValueError("Neither public nor private key was specified.")

        if pubkey_hex is None:
            pubkey_hex = arithmetic.privkey_to_pubkey(privkey_hex)

        pubkey_bin = pubkey_to_pyelliptic(pubkey_hex)

        self.has_privkey = privkey_hex is not None
        if self.has_privkey:
            privkey_bin = privkey_to_pyelliptic(privkey_hex)
        else:
            privkey_bin = None

        self._ec = ec.ECC(curve=BTC_CURVE,
                          pubkey=pubkey_bin,
                          privkey=privkey_bin)
Пример #13
0
def makeCryptor(privkey):
    private_key = a.changebase(privkey, 16, 256, minlen=32)
    public_key = pointMult(private_key)
    privkey_bin = '\x02\xca\x00\x20' + private_key
    pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32] + '\x00\x20' + public_key[-32:]
    cryptor = pyelliptic.ECC(curve='secp256k1',privkey=privkey_bin,pubkey=pubkey_bin)
    return cryptor
Пример #14
0
    def test_encode(self):
        recv_key = pyelliptic.ECC(curve="prime256v1")
        subscription_info = self._gen_subscription_info(recv_key)
        data = "Mary had a little lamb, with some nice mint jelly"
        push = WebPusher(subscription_info)
        encoded = push.encode(data)

        keyid = base64.urlsafe_b64encode(recv_key.get_pubkey()[1:])

        http_ece.keys[keyid] = recv_key
        http_ece.labels[keyid] = 'P-256'

        # Convert these b64 strings into their raw, binary form.
        raw_salt = base64.urlsafe_b64decode(push._repad(encoded['salt']))
        raw_dh = base64.urlsafe_b64decode(push._repad(encoded['crypto_key']))
        raw_auth = base64.urlsafe_b64decode(
            push._repad(subscription_info['keys']['auth']))

        decoded = http_ece.decrypt(buffer=encoded['body'],
                                   salt=raw_salt,
                                   dh=raw_dh,
                                   keyid=keyid,
                                   authSecret=raw_auth)

        eq_(decoded.decode('utf8'), data)
Пример #15
0
def private(passphrase):
    priv = hashlib.sha256("elliptic" +
                          hashlib.sha256(passphrase).digest()).digest()
    px, py = priv2pub(priv)
    key = pe.ECC(curve=CURVE)
    key._set_keys(px, py, priv)
    return key
Пример #16
0
    def generate_new_keypair(self):

        # Generate new keypair
        key = ec.ECC(curve='secp256k1')
        self.secret = key.get_privkey().encode('hex')
        pubkey = key.get_pubkey()
        signedPubkey = key.sign(pubkey)
        self.pubkey = pubkey.encode('hex')
        self._myself = key

        # Generate a node ID by ripemd160 hashing the signed pubkey
        guid = hashlib.new('ripemd160')
        guid.update(signedPubkey)
        self.guid = guid.digest().encode('hex')

        # Insert new record for the new user
        #self._db.settings.insert({"id":'%s' % market_id, "secret":self.secret, "pubkey":self.pubkey, "guid":self.guid})

        self._db.settings.update({"id": '%s' % self._market_id}, {
            "$set": {
                "secret": self.secret,
                "pubkey": self.pubkey,
                "guid": self.guid
            }
        }, True)
Пример #17
0
    def test_asymmetric_sing_ver(self):
        signature = self.bob.sign("Hello Alice")

        bob_pubkey = self.bob.get_pubkey()
        self.assertTrue(
            ec.ECC(pubkey=bob_pubkey).verify(signature, "Hello Alice")
        )
Пример #18
0
    def __init__(self, my_ip, my_port, market_id):

        self._log = logging.getLogger('[%s] %s' %
                                      (market_id, self.__class__.__name__))

        # Connect to database
        MONGODB_URI = 'mongodb://localhost:27017'
        _dbclient = MongoClient()
        self._db = _dbclient.openbazaar

        self._market_id = market_id
        self.nick_mapping = {}
        self._uri = "tcp://%s:%s" % (my_ip, my_port)

        # Set up
        self._setup_settings()

        self._dht = DHT(market_id, self.settings)

        self._myself = ec.ECC(pubkey=self.pubkey.decode('hex'),
                              privkey=self.secret.decode('hex'),
                              curve='secp256k1')

        TransportLayer.__init__(self, market_id, my_ip, my_port, self.guid)

        # Set up callbacks
        self.add_callback('ping', self._dht._on_ping)
        self.add_callback('findNode', self._dht._on_findNode)
        self.add_callback('findNodeResponse', self._dht._on_findNodeResponse)
Пример #19
0
    def __init__(self, key, algorithm):
        if algorithm not in self.valid_hash_algs:
            raise JWKError('hash_alg: %s is not a valid hash '
                           'algorithm', algorithm)
        self.curve = self.curve_map.get(algorithm)
        sha_map = {
            'ES256': 'sha256',
            'ES384': 'sha384',
            'ES512': 'sha512',
        }

        if isinstance(key, dict):
            self.prepared_key = self._process_jwk(key, sha_map[algorithm])
            return

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

            # be a bit smart about what you're doing.
            # keys must be in raw form, not ASN1, so convert if needed.

            # The private key provided for testing is a base64 ASN1 that has a
            # PEM wrapper. This may take a bit of guesswork...
            der = self.pem_to_der(key)
            # The key dictates the curve, this emulates the ecdsa lib
            (self.curve, raw_key, raw_pub) = self.asn_to_raw(der, self.curve)
            self.prepared_key = pyelliptic.ECC(curve=self.curve,
                                               privkey=raw_key,
                                               pubkey=raw_pub,
                                               hasher=sha_map[algorithm])
            return
        raise JWKError('Unable to parse an ECKey from key: %s' % key)
Пример #20
0
def create_ecc(priv_key, curve=DEFAULT_CURVE):
    # enable both hexilified or unhexlified priv_key input
    try:
        priv_key = unhexlify(priv_key)
    except Exception:
        pass
    pub_key = ecc_priv_to_pub_key(priv_key, curve=curve)
    return pyelliptic.ECC(privkey=priv_key, pubkey=pub_key, curve=curve)
Пример #21
0
 def sign(self, private_key):
     signature = pyelliptic.ECC(curve='secp256k1',
                                privkey=private_key,
                                pubkey=self._source.decode('hex')).sign(
                                    self.to_signable()).encode('hex')
     self._signature = signature
     self._tx_hash = self._calculate_tx_hash()
     return signature
Пример #22
0
def makeCryptor(privkey):
    privkey_bin = '\x02\xca\x00 ' + a.changebase(privkey, 16, 256, minlen=32)
    pubkey = a.changebase(a.privtopub(privkey), 16, 256, minlen=65)[1:]
    pubkey_bin = '\x02\xca\x00 ' + pubkey[:32] + '\x00 ' + pubkey[32:]
    cryptor = pyelliptic.ECC(curve='secp256k1',
                             privkey=privkey_bin,
                             pubkey=pubkey_bin)
    return cryptor
Пример #23
0
def get_shared_secret(server_pub_key, private_key):
    user_pub_key = get_pub_key(private_key)
    network_code = get_network_code(private_key)
    uncompressed_user_key = binascii.unhexlify(pybitcointools.decompress(user_pub_key))
    uncompressed_server_key = binascii.unhexlify(pybitcointools.decompress(server_pub_key))
    user_priv_key_bin = binascii.unhexlify(pybitcointools.encode_privkey(private_key, 'hex', network_code))
    user = pyelliptic.ECC(privkey=user_priv_key_bin, pubkey=uncompressed_user_key, curve='secp256k1')
    shared_secret = user.get_ecdh_key(uncompressed_server_key)
    return shared_secret
Пример #24
0
def private(passphrase):
    if six.PY3 and isinstance(passphrase, six.string_types):
        passphrase = passphrase.encode()
    priv = hashlib.sha256(b"elliptic" +
                          hashlib.sha256(passphrase).digest()).digest()
    px, py = priv2pub(priv)
    key = pe.ECC(curve=CURVE)
    key._set_keys(px, py, priv)
    return key
Пример #25
0
def makePrivCryptor(privkey_hex):
    privkey_bin = '\x02\xca\x00 ' + arithmetic.changebase(
        privkey_hex, 16, 256, minlen=32)
    pubkey_hex = arithmetic.privkey_to_pubkey(privkey_hex)
    pubkey_bin_bare = arithmetic.changebase(pubkey_hex, 16, 256, minlen=65)[1:]
    pubkey_bin = '\x02\xca\x00 ' + pubkey_bin_bare[:
                                                   32] + '\x00 ' + pubkey_bin_bare[
                                                       32:]
    cryptor = ec.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin)
    return cryptor
Пример #26
0
 def test_send_no_headers(self, mock_post):
     recv_key = pyelliptic.ECC(curve="prime256v1")
     subscription_info = self._gen_subscription_info(recv_key)
     data = "Mary had a little lamb"
     WebPusher(subscription_info).send(data)
     eq_(subscription_info.get('endpoint'), mock_post.call_args[0][0])
     pheaders = mock_post.call_args[1].get('headers')
     eq_(pheaders.get('ttl'), '0')
     ok_('encryption' in pheaders)
     eq_(pheaders.get('content-encoding'), 'aesgcm')
Пример #27
0
 def encrypt(self, data):
     try:
         if self.pub is not None:
             hexkey = hexToPubkey(self.pub)
             return ec.ECC(curve='secp256k1').encrypt(data, hexkey)
         else:
             self.log.error('Public Key is missing')
             return False
     except Exception as e:
         self.log.error('Encryption failed. %s' % e)
Пример #28
0
 def setCryptoParams(self, private_key_hex, public_key_hex):
     try:
         # Do not decode here as the hex presentation is used more often (decode only for initializing ECC)
         self._prvkey = private_key_hex
         self._pubkey = public_key_hex
     except TypeError:
         raise TypeError('Could not decode keys.')
     self._crypter = pyelliptic.ECC(curve='secp256k1',
                                    privkey=self._prvkey.decode('hex'),
                                    pubkey=self._pubkey.decode('hex'))
     return
Пример #29
0
def bid_price(req):
    if req.method =='GET':
        return render(req,'hello.html')
    if 'chain' in req.session:
        chain= req.session['chain']
        read = req.session['read']
        write= req.session['write']
        user = req.session['uid']
        txid= req.session['tx_id']
   
    c = req.POST['chain']
    n = req.POST['number']
    #n=''.join([random.choice(string.digits) for _ in range(4)])
    u = req.POST['user']
    b = req.POST['bid_txid']
    p = req.POST['price']
    
    k=Bid.objects.get(txid=b)
    key1=k.pub_key1
    key2=k.pub_key2
    
    pk1=pyelliptic.ECC(pubkey=bytes.fromhex(k.pub_key1),privkey=bytes.fromhex(k.pri_key1),curve="secp256k1")
    pk2=pyelliptic.ECC(pubkey=bytes.fromhex(k.pub_key2),privkey=bytes.fromhex(k.pri_key2),curve="secp256k1")

    
    uk=pk2.encrypt(u, pk2.get_pubkey()).hex()
    pp=pk1.encrypt(p, pk1.get_pubkey()).hex()
    

    message={"Type":"bid_price","Chain":c,"Number":n,"User":uk,"Price":pp}
    me=json.dumps(message)
    result= OP_RETURN_store(me)
    be = result['txids'][0]
    ls= Bid.objects.get(txid=b,number=n)
    #pi,_ = list_Bid.objects.get_or_create(list_id = be,number=n,price=p,bid_itxid=ls.txid)
    pi = list_Bid.objects.create(list_id = be,number=n,price=p,bid_txid=ls)
    pi.save()
    a=4
    template = get_template('price.html')
    html= template.render(locals())
    return HttpResponse(html)
Пример #30
0
    def encrypt(self, data):
        try:
            if self._pub is not None:
                result = ec.ECC(curve='secp256k1').encrypt(
                    data, CryptoPeerConnection.hexToPubkey(self._pub))

                return result
            else:
                self._log.error('Public Key is missing')
                return False
        except Exception as e:
            self._log.error('Encryption failed. %s' % e)