Example #1
0
 def _decryptConsole(cls, command, nonce):
     if cls._consoleKey is None:
         result = command
     else:
         result = libnacl.crypto_secretbox_open(command, nonce,
                                                cls._consoleKey)
     return result.decode('UTF-8')
 def test_secret_box(self):
     msg = b'Are you suggesting coconuts migrate?'
     sk1 = libnacl.utils.salsa_key()
     nonce1 = libnacl.utils.rand_nonce()
     enc_msg = libnacl.crypto_secretbox(msg, nonce1, sk1)
     self.assertNotEqual(msg, enc_msg)
     clear_msg = libnacl.crypto_secretbox_open(enc_msg, nonce1, sk1)
     self.assertEqual(msg, clear_msg)
Example #3
0
 def decrypt(self, ctxt, nonce=None):
     '''
     Decrypt the given message, if no nonce is given the nonce will be
     extracted from the message
     '''
     if nonce is None:
         nonce = ctxt[:libnacl.crypto_secretbox_NONCEBYTES]
         ctxt = ctxt[libnacl.crypto_secretbox_NONCEBYTES:]
     if len(nonce) != libnacl.crypto_secretbox_NONCEBYTES:
         raise ValueError('Invalid nonce')
     return libnacl.crypto_secretbox_open(ctxt, nonce, self.sk)
Example #4
0
    def test_secretbox(self):
        msg = b'Are you suggesting coconuts migrate?'

        nonce = libnacl.utils.rand_nonce()
        key = libnacl.utils.salsa_key()

        c = libnacl.crypto_secretbox(msg, nonce, key)
        m = libnacl.crypto_secretbox_open(c, nonce, key)
        self.assertEqual(msg, m)

        with self.assertRaises(ValueError):
            libnacl.crypto_secretbox(msg, b'too_short', key)

        with self.assertRaises(ValueError):
            libnacl.crypto_secretbox(msg, nonce, b'too_short')

        with self.assertRaises(ValueError):
            libnacl.crypto_secretbox_open(c, b'too_short', key)

        with self.assertRaises(ValueError):
            libnacl.crypto_secretbox_open(c, nonce, b'too_short')
Example #5
0
    def decrypt(self, s):
        """Decrypt a secrets structure ``s`` with our private key."""
        key = None
        nonce = binascii.a2b_base64(s['nonce'])
        sender = binascii.a2b_base64(s['sender'])
        secret = s['keys'].get(self.publicKeyBase64)
        if secret is None:
            print repr(self.publicKeyBase64), 'not in', s['keys'].keys()
            raise ValueError('This node is not in the list of recipients')

        box = binascii.a2b_base64(secret)
        key = libnacl.crypto_box_open(box, nonce, sender, self.privateKey)
        box = binascii.a2b_base64(s['secret'])
        return libnacl.crypto_secretbox_open(box, nonce, key)
    def apiCall(self, a):
        # Process one incoming binary API message

        # Get timestamp which is also the nonce
        t = a[:8]
        t = struct.unpack("<Q", t)
        # reject very old stuff
        if t < (time.time() - 3600) * 1000000:
            return {}

        # Get the key ID, which is just the hash of the key.
        k = a[8:40]

        # Get the data
        d = a[40:]

        if not k == libnacl.crypto_generichash(self.syncKey):
            return

        d = libnacl.crypto_secretbox_open(d, a[:8] + '\0' + 16, self.secretKey)
        d = json.loads(d)

        writePassword = d.get("writePassword", '')

        if writePassword and not writePassword == self.config.get(
                'sync', 'writePassword', fallback=None):
            raise RuntimeError("Bad Password")

        r = {'records': []}
        if "getNewArrivals" in d:
            cur = self.conn.cursor()
            cur.execute(
                "SELECT json,signature FROM document WHERE json_extract(json,'$._time')>?",
                (d['getNewArrivals'], ))

            for i in cur:
                r['records'].append([i])

        if "insertDocuments" in d:
            for i in 'insertDocuments':
                if writePassword:
                    self.setDocument(i[0], i[1])

        return r
