Esempio n. 1
0
def __decode_high_scores(high_score_list_b64_encoded):
    # -- Decode with b64 framework
    high_score_list_b64_decoded = base64.base64_decode(
        high_score_list_b64_encoded.encode('utf-8'))
    # -- Use json.loads to create an object out of a string
    high_score_list = json.loads(high_score_list_b64_decoded[0])
    return high_score_list
Esempio n. 2
0
def problem6():
   print "Problem 6:"
   f = open('problem6data.txt', 'r')
   inputString = "".join([base64_decode(line.strip())[0] for line in f])
   keySizeList = findKeySizes(inputString, 2, 40)
   result = repeatingXorDecrypt(inputString, keySizeList[0][0])
   print result
def verify_sig(user_certfile, sig_file, file_to_sign):
    backend = default_backend()

    with open(user_certfile, 'rb') as file:
        certificate = x509.load_pem_x509_certificate(data=file.read(),
                                                     backend=backend)

    public_key = certificate.public_key()
    # Use the PKCS1v15 padding
    pad = asympadding.PKCS1v15()

    # Load the signature from the signature file
    with open(sig_file, 'rb') as file:
        # get signature from file
        sig = file.read().split(b"-----BEGIN SIGNATURE-----\n")[1].split(
            b"\n-----END SIGNATURE-----")[0]

        myhash, digest = getMyhashDigest(file_to_sign)

        try:
            public_key.verify(signature=base64_decode(sig)[0],
                              data=digest,
                              padding=pad,
                              algorithm=utils.Prehashed(myhash))
        except:
            print("sig is invalid")
        else:
            print("sig is valid")
def verify_signature(filename, backend_sig):
    with open(filename, 'rb') as file:
        data_to_encrypt = file.read()

    myhash = hashes.SHA256()
    hasher_sha256 = hashes.Hash(myhash, backend_sig)
    hasher_sha256.update(data_to_encrypt)
    digest = hasher_sha256.finalize()

    #load the public key from task 2
    with open("ku.pem", 'rb') as file:
        public_key = serialization.load_pem_public_key(data=file.read(),
                                                       backend=backend_sig)

    # Load the signature from the signature file
    with open("file.sig", 'rb') as file:
        #get signature from file
        sig = file.read().split(b"-----BEGIN SIGNATURE-----\n")[1].split(
            b"\n-----END SIGNATURE-----")[0]

    # unpad using same algorithm
    pad = asympadding.PSS(mgf=asympadding.MGF1(hashes.SHA256()),
                          salt_length=asympadding.PSS.MAX_LENGTH)

    try:
        public_key.verify(signature=base64_decode(sig)[0],
                          data=digest,
                          padding=pad,
                          algorithm=utils.Prehashed(myhash))
    except:
        print("sig is invalid")
    else:
        print("signature was verified")
Esempio n. 5
0
def to_external_url(request):
    url = request.GET.get('url')
    ref = request.GET.get('ref')
    request_ad = request.GET.get('ad')
    try:
        from_url = base64_decode(bytes(ref, 'utf-8'))[0].decode('utf-8')
        ad_id = base64_decode(bytes(request_ad, 'utf-8'))[0].decode('utf-8')
        ad = Ad.objects.get(id=ad_id)
    except:
        from_url = None
        ad = None
    if not url or not from_url or not from_url.startswith(request.build_absolute_uri('/')) or not ad:
        return HttpResponseBadRequest()
    response = HttpResponseRedirect(url)
    response['Referer'] = from_url
    action.send(request.user, verb=ACTION_FOLLOW_EXTERNAL_AD, target=ad)
    return response
Esempio n. 6
0
    def validate(cls,
                 contents: Union[bytes, str],
                 types: int = PNG + JPEG + GIF) -> Result:
        if not contents:
            return Success(None)
        if isinstance(contents, str):
            contents = bytes(contents, 'ascii')
        header = bytes(memoryview(contents)[0:36])
        if len(header) != 36:
            return Failure(
                ValErrorEntry(_ERR_IMG_CONTENT_TOO_SHORT,
                              'Not valid data contents. Content too short'))
        if not header.startswith(b'data:image/'):
            return Failure(
                ValErrorEntry(_ERR_IMG_MISSING_HEADER,
                              'Not valid data contents. Expected image data'))
        img = header.split(b';', 1)
        if len(img) != 2:
            return Failure(
                ValErrorEntry(_ERR_IMG_MISSING_HEADER,
                              'Not valid data contents. Expected image data'))

        image_type = img[0][11:]
        val = cls._IMG_VAL.get(image_type)
        it = cls._IMG_TYPES.get(image_type)
        if not it or it & types == 0 or not val:
            formats = []
            if types & cls.PNG:
                formats.append('PNG')
            if types & cls.JPEG:
                formats.append('JPEG')
            if types & cls.GIF:
                formats.append('GIF')
            formats = ', '.join(formats)
            return Failure(
                ValErrorEntry(_ERR_IMG_TYPE,
                              f'Unknown image type. Expected {formats}'))

        if not img[1].startswith(b'base64,'):
            return Failure(
                ValErrorEntry(_ERR_IMG_CONTENT,
                              'Unknown image type. Expected base64 contents'))

        content_start = len(img[0]) + 8
        try:
            image_bytes = base64_decode(contents[content_start:])[0]
        except (TypeError, binascii.Error) as ex:
            return Failure(
                ValErrorEntry(_ERR_IMG_CONTENT,
                              f'Invalid image contents. {ex}'))

        result = val(image_bytes)
        if result.ok:
            return Success(
                cls.Image(img_type=image_type.decode('ascii'),
                          img_contents=image_bytes))
        else:
            return result
