Esempio n. 1
0
def twistEdVerify2(gen_point, pub_key, sig, hash, a, d, p, n):
    """Verify a signature, using an implementation compatible with twistEdSign2
    :param gen_point: x, y of the generator point
    :param pub_key:
    :param sig: (r, s) (or (u,s)) that is the signature
    :param hash: the hash of the message to sign
    :param a: the constant 'a' as used for the twisted edwards curve
    :param d: the constant 'd' as used for the twisted edwards curve
    :param p: the prime field p as used for the prime field
    :param n: the order of the generator point (order of the subgroup generated by gen_point)
    :return: True if the signature is valid, False if not.
    """
    u, s = sig
    P = pub_key
    sG = twistEdPointMultiply(gen_point, s, a, d, p)
    R = twistEdPointMultiply(gen_point, u, a, d, p)
    bytes_R = sha3_512(point_to_bytes(R)).digest()
    bytes_P = sha3_512(point_to_bytes(P)).digest()
    bytes_msg = int_to_bytes(hash)
    h = int_from_bytes(sha3_512(bytes_R + bytes_P + bytes_msg).digest()) % n
    hP = twistEdPointMultiply(pub_key, h, a, d, p)

    _sG = twistEdPointAdd(R, hP, a, d, p)

    valid = sG == _sG
    return valid
Esempio n. 2
0
def twistEdSign2(gen_point, priv, hash, a, d, p, n):
    """A safer implementation of twistEdSign, using a different scheme but the same principles as the previous implementation
    :param gen_point: x1, y1 of the generator point
    :param priv: the private key to sign with
    :param hash: hash of the message to sign
    :param a: the constant 'a' as used for the twisted edwards curve
    :param d: the constant 'd' as used for the twisted edwards curve
    :param p: the prime field p as used for the prime field
    :param n: the order of the generator point (order of the subgroup generated by gen_point)
    :return: (R, s) that is the signature
    """

    # The idea this time is we use S = R + hP, where 'S' and 'R' are given via the signature and P is the public key.
    # 'h' is the hash(P + R + z) where 'z' is the message (or message hash)
    # The client has full disclosure on constructing 'h' due to the given parameters {P, R, z}
    # This yields the equation sG = rG + hpG, where rG = R and pG = P
    # Note: this means 'p' must be kept entirely secret, which it is due to the elliptic curve discrete logarithm problem
    # To keep the signature rigid, we make h = hash(hash(message)+bytes(R)+bytes(P)). This is a hard problem for someone trying to make a bogus signature
    # because the malicious entity would need to know private key (p) in order to calculate a bogus r', s'
    # via modular inverse and use the equation s'G = r'G + h'P
    # That (h'P) is essentially the ECDLP due to hP = h(pG)

    P = twistEdPointMultiply(gen_point, priv, a, d, p)
    bytes_msg = int_to_bytes(hash)
    r = int_from_bytes(
        sha3_512(sha3_512(int_to_bytes(priv)).digest() +
                 bytes_msg).digest()) % n
    R = twistEdPointMultiply(gen_point, r, a, d, p)
    bytes_R = sha3_512(point_to_bytes(R)).digest()
    bytes_P = sha3_512(point_to_bytes(P)).digest()
    h = int_from_bytes(sha3_512(bytes_R + bytes_P + bytes_msg).digest()) % n
    s = (r + h * priv % n) % n

    return r, s  # alternatively, return R, s