Example #7
0
 def _decryptConsole(cls, command, nonce):
     if cls._consoleKey is None:
         return command
     return libnacl.crypto_secretbox_open(command, nonce, cls._consoleKey)
Example #8
0
 def decrypt(ec: EncryptedWallet, key: bytes) -> 'Wallet':
     decryped = crypto_secretbox_open(ec.raw, ec.nonce, key)
     decoded = decryped.decode()
     wallet = jsonpickle.decode(decoded)
     return wallet
Example #9
0
 def _decryptConsole(cls, command, nonce):
     if cls._consoleKey is None:
         result = command
     else:
         result = libnacl.crypto_secretbox_open(command, nonce, cls._consoleKey)
     return result.decode('UTF-8')
Example #10
0
 def _decryptConsole(cls, command, nonce):
     if cls._consoleKey is None:
         return command
     return libnacl.crypto_secretbox_open(command, nonce, cls._consoleKey)
Example #11
0
 def decrypt_response(self, data, nonce):
     """decrypt console"""
     result = libnacl.crypto_secretbox_open(data, nonce, self.console_key)
     return result.decode('utf-8')
Example #12
0
 def decrypt(ec: EncryptedWallet, key: bytes) -> 'Wallet':
     decryped = crypto_secretbox_open(ec.raw, ec.nonce, key)
     decoded = decryped.decode()
     wallet = jsonpickle.decode(decoded)
     return wallet
Example #13
0
    def handleBinaryAPICall(self, a, sessionObject=None):
        # Process one incoming binary API message.  If part of a sesson, using a sesson objert enables certain features.

        #Get the key hint
        k = a[:16]
        a = a[16:]

        # Get timestamp which is also the nonce
        remoteNodeID = a[:32]
        a = a[32:]

        #Verify that it is from who we think
        a = libnacl.crypto_sign_open(a, remoteNodeID)

        tbytes = a[:8]
        t = struct.unpack("<Q", tbytes)[0]
        # reject very old stuff
        if t < (time.time() - 3600) * 1000000:
            return {}

        # Get the data
        d = a[8:]

        #We can use either the real key, or the write password, which is only used for "centralized mode"
        if k == libnacl.crypto_generichash(
                self.syncKey.encode("utf8").ljust(32, b'\0'))[:16]:
            openingKey = self.syncKey
            writePassword = False

        elif k == libnacl.crypto_generichash(
                self.writePassword.encode("utf8").ljust(32, b'\0'))[:16]:
            openingKey = self.writePassword
            writePassword = True
        else:
            raise RuntimeError("Bad key hint")

        openingKey = openingKey.encode("utf8").ljust(32, b'\0')

        d = libnacl.crypto_secretbox_open(d, a[:8] + b'\0' * 16, openingKey)
        d = json.loads(d)

        r = {'records': []}

        if sessionObject and not sessionObject.alreadyDidInitialSync:
            cur = self.threadLocal.conn.cursor()
            cur.execute("SELECT lastArrival FROM peers WHERE peerID=?",
                        (remoteNodeID, ))

            c = cur.fetchone()
            if c:
                c = c[0]
            else:
                c = 0
            #No falsy value allowed, that would mean don't get new arrivals
            r['getNewArrivals'] = c or 1
            sessionObject.alreadyDidInitialSync = True

        if "getNewArrivals" in d:
            cur = self.threadLocal.conn.cursor()
            #Avoid dumping way too much at once
            cur.execute(
                "SELECT json,signature FROM document WHERE json_extract(json,'$.arrival')>? LIMIT 100",
                (d['getNewArrivals'], ))

            #Declares that there are no records left out in between this time and the first time we actually send
            r['recordsStartFrom'] = d['getNewArrivals']

            for i in cur:
                if not 'records' in r:
                    r['records'] = []
                print(i)
                r['records'].append([i[0], base64.b64encode(i[1]).decode()])

                sessionObject.lastResyncFlushTime = max(
                    sessionObject.lastResyncFlushTime,
                    json.loads(i[0])['arrival'])

        if "records" in d and d['records']:
            for i in d['records']:
                #No need sig verify, if we are using PW verification.
                #Set a flag to request that the server send us any records that came after the last one,
                self.setDocument(i[0], None if writePassword else i[1])
                r['getNewArrivals'] = i[0]['arrival']

            #Set a flag saying that
            cur = self.threadLocal.conn.cursor()
            #If the recorded lastArrival is less than the incoming recordsStartFrom, it would mean that there is a gap in which records
            #That we don't know about could be hiding.   Don't update the timestamp in that case, as the chain is broken.
            #We can still accept new records, but we will need to request everything all over again starting at the breakpoint to fix this.
            cur.execute(
                "UPDATE peers SET lastArrival=? WHERE peerID=? AND lastArrival !=? AND lastArrival>=?",
                (r['getNewArrivals'], remoteNodeID, r['getNewArrivals'],
                 r.get("recordsStartFrom")))

        return self.encodeMessage(r)