Esempio n. 7
0
def crosshair(request):

    response = HttpResponse()
    response['Content-type'] = 'image/png'
    response['Expires'] = 'Fri, 09 Dec 2327 08:34:31 GMT'
    response['Last-Modified'] = 'Fri, 24 Sep 2010 11:36:29 GMT'
    output, length = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAwElEQVQoz6WTwY0CMQxFX7DEVjCShUQnc6YCdzCH1EYDboICphb28veA2UULSBHzLpEif9vfcRr/kHQF9jzz3Vr74hWSLpKUmYoIubvMTO6uiFBmqri8FPbeBazAAhwBq3MB1t77c4IH4flNy9T9+Z7g12Nm3iu+Ez4mWMvCFUmKCFVrIywRcasuSe6u8jbC0d3/xGamGs4IZmaSpB3ANE0Ah0HxoeLZAczzDHAaFJ8qfuO0N73z5g37dLfbll/1A+4O0Wm4+ZiPAAAAAElFTkSuQmCC')
    response.write(output)
    return response
Esempio n. 8
0
def crosshair(request):

    response = HttpResponse()
    response['Content-type'] = 'image/png'
    response['Expires'] = 'Fri, 09 Dec 2327 08:34:31 GMT'
    response['Last-Modified'] = 'Fri, 24 Sep 2010 11:36:29 GMT'
    output, length = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAwElEQVQoz6WTwY0CMQxFX7DEVjCShUQnc6YCdzCH1EYDboICphb28veA2UULSBHzLpEif9vfcRr/kHQF9jzz3Vr74hWSLpKUmYoIubvMTO6uiFBmqri8FPbeBazAAhwBq3MB1t77c4IH4flNy9T9+Z7g12Nm3iu+Ez4mWMvCFUmKCFVrIywRcasuSe6u8jbC0d3/xGamGs4IZmaSpB3ANE0Ah0HxoeLZAczzDHAaFJ8qfuO0N73z5g37dLfbll/1A+4O0Wm4+ZiPAAAAAElFTkSuQmCC')
    response.write(output)
    return response
Esempio n. 9
0
 def _getFromArguments(self, request):
     for argument in request.arguments():
         values = request.get_all(argument)
         if argument == "jsonrpc":
             assert len(values) != 0
             if len(values) > 1:
                 error("multiple jsonrpc version indicator")
                 self.error = JsonRpcError.INVALID_REQUEST
                 return
             self.jsonrpc = values[0]
             continue
         if argument == "method":
             debug("argument %s has %s" % (argument, values))
             assert len(values) != 0
             if len(values) > 1:
                 error("multiple methods are given")
                 self.error = JsonRpcError.INVALID_REQUEST
                 return
             self.method = values[0]
             continue
         if argument == "id":
             debug("argument %s has %s" % (argument, values))
             assert len(values) != 0
             if len(values) > 1:
                 error("multiple ids are given")
                 self.error = JsonRpcError.INVALID_REQUEST
                 return
             self.id = values[0]
             continue
         if argument == "params":
             for params in values:
                 try:
                     decoded_params = base64_decode(params)
                 except:
                     error("failed to decode BASE64 for params")
                     self.error = JsonRpcError.PARSE_ERROR
                     return
                 try:
                     loaded_params = loads(decoded_params)
                 except:
                     error("failed to decode JSON for params")
                     self.error = JsonRpcError.PARSE_ERROR
                     return
                 try:
                     assert isinstance(loaded_params, list)
                 except:
                     error(
                         "params is expected to be an array of objects, that is, a list"
                     )
                     self.error = JsonRpcError.PARSE_ERROR
                 self.params.extend(loaded_params)
             continue
         self.dict[argument] = values
     assert not isinstance(self.id, list)
 def _getFromArguments(self, request):
     for argument in request.arguments():
         values = request.get_all(argument)
         if argument == "jsonrpc":
             assert len(values) != 0
             if len(values) > 1:
                 error("multiple jsonrpc version indicator")
                 self.error = JsonRpcError.INVALID_REQUEST
                 return
             self.jsonrpc = values[0]
             continue
         if argument == "method":
             debug("argument %s has %s" % (argument, values))
             assert len(values) != 0
             if len(values) > 1:
                 error("multiple methods are given")
                 self.error = JsonRpcError.INVALID_REQUEST
                 return
             self.method = values[0]
             continue
         if argument == "id":
             debug("argument %s has %s" % (argument, values))
             assert len(values) != 0
             if len(values) > 1:
                 error("multiple ids are given")
                 self.error = JsonRpcError.INVALID_REQUEST
                 return
             self.id = values[0]
             continue
         if argument == "params":
             for params in values:
                 try:
                     decoded_params = base64_decode(params)
                 except:
                     error("failed to decode BASE64 for params")
                     self.error = JsonRpcError.PARSE_ERROR
                     return
                 try:
                     loaded_params = loads(decoded_params)
                 except:
                     error("failed to decode JSON for params")
                     self.error = JsonRpcError.PARSE_ERROR
                     return
                 try:
                     assert isinstance(loaded_params, list)
                 except:
                     error("params is expected to be an array of objects, that is, a list")
                     self.error = JsonRpcError.PARSE_ERROR
                 self.params.extend(loaded_params)
             continue
         self.extra[argument] = values
     assert not isinstance(self.id, list)
