Beispiel #1
0
 def generateHMACSecret(self):
     self.logshit("sekurelib.generateHMACSecret")
     keybytes = get_random_bytes(16)
     shake = SHAKE256.new()
     shake.update(keybytes)
     out = hexlify(shake.read(32))
     for count in range(10000):
         shake = SHAKE256.new()
         shake.update(out)
         out = hexlify(shake.read(32))
     return out.decode()
Beispiel #2
0
 def generateOTPKey(self):
     import random
     self.logshit("sekurelib.generateOTPKey")
     shake = SHAKE256.new()
     shake.update(get_random_bytes(128))
     out = hexlify(shake.read(7000))
     for count in range(10000):
         shake = SHAKE256.new()
         shake.update(out)
         shake.update(get_random_bytes(16))
         out = hexlify(shake.read(7000))
     out = out.decode()
     id = str(random.randrange(0,1000)).zfill(4)
     out = {'id':id,'key':out,'uses':5}
     return out
Beispiel #3
0
    def evaluate(self, x):
        """
        Returns the y in Y of x in X of the PPRF F: X->Y. It will return an exception should x be a punctured value
        or not in the defined range of the PPRF F.

        Arguments:
            x: The value for which F(x) will be returned
        
        Exception:
            PuncturedException: Should F(x) be punctured.
            ValueError: Should x not be member of X in F: X->Y
        """
        if x in self.punctures:
            raise PuncturedException
        if x < 0 or x > 231:
            raise ValueError

        mult = 1
        for j in range(len(self.outerPPRF.primes)):
            if (j != x) and not (j in self.punctures):
                mult *= self.outerPPRF.primes[j] % self.outerPPRF.N
        ret = square_and_multiply(self.g, self.outerPPRF.N, mult)
        hash = SHAKE256.new()
        hash.update(ret.to_bytes(int(self.outerPPRF.secpem / 8), 'little'))
        return hash.read(int(self.outerPPRF.secpem / 8))
Beispiel #4
0
    def hash_to_point(self, message, salt):
        """
        Hash a message to a point in Z[x] mod(Phi, q).
        Inspired by the Parse function from NewHope.
        """
        n = self.n
        if q > (1 << 16):
            raise ValueError("The modulus is too large")

        k = (1 << 16) // q
        # emessage = message.encode('utf-8')
        # Create a SHAKE object and hash the salt and message.
        shake = SHAKE256.new()
        shake.update(salt)
        shake.update(message)
        # Output pseudorandom bytes and map them to coefficients.
        hashed = [0 for i in range(n)]
        i = 0
        j = 0
        while i < n:
            # Takes 2 bytes, transform them in a 16 bits integer
            twobytes = shake.read(2)
            elt = (twobytes[0] << 8) + twobytes[1]  # This breaks in Python 2.x
            # Implicit rejection sampling
            if elt < k * q:
                hashed[i] = elt % q
                i += 1
            j += 1
        return hashed
Beispiel #5
0
    def _verify_ed448(self, msg_or_hash, signature, ph):

        if len(signature) != 114:
            raise ValueError("The signature is not authentic (length)")

        flag = int(ph)
        # dom4(flag, self._context)
        dom4 = b'SigEd448' + bchr(flag) + \
               bchr(len(self._context)) + self._context

        PHM = msg_or_hash.read(64) if ph else msg_or_hash

        # Section 5.2.7

        # Step 1
        try:
            R = import_public_key(signature[:57]).pointQ
        except ValueError:
            raise ValueError("The signature is not authentic (R)")
        s = Integer.from_bytes(signature[57:], 'little')
        if s > self._order:
            raise ValueError("The signature is not authentic (S)")
        # Step 2
        k_hash = SHAKE256.new(dom4 + signature[:57] + self._A + PHM).read(114)
        k = Integer.from_bytes(k_hash, 'little') % self._order
        # Step 3
        point1 = s * 8 * self._key._curve.G
        # OPTIMIZE: with double-scalar multiplication, with no SCA
        # countermeasures because it is public values
        point2 = 8 * R + k * 8 * self._key.pointQ
        if point1 != point2:
            raise ValueError("The signature is not authentic")
    def hashSign(self, m, vi, l1, delta, si):
        # Not used currently, but could be used to verify token parts are valid
        """
        H'(m)
        :param: m  - message (plaintext)
        :param: vi  - verification key share
        :param: l1 - Secondary security parameter
        :param: delta  - n factorial 
        :param: si - secret share
        :returns: (z,c) - pair
        """
        x = self.hash(m)
        r = randrange(0, pow(2, int.bit_length(self.N) + 2 * l1))
        vprime = pow(self.v, r, self.N)
        xtilde = pow(x, 4 * delta, self.N)
        xprime = pow(xtilde, r, self.N)
        xi = pow(x, 4 * delta * si, self.N)

        b = SHAKE256.new()
        # Via Shoup p.215,
        b.update(bytes(self.v % self.N))
        b.update(bytes(xtilde))
        b.update(bytes(vi % self.N))
        b.update(bytes(xi % self.N))
        b.update(bytes(vprime))
        b.update(bytes(xprime))
        c = int(hexlify(b.read(l1)), 16) % self.N
        z = c * si + r

        return (z, c)