Esempio n. 3
0
 def post(self, request):
     try:
         resultpoolservice = request.data.get('ResultPoolService')
         method = resultpoolservice['method']
         method = method.lower()
         
     except:
         return Response(f"No method")
     
     if method == "getticket":
         ticket = sha3_512((str(datetime.now()) + str(randint(1000, 3000))).encode('utf-8')).hexdigest()
         a = ResultPoolService(r_ticket=ticket)
         a.save()
         return Response(f'Place for result has created.check ticket: {ticket}')
         
     elif method == "put":
         try:
             r_ticket = resultpoolservice["r_ticket"]
             result = resultpoolservice["result"]
         except:
             return Response(f"You need r_ticket and result")
         ResultPoolService.objects.filter(r_ticket=r_ticket).update(text=result, flag=1)
         return Response(f"{r_ticket} is ready")
     
     elif method == "get":
         try:
             r_ticket = resultpoolservice["r_ticket"]
         except:
             return Response(f"You need r_ticket")
         obj = ResultPoolService.objects.filter(r_ticket=r_ticket).get()
         result = obj.text
         return Response(f"{result} is your answer")
     
     elif method == "delete":
         try:
             r_ticket = resultpoolservice["r_ticket"]
         except:
             return Response(f"You need r_ticket")
         ResultPoolService.objects.filter(r_ticket=r_ticket).delete()
         return Response(f"{r_ticket} has successfully deleted")
     
     elif method == "subscribe":
         try:
             r_ticket = resultpoolservice["r_ticket"]
             endpoint = resultpoolservice["endpoint"]
         except:
             return Response(f"You need r_ticket and endpoint")
         a = Subscribtion(r_ticket = r_ticket, endpoint = endpoint)
         a.save()
         return Response(f"{r_ticket} has successfully subscribed")
     
     elif method == "unsubscribe":
         try:
             r_ticket = resultpoolservice["r_ticket"]
         except:
             return Response(f"You need r_ticket")
         Subscribtion.objects.filter(r_ticket=r_ticket).delete()
         return Response(f"{r_ticket} has successfully unsubscribed")
Esempio n. 4
0
def register(endpoint, pool):
    if PoolServices.objects.filter(endpoint=endpoint):
        if PoolServices.objects.filter(endpoint=endpoint, pool=pool):
            ticket = PoolServices.objects.filter(endpoint=endpoint, pool=pool)[0]
        else:
            return 'error'    
    else:
        ticket = sha3_512((endpoint + str(pool)).encode('utf-8')).hexdigest()
        q = PoolServices(ticket=ticket, endpoint=endpoint, pool=pool, timestamp=getNow())
        q.save()
        return ticket
Esempio n. 5
0
    def setstate(self, state):
        state = deepcopy(state)
        if state['fast']:
            fast_state = state['fast_impl']
            del state['fast_impl']
            c = state['c']
            if c == 448:
                state['fast_impl'] = _sha3.sha3_224()
            elif c == 512:
                state['fast_impl'] = _sha3.sha3_256()
            elif c == 768:
                state['fast_impl'] = _sha3.sha3_384()
            elif c == 1024:
                state['fast_impl'] = _sha3.sha3_512()
            elif c == 576:
                state['fast_impl'] = _sha3.sha3_0()
            else:
                raise TypeError('Malformed state')
            state['fast_impl'].state = fast_state

        for k, v in state.iteritems():
            setattr(self, k, v)
    def handle_new_request(
            self,
            parameters: SpectralAnalysisParameters) -> SpectralAnalysisFlow:
        id = sha3_512(
            f'{parameters.youtube_url}'
            f'_{parameters.frame_size_power}_'
            f'{parameters.overlap_factor}'.encode('utf-8')).hexdigest()

        spectral_request = SpectralAnalysisFlow(
            id='result_' + id,
            parameters=parameters,
            status='requested',
        )

        maybe_existing_request = self.orm.load_request_by_id(
            spectral_request.id)
        if maybe_existing_request is None or maybe_existing_request.status != 'finished':
            self.orm.save_request(spectral_request)
            self.message_publisher.publish(
                'render-request',
                spectral_request.json().encode("utf-8"))
        else:
            logger.info('already computed...')
        return spectral_request