Example #14
0
 def decrypt(self, d, k, nonce):
     return libnacl.crypto_secretbox_open(d, nonce, k)
Example #15
0
 def decrypt(self, ct, key, counter):
     try:
         return libnacl.crypto_secretbox_open(ct, counter, key)
     except:
         return None
 def decrypt(self,d,k,nonce):
     return libnacl.crypto_secretbox_open(d, nonce, k)
Example #17
0
def login_request(request):
    print()
    print()
    print(request.META['REMOTE_ADDR'])
    print(request.META['HTTP_HOST'])
    email = request.query_params['email']
    password = request.query_params['password']
    print(email)
    print(password)

    n = binascii.unhexlify(email[0:libnacl.crypto_secretbox_NONCEBYTES * 2])
    eml = binascii.unhexlify(email[libnacl.crypto_secretbox_NONCEBYTES * 2:])
    passcode = binascii.unhexlify(password)
    ky = binascii.unhexlify(key)

    #print(n)
    #print(eml)
    #print(passcode)

    email = libnacl.crypto_secretbox_open(eml, n, ky)
    passcode = libnacl.crypto_secretbox_open(passcode, n, ky)

    print(email.decode())
    print(passcode.decode())

    try:
        qsetUsers = Users.objects.get(email=email.decode(),
                                      passcode=passcode.decode())
        userserializer = UsersSerializer(qsetUsers)
        #print(userserializer.data)

        userId = userserializer.data['userId']
        qsetUserInfo = UserLoginInfo.objects.get(userId=userId)
        #print(qsetUserInfo)

        userInfoSerializer = UsersLoginInfoSerializer(qsetUserInfo)
        #print(userInfoSerializer.data)

        qsetUserInfo.visits = userInfoSerializer.data['visits'] + 1
        qsetUserInfo.lastSuccess = timezone.now()
        qsetUserInfo.save()

        qsetUserInfo = UserLoginInfo.objects.get(
            userId=userserializer.data['userId'])
        userInfoSerializer = UsersLoginInfoSerializer(qsetUserInfo)
        #print(userInfoSerializer.data)

        return Response({
            'status': True,
            'data': {
                'userId': userserializer.data['userId'],
                'success': userInfoSerializer.data['lastSuccess'],
                'unsuccess': userInfoSerializer.data['lastUnsuccess'],
                'visits': userInfoSerializer.data['visits']
            }
        })
    except Users.DoesNotExist as e:
        #print(e.__str__())
        return Response({'status': False, 'data': e.__str__()})
    except UserLoginInfo.DoesNotExist as e:
        #print(e.__str__())
        return Response({'status': False, 'data': e.__str__()})
    except:
        e = sys.exc_info()[0]
        #print(e)
        return Response({'status': False, 'data': e.__name__})