Beispiel #7
0
def new(entropy):
    if not isinstance(entropy, bytes):
        raise TypeError("BIP85DRNG input entropy must be bytes.")

    if len(entropy) != 64:
        raise ValueError("BIP85DRNG input entropy must be exactly 512 bits.")

    return SHAKE256.new(entropy)
Beispiel #8
0
 def test_short_256(self):
     test_vectors = load_tests("SHA3", "ShortMsgKAT_SHAKE256.txt")
     for result, data, desc in test_vectors:
         data = tobytes(data)
         hobj = SHAKE256.new(data=data)
         assert(len(result) % 2 == 0)
         digest = hobj.read(len(result)//2)
         hexdigest = "".join(["%02x" % bord(x) for x in digest])
         self.assertEqual(hexdigest, result)
 def test_short_256(self):
     test_vectors = load_tests("SHA3", "ShortMsgKAT_SHAKE256.txt")
     for result, data, desc in test_vectors:
         data = tobytes(data)
         hobj = SHAKE256.new(data=data)
         assert (len(result) % 2 == 0)
         digest = hobj.read(len(result) // 2)
         hexdigest = "".join(["%02x" % bord(x) for x in digest])
         self.assertEqual(hexdigest, result)
Beispiel #10
0
    def _sign_ed448(self, msg_or_hash, ph):

        flag = int(ph)
        # dom4(flag, self._context)
        dom4 = b'SigEd448' + bchr(flag) + \
               bchr(len(self._context)) + self._context

        PHM = msg_or_hash.read(64) if ph else msg_or_hash

        # See RFC 8032, section 5.2.6

        # Step 2
        r_hash = SHAKE256.new(dom4 + self._key._prefix + PHM).read(114)
        r = Integer.from_bytes(r_hash, 'little') % self._order
        # Step 3
        R_pk = EccKey(point=r * self._key._curve.G)._export_eddsa()
        # Step 4
        k_hash = SHAKE256.new(dom4 + R_pk + self._A + PHM).read(114)
        k = Integer.from_bytes(k_hash, 'little') % self._order
        # Step 5
        s = (r + k * self._key.d) % self._order

        return R_pk + s.to_bytes(57, 'little')
Beispiel #11
0
    def hash(self, x):
        """
        :param: x (bytestring) : value to hash
        :returns: H(x): x hashed into Zn*
        """

        b = SHAKE256.new()
        b.update(x)

        # reading the bitlength of parameter +1 from hash
        length = int.bit_length(self.N) + 1
        h = int(hexlify(b.read(length)), 16) % self.N
        # calculaitng h in Zn
        return h
Beispiel #12
0
    def shake_256(self, size: int = 64):
        """Get Shake-256 hash
        
        Shake is an Extendable Output Function (XOF) of the SHA-3 hash algorithm, 
        part of the Keccak family, allowing for variable output length/size.

        Args:
            size (int, optional): How many bytes to read, by default 64

        Returns:
            Chepy: The Chepy object. 
        """
        h = SHAKE256.new()
        h.update(self._convert_to_bytes())
        self.state = binascii.hexlify(h.read(size))
        return self
Beispiel #13
0
 def new_test(self, data=data, result=tv.md):
     hobj = SHAKE256.new(data=data)
     digest = hobj.read(len(result))
     self.assertEqual(digest, result)
Beispiel #14
0
 def new_test(self, data=data, result=tv.md):
     hobj = SHAKE256.new(data=data)
     digest = hobj.read(len(result))
     self.assertEqual(digest, result)
Beispiel #15
0
 def __init__(self, key):
     self.bs = AES.block_size
     shake = SHAKE256.new(key.encode('utf-8'))
     self.key = shake.read(32)
Beispiel #16
0
def encrypt(s, flag):
    raw = bytes(np.mod(s, 256).tolist())
    shake = SHAKE256.new()
    shake.update(raw)
    pad = shake.read(len(flag))
    return strxor(flag, pad)