Esempio n. 11
0
    def do(self, theEnv, theString, *args, **kargs):
        """
        function handler implementation
        """
        
        aString = self.resolve(theEnv, self.semplify(theEnv, theString, types.String, ("1", "string")))
        
        aString = base64_decode(aString)[0]

        try:
            parsed = theEnv.network.getParser().parse(aString, extended=True)
        except Exception, e:
            print >> theEnv.RESOURCES['werror'], theEnv.network.getParser().ExceptionPPrint(e, aString)
            return types.Symbol('FALSE')
Esempio n. 12
0
    def do(self, theEnv, theString, *args, **kargs):
        """
        function handler implementation
        """

        aString = self.resolve(
            theEnv,
            self.semplify(theEnv, theString, types.String, ("1", "string")))

        aString = base64_decode(aString)[0]

        try:
            parsed = theEnv.network.getParser().parse(aString, extended=True)
        except Exception, e:
            print >> theEnv.RESOURCES['werror'], theEnv.network.getParser(
            ).ExceptionPPrint(e, aString)
            return types.Symbol('FALSE')
    def create(self, validated_data):
        body = validated_data.get('body')
        body = base64_decode(body)[0]

        document = Document()
        document.account = self.context['account']
        document.folder = validated_data.get('folder')
        document.type = validated_data.get('type') or Document.OTHER
        document.file = ContentFile(body, validated_data.get('name'))
        document.user = self.context['user']

        old_doc = validated_data.get('old_doc')
        if old_doc:
            document.previous_version = old_doc.id

        document.save()

        return document
Esempio n. 14
0
def decode_base64(string_to_decode):
    return base64_decode(string_to_decode)[0]
Esempio n. 15
0
myhash = hashes.SHA256()
hasher_sha256 = hashes.Hash(myhash, backend)
hasher_sha256.update(data_to_encrypt)
digest = hasher_sha256.finalize()

#load the public key from task 2
with open("ku.pem", 'rb') as file:
    public_key = serialization.load_pem_public_key(data=file.read(),
                                                   backend=backend)

# Load the signature from the signature file
with open("file.sig", 'rb') as file:
    #get signature from file
    sig = file.read().split(b"-----BEGIN SIGNATURE-----\n")[1].split(
        b"\n-----END SIGNATURE-----")[0]
    print("sig", sig)

    # unpad using same algorithm
    # unpad using same algorithm
    pad = padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                      salt_length=padding.PSS.MAX_LENGTH)

    try:
        public_key.verify(signature=base64_decode(sig)[0],
                          data=digest,
                          padding=pad,
                          algorithm=utils.Prehashed(myhash))
    except:
        print("sig is invalid")
    else:
        print("sig is valid")
Esempio n. 16
0
 def on_message(ws, message):
     # Rancher message was encoded in utf-8 base64
     decoded_message = base64_decode(message)
     if decoded_message:
         decoded_message = decoded_message[0]
         print decoded_message,
Esempio n. 17
0
    salt_length=padding.PSS.MAX_LENGTH)
sig = private_key.sign(  # signs the private key
    data=digest,
    padding=pad,
    algorithm=utils.Prehashed(
        myhash))  # pass the hash object into Prehashed function

path_eninput = os.path.abspath(mydata)
path2_enoutput = os.path.abspath(mydata2)

try:
    public_key.verify(  # verify signature method
        signature=sig,
        data=digest,
        padding=pad,
        algorithm=utils.Prehashed(myhash))
    sig_fname = 'sig.pem'

    path = os.path.abspath(sig_fname)
    file2 = open(sig_fname, 'wb')  # writes message into bytes like object
    file2.write(sig)
    file2.close()

except:
    hasher.update(b"message to hash"
                  )  # update our message digest if signature is incorrect
    hasher.verify(
        b"incorrect signature")  # exception thrown if signature is incorrect
else:
    print(base64_decode(sig))  # print base64 signature decoded into bytes