Esempio n. 7
0
    def __init__(self, r=1024,c=576,fixed_out=False,duplex=False,verbose=False):
        """Constructor:

        r: bitrate (default 1024)
        c: capacity (default 576)
        verbose: print the details of computations(default:False)
        r + c must be 25, 50, 100, 200, 400, 800 or 1600 (recommended 1600)
        see http://keccak.noekeon.org/NoteOnKeccakParametersAndUsage.pdf
        """

        if fixed_out and duplex:
            raise ValueError('It is nonsense to try to instantiate a fixed output, duplex Keccak')
        self.fixed_out = fixed_out
        self.duplex = duplex
        self.verbose = verbose
        if (r<0) or (r%8!=0):
            raise ValueError('r must be a multiple of 8 in this implementation')
        self.r = r
        self.c = c
        self.b = b = r+c
        if b not in [25, 50, 100, 200, 400, 800, 1600]:
            raise ValueError('b value not supported - use 25, 50, 100, 200, 400, 800 or 1600')
        self.w = b//25
        self.l=(self.w-1).bit_length()
        self.nr=12+2*self.l
        self.done_absorbing = False

        if has_fast and not duplex:
            if fixed_out and b == 1600 and c == 448:
                self.fast = True
                self.fast_impl = _sha3.sha3_224()
                return
            elif fixed_out and b == 1600 and c == 512:
                self.fast = True
                self.fast_impl = _sha3.sha3_256()
                return
            elif fixed_out and b == 1600 and c == 768:
                self.fast = True
                self.fast_impl = _sha3.sha3_384()
                return
            elif fixed_out and b == 1600 and c == 1024:
                self.fast = True
                self.fast_impl = _sha3.sha3_512()
                return
            elif not fixed_out and b == 1600 and c == 576:
                self.fast = True
                self.fast_impl = _sha3.sha3_0()
                return

        self.fast = False
        if verbose:
            print "Create a Keccak function with (r=%d, c=%d (i.e. w=%d))" % (r,c,(r+c)//25)

        # Initialisation of state
        self.S = ((0,0,0,0,0),
                  (0,0,0,0,0),
                  (0,0,0,0,0),
                  (0,0,0,0,0),
                  (0,0,0,0,0))
        self.P = ''
        self.output_cache = ''
Esempio n. 8
0
    def post(self, request):
        try:
            poolservice = request.data.get('PoolService')
            method = poolservice['method']
            method = method.lower()
        except:
            return Response(f"No method")
        
        if method == "get":
            services = PoolServices.objects.all()
            serializer = PoolServicesSerializer(services, many=True)
            return Response({"PoolServices": serializer.data})
        
        elif method == "register":
            try:
                endpoint = poolservice['endpoint']
                pool = poolservice['pool']
            except:
                return Response(f"You need endpoint and pool")
            if PoolServices.objects.filter(endpoint=endpoint):
                if PoolServices.objects.filter(endpoint=endpoint, pool=pool):
                    obj = PoolServices.objects.filter(endpoint=endpoint, pool=pool)[0]
                    ticket = obj.getTicket()
                    q = self.update(ticket, 'SA')
                else:
                    return Response({"Error"})   
            else:
                ticket = sha3_512((endpoint + str(pool)).encode('utf-8')).hexdigest()
                q = PoolServices(ticket=ticket, endpoint=endpoint, pool=pool, timestamp=getNow())
                serializer = self.serialize(q)
                q.save()
                if serializer.is_valid(raise_exception=True):
                    poolservice_saved = serializer.save()
                    ticket = poolservice_saved.ticket
            return Response(f"PoolService created succesfully. Ticket: {ticket}")

        elif method == "update":
            #ticket; state, timestamp
            try:
                ticket = poolservice['ticket']
                pool = poolservice['pool']
            except:
                return Response(f"You need ticket and pool")
            saved_pool = get_object_or_404(PoolServices.objects.all(), pk=ticket)
            serializer = PoolServicesSerializer(instance=saved_pool, data={"pool": pool, "timestamp":getNow()}, partial=True)
            if serializer.is_valid(raise_exception=True):
                pool_saved = serializer.save()
            return Response(f"success: PoolService {pool_saved.endpoint} updated successfully")
        
        elif method == "unregister":
            try:
                ticket = poolservice['ticket']
            except:
                return Response(f"You need ticket")
            PoolServices.objects.filter(pk=ticket).delete()
            return Response(f"success: PoolService {ticket} deleted successfully")
     
        elif method == "getwork":
            try:
                pool = poolservice['pool']
            except:
                return Response(f"You need pool")
            if PoolServices.objects.filter(pool=pool, state='SA').count() < 1:
                return Response(f"No available pool service")
            else:
                obj = PoolServices.objects.filter(pool=pool, state='SA').first()
                print(obj)
                ticket = obj.getTicket()
                self.update(ticket, 'SP')
                a = PoolPending(ticket=obj, timer=getNow())
                a.save()
                return Response(f"Pool servie {obj.endpoint} is busy now")
Esempio n. 9
0
def put(text, pool, ticket=''):
    if ticket == '':
        ticket = sha3_512((text + str(pool)).encode('utf-8')).hexdigest()
    a = ResultPoolService(ticket=ticket, text=text, pool=pool)
    a.save()