Esempio n. 1
0
def test_to_str():
    s = 'Märchen'
    ok_(str(pyqrcode.create(s)))

    s = '外来語'
    qr = pyqrcode.create(s)
    ok_(str(pyqrcode.create(s)))
Esempio n. 2
0
def test_kanji_enforce_binary():
    data = '点'
    # 1. Try usual mode --> kanji
    qr = pyqrcode.create(data)
    eq_('kanji', qr.mode)
    # 2. Try another encoding --> binary
    qr = pyqrcode.create(data, mode='binary', encoding='utf-8')
    eq_('binary', qr.mode)
Esempio n. 3
0
def test_unicode_utf8():
    s = '\u263A'  # ☺ (WHITE SMILING FACE)
    try:
        pyqrcode.create(s, encoding='latin1')
        raise Exception('Expected an error for \u263A and ISO-8859-1')
    except ValueError:
        pass
    qr = pyqrcode.create(s, encoding='utf-8')
    eq_('binary', qr.mode)
def decryptMiniProdFile(key):	
	# List files in the export folder
	export_file_names = [f for f in listdir("export/") if isfile(join("export/", f))]
		
	# Ask for Mooltipass ID
	mooltipass_ids = raw_input("Enter Mooltipass ID: ")
	
	# Generate a list with Mooltipass IDs
	mooltipass_ids_list = mooltipass_ids.split(' ')
	
	# Find Mooltipass ID in files
	for mooltipass_id in mooltipass_ids_list:
		for file_name in export_file_names:
			if "Mooltipass-" + mooltipass_id + ".txt" in file_name:
				print "Found export file:", file_name
				data = pickle_read(join("export/",file_name))			
				decrypted_data = seccure.decrypt(data, key, curve='secp521r1/nistp521')
				items = decrypted_data.split('|')
				#print decrypted_data
				# Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID, flush write
				
				if True:
					# Print Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID (might get quite big)
					data_qr = pyqrcode.create(decrypted_data, error="L")
					print(data_qr.terminal(quiet_zone=1))
					raw_input("Press enter:")
				else:
					# This is just here in case you need it....
					# key1
					key1 = items[1]
					key1_qr = pyqrcode.create(key1)
					print ""
					print "AES key 1:", key1
					print(key1_qr.terminal(quiet_zone=1))
					
					# key2
					key2 = items[2]
					key2_qr = pyqrcode.create(key2)
					print ""
					print "AES key 2:", key2
					print(key2_qr.terminal(quiet_zone=1))
					
					# Request UID
					request = items[3]
					request_qr = pyqrcode.create(request)
					print "Request UID key:", request
					print(request_qr.terminal(quiet_zone=1))
					
					# UID
					request = items[4]
					request_qr = pyqrcode.create(request)
					print "UID :", request
					print(request_qr.terminal(quiet_zone=1))
def make_pdf(params, num_codes):
    pagesize = params.pagesize
    c = canvas.Canvas(params.pdf_filename, pagesize=pagesize)
    d = tempfile.mkdtemp()
    width, height = pagesize
    x_offset = 0.0
    y_offset = 0.0
    for i in range(0, num_codes):
        text = '{}{:04d}'.format(params.prefix, i)
        filename = '{}/{}.png'.format(d, text)
        c.setFont('Courier-Bold', params.text_size)
        c.drawCentredString(x_offset + params.text_x,
                            y_offset + params.text_y,
                            text)
        code = pyqrcode.create(text, error='H', version=1, mode='alphanumeric')
        code.png(filename, scale=20, module_color=[0,0,0], background=[255,255,255])
        c.drawImage(filename,
                    x_offset + params.barcode_corner_x,
                    y_offset + params.barcode_corner_y,
                    width = params.barcode_size,
                    height = params.barcode_size)
        if params.checkerboard_square_size is not None:
            draw_checkerboard(c, x_offset, y_offset, params)

        if params.cut_lines:
            for line in params.cut_lines:
                xl,yl,xt,yt = line
                c.line(xl, yl, xt, yt)

        # if params.margins:
        #     left, right, top, bottom = params.margins
        #     width,height = params.pagesize
        #     if left > 0:
        #         c.line(left, 0, left, height)
        #     if right > 0:
        #         c.line(width-right, 0, width-right, height)
        #     if bottom > 0:
        #         c.line(0, bottom, width, bottom)
        #     if top > 0:
        #         c.line(0, height-top, width, height - top)

        if args.verbose is True:
            print 'made id {} at offset ({}, {})'.format(i, x_offset/inch, y_offset/inch)
            print 'going to id {}'.format(params.end_num)
        i += 1
        x_offset += params.column_interval
        if x_offset > (width - params.column_interval):
            # end of a row
            if args.verbose is True:
                print 'end of row'
            x_offset = 0
            y_offset += params.row_interval
        if y_offset > (height - params.row_interval):
            # top of a page
            if args.verbose is True:
                print 'top of new page'
            y_offset = 0
            c.showPage() # finish the page, and start a new one
    c.save()
    shutil.rmtree(d)
Esempio n. 6
0
 def save_png(cls, content, buffer=None):
     qr_code = pyqrcode.create(content)
     if buffer is None:
         buffer = io.BytesIO()
     # qr_code.png(buffer, scale=2, quiet_zone=0,  module_color=(255,255,255), background=(1,1,1,1))
     qr_code.png(buffer)
     return buffer
Esempio n. 7
0
def qr( qr_id=None ):
    if qr_id:
        if request.method == "GET":
            width = request.args.get('width', '800')
            height = request.args.get('height', '600')
            table = db.session.query(Table).filter(Table.id == qr_id).first()
            if table is None:
                return jsonify({'msg': 'None'}), 404
            svg = render_template( str(qr_id) + '.svg', width=width, height=height)
            response = make_response(svg)
            response.content_type = 'image/svg+xml'
            return response
        if request.method == "POST":
            if qr_id > 20 : qr_id =20
            total = db.session.query(Table).count()
            import pyqrcode
            for i in range( qr_id - total ):
                table = Table( str( total + i + 1)  )
                db.session.add(table)            
                qr = pyqrcode.create( table.orderUrl())
                qr.svg('templates/' + str( total + i + 1) + '.svg', scale=8)
            else:
                db.session.commit()
            table = db.session.query(Table).filter(Table.id == qr_id).first()
            form = TableDescriptionForm(request.form)
            form.validate() 
            table.description = form.description
            form.populate_obj( table)
            db.session.add(table)
            db.session.commit()
    if request.is_xhr:
        tables = db.session.query(Table)
        result = tables_schema.dump(tables)
        return jsonify({'tables': result.data})
    return render_template('QRs.html', form=TableDescriptionForm(), title='QR') 
Esempio n. 8
0
def generateQrCode(request):
    if request.method == 'POST':
        form = ToPhoneForm(request.POST)
        if form.is_valid():
            # process data
            print "\n\nProcessing data..."
            print form.cleaned_data

            link_val = form.cleaned_data.get('copy_value', None)
            # short circuit if no value exists, this should never happen
            # because the form will not validate without input
            if not link_val:
                return render(request, 'tophone.html', {'form': ToPhoneForm()})

            qrcode = pyqrcode.create(link_val)
            uuid_val = uuid() # third-party short, url-safe uuid generator
            img_name = "qrcoderepo/svg/%s.svg" % uuid_val
            print img_name
            qrcode.svg(img_name, scale=8)
            print "svg image created"

            return HttpResponseRedirect(uuid_val + '/')

    else:
        form = ToPhoneForm()

    return render(request, 'tophone.html', {'form': form})
Esempio n. 9
0
def _read_node_pubkey(cbdir, privkey_path=u'key.priv', pubkey_path=u'key.pub'):

    node_pubkey_path = os.path.join(cbdir, pubkey_path)

    if not os.path.exists(node_pubkey_path):
        raise Exception('no node public key found at {}'.format(node_pubkey_path))

    node_pubkey_tags = _parse_keyfile(node_pubkey_path)

    node_pubkey_hex = node_pubkey_tags[u'public-key-ed25519']

    qr = pyqrcode.create(node_pubkey_hex, error='L', mode='binary')

    mode = 'text'

    if mode == 'text':
        node_pubkey_qr = qr.terminal()

    elif mode == 'svg':
        import io
        data_buffer = io.BytesIO()

        qr.svg(data_buffer, omithw=True)

        node_pubkey_qr = data_buffer.getvalue()

    else:
        raise Exception('logic error')

    node_pubkey = {
        u'hex': node_pubkey_hex,
        u'qrcode': node_pubkey_qr
    }

    return node_pubkey
Esempio n. 10
0
def getQRArray(text, errorCorrection):
	""" Takes in text and errorCorrection (letter), returns 2D array of the QR code"""
	# White is True (1)
	# Black is False (0)
	# ECC: L7, M15, Q25, H30

	# Create the object
	qr = pyqrcode.create(text, error=errorCorrection)

	# Get the terminal representation and split by lines (get rid of top and bottom white spaces)
	plainOut = qr.terminal().split("\n")[5:-5]

	# Initialize the output 2D list
	out = []

	for line in plainOut:
		thisOut = []
		for char in line:
			if char == u'7':
				# This is white
				thisOut.append(1)
			elif char == u'4':
				# This is black, it's part of the u'49'
				thisOut.append(0)
		# Finally add everything to the output, stipping whitespaces at start and end
		out.append(thisOut[4:-4])

	# Everything is done, return the qr code list
	return out
Esempio n. 11
0
File: main.py Progetto: peuter/gosa
    def setTwoFactorMethod(self, user_dn, factor_method, user_password=None):
        if factor_method == "u2f":
            print(_("checking U2F devices..."))
            # check for devices
            devices = u2f.list_devices()
            if len(devices) == 0:
                print(_("No U2F devices found, aborting!"))
                return

        response = self.proxy.setTwoFactorMethod(user_dn, factor_method, user_password)
        if response is None:
            return
        if factor_method == "u2f":
            # bind
            response = loads(response)
            for device in devices:
                # The with block ensures that the device is opened and closed.
                print(_("Please touch the flashing U2F device now."))
                with device as dev:
                    # Register the device with some service
                    for request in response['registerRequests']:
                        registration_response = u2f.register(device, request, request['appId'])
                        response = self.proxy.completeU2FRegistration(user_dn, registration_response)
                        if response is True:
                            print(_("U2F authentication has been enabled"))

        elif response.startswith("otpauth://"):
            url = pyqrcode.create(response, error='L')
            print(url.terminal(quiet_zone=1))
        else:
            print(response)
    def new(watchID,expireTime,permission = None ):
        import pyqrcode
        from setting import qr_local_path as qrPath
        ## init watch dir if not exist
        ## just convient for debug
        watchSession.chkWatchDir(watchID)

        ## clean exist session
        watchSession.clean(watchID)

        ## Generator Session
        sKey = strftime(watchSession.timeFormat) + "-session" + "-" + watchID
        sData = [watchID,sKey,expireTime,permission]

        sFile = open(path.join(wDir,watchSession.filename) , 'a' )
        sFile.writelines(json.dumps(sData)+ "\n")
        sFile.close()

        if ( not path.exists(qrPath) ):
            mkdir(qrPath)

        url = pyqrcode.create(sKey,error='L')
        url.png(path.join(qrPath,sKey+'.png'), scale=8, module_color=[0, 0, 0, 255], background=[0xff, 0xff, 0xff])

        return [0,sKey,'sucessful generate session key']
Esempio n. 13
0
def qr_encode_material(wallet_password_filename, wallet_material_name, qr_page_message):
    import pyqrcode
    qr = None
    with open(wallet_password_filename, 'r') as fin:
        qr = pyqrcode.create(fin.read(), version=40, error='M')
        qr_temp_file_name = working_directory_name + "/qrtempfile.eps"
        qr.eps(qr_temp_file_name, scale=2.5) # this will write the qrcode to the disk. only uncomment if you want that
        

        #generate page    
        print_font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 16) #may want to play with this; very ubuntu specific.  
        qr = Image.open(qr_temp_file_name)
        qr_page = Image.new("RGB", (850, 1100), 'white')  # assuming an 8.5 x 11 page at 300 DPI, no margin, fully specified
            
        #    lay out the page   
        draw = ImageDraw.Draw(qr_page)
        draw.text((10 ,10), ' /\_/\  ',(0,0,0),font=print_font)
        draw.text((10 ,24), "(='.'=) meow offline material for wallet" + wallet_material_name ,(0,0,0),font=print_font)
        draw.text((10,40), ' > ^ <  ',(0,0,0),font=print_font)
        draw.text((10,46), qr_page_message ,(0,0,0),font=print_font)
        draw = ImageDraw.Draw(qr_page)
        
        qr_page.paste(qr, (10, 70))
        
        # uncomment these if you want a separate on-disk file of some sort. note we are not setting local directory here
        # qr_temp_file_name_jpeg = working_directory_name + "/qrtempfile.jpeg"
        # qr_page.save(qr_temp_file_name_jpeg, 'JPEG')
        # print "temp sample QRcode jpeg file is " + qr_temp_file_name_jpeg
        # debug = raw_input( 'press any key to continue...')
        
        
        #test_page.save('test_page.png', 'PNG')
        #test_page.save('test_page.bmp', 'BMP')
            
        qr_print_success = "/"
        while not qr_print_success.lower()[0] in ('y', 'r', 'q'):
    
            try:
                    
                # generate the page
                lpr =  subprocess.Popen(["/usr/bin/lpr", '-E'], stdin=subprocess.PIPE)
                output = StringIO.StringIO()
                format = 'jpeg' # or 'JPEG' or whatever you want
                
                qr_page.save(output, format)
                lpr.communicate(output.getvalue())
                            
                output.close() # what happens when this is here?
                
                qr_print_success = raw_input( 'Did the item ' + qr_page_message + ' print for wallet ' + wallet_material_name + ' successfully? (Yes | Retry | Quit)')
                if qr_print_success.lower()[0] == 'q':
                    splash('goodbye!')
                    raise Exception('Program cancelled by User')
                elif qr_print_success.lower()[0] == 'y':
                    return
                elif qr_print_success.lower()[0] == 'r':
                    qr_print_success = "/"
                        
            except Exception as e:
                print('Error attempting to print:' + str(e)) 
Esempio n. 14
0
 def generate_QRcode(self, text, escala):
     qr = pyqrcode.create(text)
     output = StringIO.StringIO()
     qr.png(output, scale=escala)
     result = output.getvalue().encode("base64")
     # se devuelve un PNG codificado en base64
     return result
Esempio n. 15
0
def test_no_line_class():
    qr = pyqrcode.create('test')
    out = io.BytesIO()
    qr.svg(out, lineclass=None)
    root = _parse_xml(out)
    path_el = _get_path(root)
    ok_('class' not in path_el.attrib)
Esempio n. 16
0
def test_custom_svg_class():
    qr = pyqrcode.create('test')
    out = io.BytesIO()
    qr.svg(out, svgclass='test-class')
    root = _parse_xml(out)
    ok_('class' in root.attrib)
    eq_('test-class', root.attrib.get('class'))
Esempio n. 17
0
def showQRCode(url):
    import os
    import pyqrcode
    import kodigui
    # from kodijsonrpc import rpc

    class ImageWindow(kodigui.BaseDialog):
        xmlFile = 'script.cinemavision-image.xml'
        path = kodiutil.ADDON_PATH
        theme = 'Main'
        res = '1080i'

        def __init__(self, *args, **kwargs):
            kodigui.BaseDialog.__init__(self)
            self.image = kwargs.get('image')

        def onFirstInit(self):
            self.setProperty('image', self.image)

    with kodiutil.Progress(T(32582, 'QR Code'), T(32583, 'Creating QR code...')):
        code = pyqrcode.create(url)
        QRDir = os.path.join(kodiutil.PROFILE_PATH, 'settings', 'QR')
        if not os.path.exists(QRDir):
            os.makedirs(QRDir)
        QR = os.path.join(QRDir, 'QR.png')
        code.png(QR, scale=6)
    # rpc.Player.Open(item={'path': QRDir})
    ImageWindow.open(image=QR)
Esempio n. 18
0
def qrcode(admin_id):
    """ Presents the user with a QR code to scan to setup 2 factor authentication
    """
    # render qrcode for FreeTOTP
    admin = Admins.query.get_or_404(admin_id)
    if admin.id != current_user.id:
        raise GenericError("You may not view other admin's QR codes")
    if admin.otp_active:
        return ("", 204)
    admin.generate_otp_secret()
    try:
        db.session.add(admin)
        db.session.commit()
    except ValidationError as e:
        raise e
    except Exception as e:
        db.session.rollback()
        json_logger("error", current_user.username, "The following error occurred in qrcode: {0}".format(str(e)))
        raise GenericError("The administrator could not be updated")
    url = pyqrcode.create(admin.get_totp_uri())
    stream = BytesIO()
    url.svg(stream, scale=5)
    return (
        stream.getvalue(),
        200,
        {
            "Content-Type": "image/svg+xml",
            "Cache-Control": "no-cache, no-store, must-revalidate",
            "Pragma": "no-cache",
            "Expires": "0",
        },
    )
def create_barcodes(file,delim):

    currenttime=time.time()
    tempfilename='temp_'+str(currenttime)
    cwd = os.getcwd()
    directory = str(cwd)+"/"+str(tempfilename)
    path = str(directory)+"/"
    barcodefile = str(file)

    if not os.path.exists(directory):
        os.makedirs(directory)
    else:
        raise RuntimeError("A temp directory of this name exists, fatal error.")

    if delim=='tab':
        delimvalue='\t'
    elif delim=='comma':
        delimvalue=','
    else:
        delimvalue=None

    with open(barcodefile) as fileinput:
        reader = csv.reader(fileinput, delimiter=delimvalue)
        for row in reader:
            barcodeqr=qr.create(str(row[0]))
            currenttime1 = time.time()
            barname=str(path)+str(currenttime1)+".png"
            barcodeqr.png(barname , scale=2)
            barcodepic=cv2.imread(barname)
            barcodepic1=cv2.copyMakeBorder(barcodepic,10,20, 25, 25,cv2.BORDER_CONSTANT,value=(255,255,255))

            ix,iy,iz=np.shape(barcodepic1)
            cv2.putText(barcodepic1,str(row[1]),(25,ix-5),cv2.FONT_HERSHEY_SIMPLEX,0.4,(0,0,0))
            cv2.imwrite(barname,barcodepic1)
    return path
Esempio n. 20
0
    def handle(self, request, data):
        try:
            user = fiware_api.keystone.user_get(request, request.user.id)
            if request.POST.get(u'enable', None):
                security_question = data['security_question']
                security_answer = data['security_answer']
            else:
                security_question = security_answer = None
            (key, uri) = fiware_api.keystone.two_factor_new_key(request=request,
                                                                user=user,
                                                                security_question=security_question,
                                                                security_answer=security_answer)

            LOG.info('Enabled two factor authentication or new key requested')
            # NOTE(@federicofdez) Fix this to always use redirect
            if request.is_ajax():
                context = {}
                context['two_factor_key'] = key
                qr = pyqrcode.create(uri, error='L')
                qr_buffer = io.BytesIO()
                qr.svg(qr_buffer, scale=3)
                context['two_factor_qr_encoded'] = base64.b64encode(qr_buffer.getvalue())
                context['hide'] = True
                return shortcuts.render(request, 'settings/multisettings/_two_factor_newkey.html', context)
            else:
                cache_key = uuid.uuid4().hex
                cache.set(cache_key, (key, uri))
                request.session['two_factor_data'] = cache_key
                messages.success(request, "Two factor authentication was successfully enabled.")
                return shortcuts.redirect('horizon:settings:multisettings:newkey')

        except Exception as e:
            exceptions.handle(request, 'error')
            LOG.error(e)
            return False
Esempio n. 21
0
def register_device(request):
    if request.method == 'POST':
        secret_key = request.POST['secret_key']
        otp = request.POST['otp']
        totp = pyotp.TOTP(secret_key)
        
        if totp.verify(otp) is False:
            logout(request)
            return HttpResponseRedirect('/login')
        
        otpuser = OtpUser.objects.get(user__username=request.user.username)
        otpuser.secret_key = secret_key
        otpuser.save()
        logout(request)
        return HttpResponseRedirect('/login')

    secret_key = pyotp.random_base32()
    username = request.user.username
    key_uri = 'otpauth://totp/appname:'+username+'?secret='+secret_key+'&issuer=appname'
    qr = pyqrcode.create(key_uri)
    qr_name = secret_key+'.svg'
    qr_file = os.path.join(BASE_DIR, 'static')+'/'+qr_name
    qr.svg(qr_file)

    return render_to_response('register_device.html', {'qr_file':qr_name, 'secret_key': secret_key}, context_instance=RequestContext(request))
Esempio n. 22
0
 def gen_qr_code(self, qr_file_path):
     string = 'https://login.weixin.qq.com/l/' + self.uuid
     qr = pyqrcode.create(string)
     if self.conf['qr'] == 'png':
         qr.png(qr_file_path)
     elif self.conf['qr'] == 'tty':
         print(qr.terminal(quiet_zone=1))
Esempio n. 23
0
def generate_ticket(eventUser, lang='en_US.UTF8'):
    ticket_template = svglue.load(file=os.path.join(settings.STATIC_ROOT, 'manager/img/ticket_template_p.svg'))
    ticket_template.set_text('event_name', eventUser.event.name[:30])
    locale.setlocale(locale.LC_TIME, lang)  # Locale del request
    ticket_template.set_text('event_date', (eventUser.event.date.strftime("%A %d de %B de %Y")).decode('utf-8'))
    place = json.loads(eventUser.event.place)
    if place.get("name"):  # Si tiene nombre cargado
        ticket_template.set_text('event_place_name', place.get("name"))
        ticket_template.set_text('event_place_address', place.get("formatted_address")[:50])
    else:
        ticket_template.set_text('event_place_name', place.get("formatted_address")[:50])
        ticket_template.set_text('event_place_address', '')

    ticket_template.set_text('ticket_type', u'Entrada General')
    qr = pyqrcode.create(eventUser.id)
    code = io.BytesIO()
    qr.png(code, scale=7, quiet_zone=0)
    ticket_template.set_image('qr_code', code.getvalue(), mimetype='image/png')
    ticket_template.set_text('eventUser_PK', str(eventUser.id).zfill(12))
    ticket_template.set_text('eventUser_email', eventUser.user.email)  # No se enviara a los NonRegisteredAttendee

    userName_l1 = u"%s %s" % (eventUser.user.first_name, eventUser.user.last_name)
    userName_l2 = ''
    if (len(userName_l1) > 30):
        userName_l1 = eventUser.user.first_name[:30]  # Por si tiene mas de 30 caracteres
        userName_l2 = eventUser.user.last_name[:30]

    ticket_template.set_text('eventUser_name_l1', userName_l1)
    ticket_template.set_text('eventUser_name_l2', userName_l2)

    return str(ticket_template)
Esempio n. 24
0
async def qr(app, request):
    # Generate a QR code SVG and save it to a stream; we need at least version 8
    # for the QR code
    with io.BytesIO() as stream:
        pyqrcode.create(
            url(app['server'].configuration),
            version=8).svg(
                stream,
                background='white',
                omithw=True)

        return Response(
            status=200,
            body=stream.getvalue(),
            headers={
                'Content-Type': 'image/svg+xml'})
Esempio n. 25
0
 def save(self, **kwargs):
     """overrides the save method for the model
     """
     request = pyqrcode.create(
         '{0}.{1}'.format(str(self.uuid), self.price),
         version=10
         )
     encoded_request = request.png_as_base64_str()
     image = Image.open(
         BytesIO(base64.b64decode(encoded_request.encode()))
         )
     filename = '{0}.{1}'.format(
         str(time.time())[:10],
         (image.format).lower()
     )
     memory_image = BytesIO()
     image.save(memory_image, format=image.format)
     qr_file = InMemoryUploadedFile(
         memory_image,
         None,
         filename,
         'image/png',
         memory_image.tell,
         None
     )
     self.commodity_qr.save(
         filename,
         qr_file,
         save=False,
     )
     super(Commodity, self).save(**kwargs)
Esempio n. 26
0
 def barcode(self, data, scale=4):
     """ """
     cherrypy.response.headers['Content-Type'] = "image/png"
     buffer = StringIO.StringIO()
     code = pyqrcode.create(data)
     code.png(buffer, scale=scale)
     buffer.seek(0)
     return file_generator(buffer)
Esempio n. 27
0
    def GET(self, id):
        url = urlize('/consume/{}'.format(id))

        buf = BytesIO()
        qr = pyqrcode.create(url)
        qr.svg(buf, scale=1.5)

        return buf.getvalue()
Esempio n. 28
0
def generate_qr_code(code):

    if os.path.exists("/static/prove-it.svg"):
        os.remove("/static/prove-it.svg")

    url = pyqrcode.create('"http://lr-prove-it.herokuapp.com/checkreference/%s"' % code)
    url.svg('static/prove-it.svg', scale=4, module_color="#7D007D")
    return True
Esempio n. 29
0
def generate(data):
    data=str(data)
    code=pyqrcode.create(data)
    image="temp.png"
    code.png(image,scale=10)
    encoded = base64.b64encode(open(image, "rb").read())
    os.remove("temp.png")
    return encoded
Esempio n. 30
0
def new_qr_code():
    """Create a qr code from provided txt in url."""
    txt = request.args.get("n")
    qr = pyqrcode.create(str(txt))
    name = txt.replace(' ', '_')
    print "name => ", name
    qr.png('./pics/' + name + "_qr.png", scale="8")
    return Response(txt + " have been generated as a qr code")
Esempio n. 31
0
import pyqrcode
from pyqrcode import QRCode

site = "www.instagram.com/techhengine"
url = pyqrcode.create(site)

url.svg("techhengineqrcode.svg", scale = 8)
print("QR code generated succesfully!")



#lucciffer
Esempio n. 32
0
#! python3
import pyqrcode

ssid = "YOURSSID"
security = "WPA|WEP"
password = "******"

qr = pyqrcode.create(f'WIFI:S:{ssid};T:{security};P:{password};;')
qr.png('wificode.png',
       scale=6,
       module_color=[0, 0, 0, 128],
       background=[0xff, 0xff, 0xcc])
Esempio n. 33
0
import pyqrcode
import png
import os

print("URL/text to make into a QR Code")
text = input(": ")

print("Name your QR Code file")
name = input(": ")
full_name = name + ".png"

# Create QR code
url = pyqrcode.create(text, error='M')

#Find current user's desktop and change directory.
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
os.chdir(desktop)

#Make QR code png
url.show()
url.png(full_name, scale=6)
Esempio n. 34
0
##import pyqrcode
##import numpy as np
##import cv2

import pyqrcode
import scipy.signal as sig
import matplotlib.pyplot as plt
import numpy as np
import cv2
import time
print("Start encryption")
timstar = time.time()
#Encrpytion generating "key1"
code = pyqrcode.create("number1number2")
#read key1 and show it
code.png('code.png',
         quiet_zone=0,
         scale=10,
         module_color=[1, 1, 1, 128],
         background=[255, 255, 255, 155])
imgkey = cv2.imread("code.png")
#imgkey=cv2.medianBlur(imgkey,45)
print(np.shape(imgkey))
##imgkey22=[[[]]]
##imgkey22=np.array(imgkey22)
dimen = np.shape(imgkey)
imgkey[:, :, 0] = cv2.resize(np.tile(imgkey[:, :, 0], 5), (dimen[0], dimen[1]))
imgkey[:, :, 1] = cv2.resize(np.tile(imgkey[:, :, 1], 5), (dimen[0], dimen[1]))
imgkey[:, :, 2] = cv2.resize(np.tile(imgkey[:, :, 2], 5), (dimen[0], dimen[1]))
cv2.imshow('img', (imgkey))
Esempio n. 35
0
headers = {
    "Origin": "https://ecard.fudan.edu.cn",
    "User-Agent":
    "Mozilla/5.0 (iPhone; CPU iPhone OS 13_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Mobile/15E148 Safari/604.1",
    "Referer": "https://ecard.fudan.edu.cn"
}

data = {
    "username": "",  #UIS ID
    "password": ""  #UIS Password
}

login_url = "https://uis.fudan.edu.cn/authserver/login?service=https%3A%2F%2Fworkflow1.fudan.edu.cn%2Fsite%2Flogin%2Fcas-login%3Fredirect_url%3Dhttps%253A%252F%252Fworkflow1.fudan.edu.cn%252Fopen%252Fconnection%252Findex%253Fapp_id%253Dc5gI0Ro%2526state%253D%2526redirect_url%253Dhttps%253A%252F%252Fecard.fudan.edu.cn%252Fepay%252Fwxpage%252Ffudan%252Fzfm%252Fqrcode%253Furl%253D0"
get_qr_url = "https://ecard.fudan.edu.cn/epay/wxpage/fudan/zfm/qrcode"
s = requests.Session()
response = s.get(login_url)
content = response.text
soup = BeautifulSoup(content, "lxml")
inputs = soup.find_all("input")
for i in inputs[2::]:
    data[i.get("name")] = i.get("value")
response = s.post(login_url, data=data)

response = s.get(get_qr_url)
soup = BeautifulSoup(response.text, "lxml")
qr = soup.find_all("input", id="myText")

for i in qr:
    text = pyqrcode.create(i['value'])
    print(text.terminal())
Esempio n. 36
0
import pyqrcode
from pyzbar.pyzbar import decode
from PIL import Image

# Generate qrcode
content = input("Give the text:")
qrgennerate = pyqrcode.create(content)
qrgennerate.png("content.png", scale=8)

# scan the qrcode
qr1 = decode(Image.open("content.png"))
print(qr1[0].data.decode('ascii'))
Esempio n. 37
0
import pyqrcode
import png

data=pyqrcode.create(input("Enter the data you want to add : \n"))
data.png('code.png',scale=6)
print("QR code generated!")
def generate_qrcode(data):
    qr = pyqrcode.create(data)
    qr.png('qrcode.png' , scale=10)
Esempio n. 39
0
            x += 1
        y += 1
        x = 0

    ##work out error correction
    if matrix[length - 3][9] == 1 and matrix[length - 2][9] == 1:
        error = "L"
    if matrix[length - 3][9] == 0 and matrix[length - 2][9] == 1:
        error = "M"
    if matrix[length - 3][9] == 1 and matrix[length - 2][9] == 0:
        error = "Q"
    if matrix[length - 3][9] == 0 and matrix[length - 2][9] == 0:
        error = "H"

    ##generate qr code using text from the origional
    data = pyqrcode.create(qrtxt, error=error)
    fixedqrcode = data.text(quiet_zone=1)

    ##clean extra new line off
    fixedqrcode = fixedqrcode.strip("\n")

    ##reinitalise row/cols to 0
    x = 0
    y = 0
    for rowdata in fixedqrcode.split("\n"):
        for char in rowdata:
            if int(char) != matrix[y][x]:
                print "X: %s Y: %s" % (x, y)
                answer = "%s,%s" % (x, y)
            x += 1
        y += 1
 def returnQRCodeText(self, validURL):
     objectQRCode = pyqrcode.create(validURL)
     return objectQRCode.text()
Esempio n. 41
0
import pyqrcode

url = pyqrcode.create("www.instagram.com")
url.svg('uca-url.svg', scale=8)
print(url.terminal(quiet_zone=1))
Esempio n. 42
0
# Define routes
@app.route("/")
def audio_list():
    """Audio list route."""
    return render_template("audio_list.html",
                           files=get_files(app.config["AUDIO_FOLDER"]))


@app.route("/<path:filename>", methods=["GET"])
def audio_file(filename):
    try:
        return send_from_directory(app.config["AUDIO_FOLDER"],
                                   filename=filename,
                                   as_attachment=False)
    except FileNotFoundError:
        abort(404)


# Print server details
qrcode = pyqrcode.create(f"http://{get_ip()}:5000")
print(qrcode.terminal(quiet_zone=1))
print(
    f"Scan the QR code or go to the following address: http://{get_ip()}:5000")
print(
    "Don't forget, your computer should be on the same network as your mobile device."
)

# Make server available to other devices on the same network
# https://flask.palletsprojects.com/en/1.1.x/quickstart/#a-minimal-application
app.run(debug=False, host="0.0.0.0")
Esempio n. 43
0
 def get_qrcode_data_uri_png(self, ):
     qrcode = pyqrcode.create(self.get_url()).png_as_base64_str(scale=5)
     return "data:image/png;base64,{qrcode}".format(qrcode=qrcode)
Esempio n. 44
0
def create_qr(secret=None, name=None, filename=None):
    rstr = gen_auth_string(name, secret)
    url = pyqrcode.create(rstr)
    if filename:
        url.svg(f'{filename}.svg', scale=8)
    return url
Esempio n. 45
0
File: qr.py Progetto: Hernrup/QR-IO
def generate_qr_string(data):
    code = pyqrcode.create(data)
    return code.terminal(module_color='black', background='white')
Esempio n. 46
0
def register_clinician():
    try:
        inputs = request.get_json()
        if not inputs.get("email"):
            return (
                jsonify({
                    "success": False,
                    "error_type": "request",
                    "debugmsg": "Must include email",
                }),
                400,
            )
        exclude = [
            "id",
            "pwhash",
            "pairing_code",
            "is_paired",
            "shared_secret",
            "is_password_set",
        ]
        args = {k: inputs[k] for k in inputs.keys() if k not in exclude}

        temp_password = secrets.token_urlsafe(16)
        pairing_code = secrets.token_urlsafe(16)
        args["pwhash"] = pbkdf2_sha256.hash(temp_password)
        args["pairing_code"] = pairing_code

        qrdata = {}
        qrdata["username"] = inputs.get("username")
        qrdata["password"] = temp_password
        qrdata["pairing_code"] = pairing_code
        qrdata["backend_domain"] = app.config.get("BACKEND_DOMAIN")
        qrdata["backend_id"] = app.config.get("BACKEND_ID")

        qrstring = json.dumps(qrdata)

        # TODO Convert qrstring to PNG/SVG qrcode and send in email
        qrcode = pyqrcode.create(json.dumps(qrstring))
        buffer = io.BytesIO()
        qrcode.png(buffer, scale=6)

        add_result = ext.add_user_("clinicians", args)
        if not add_result[1]:
            return add_result[0]

            # TODO CHANGE TO SMTP SERVER FROM CONFIG
            # GMAIL FOR TESTING ONLY
        config_smtp = app.config.get("SMTP_SERVER")
        # print(config_smtp)
        server = smtplib.SMTP(config_smtp, 587)
        server.ehlo()
        server.starttls()
        server.login(app.config.get("EMAIL_USER"),
                     app.config.get("EMAIL_PASSWORD"))

        # TODO Tidy up and move to resources
        msg = MIMEMultipart("alternative")
        msg["Subject"] = "Codestroke Registration"
        msg["From"] = app.config.get("EMAIL_USER")
        msg["To"] = inputs.get("email")
        contents = """\
		<html>
			<head></head>
				<body>
				<p>Hi!<br>
				<br>
				You've been registered for Codestroke.<br>
				<br>
				The registration process is almost complete! Please scan the QR code attached with your phone to complete the registration process.
				<br>
				<br>
				Codestroke Team
				</p>
			</body>
		</html>
		"""
        html = MIMEText(contents, "html")
        msg.attach(html)
        # print(buffer.getvalue())
        image = MIMEImage(buffer.getvalue(), name="QR", _subtype="png")
        msg.attach(image)

        server.sendmail(app.config.get("EMAIL_USER"), inputs.get("email"),
                        msg.as_string())
        server.close()
        return jsonify({"success": True, "destination": inputs.get("email")})
    except Exception as e:
        return (
            jsonify({
                "success": False,
                "debug_py_err": str(e),
                "e_args": str(e.args)
            }),
            500,
        )
Esempio n. 47
0
def onConnected(interface):
    """Callback invoked when we connect to a radio"""
    global args
    print("Connected to radio")
    closeNow = False  # Should we drop the connection after we finish?
    try:
        if args.settime:
            print("Setting device RTC time")
            # can include lat/long/alt etc: latitude = 37.5, longitude = -122.1
            interface.sendPosition()

        if args.setowner:
            print(f"Setting device owner to {args.setowner}")
            interface.setOwner(args.setowner)

        if args.sendtext:
            print(f"Sending text message {args.sendtext} to {args.dest}")
            interface.sendText(args.sendtext,
                               args.dest,
                               wantAck=True,
                               wantResponse=True)

        if args.set or args.setstr or args.setchan or args.seturl or args.router != None:
            closeNow = True

            def setPref(attributes, name, val):
                """Set a preferences value"""
                print(f"Setting {name} to {val}")
                try:
                    try:
                        setattr(attributes, name, val)
                    except TypeError as ex:
                        # The setter didn't like our arg type - try again as a byte array (so we can convert strings to bytearray)
                        if isinstance(val, str):
                            setattr(attributes, name,
                                    codecs.decode(val, "hex"))
                        else:
                            print(f"Incorrect type for {name} {ex}")
                except Exception as ex:
                    print(f"Can't set {name} due to {ex}")

            if args.router != None:
                setRouter(interface, args.router)

            # Handle the int/float/bool arguments
            for pref in (args.set or []):
                setPref(interface.radioConfig.preferences, pref[0],
                        fromStr(pref[1]))

            # Handle the string arguments
            for pref in (args.setstr or []):
                setPref(interface.radioConfig.preferences, pref[0], pref[1])

            # Handle the channel settings
            for pref in (args.setchan or []):
                setPref(interface.radioConfig.channel_settings, pref[0],
                        fromStr(pref[1]))

            # Handle set URL
            if args.seturl:
                interface.setURL(args.seturl, False)

            print("Writing modified preferences to device")
            interface.writeConfig()

        if args.info:
            closeNow = True
            print(interface.myInfo)
            print(interface.radioConfig)
            print(f"Channel URL {interface.channelURL}")
            print("Nodes in mesh:")
            for n in interface.nodes.values():
                print(n)

        if args.qr:
            closeNow = True
            print(f"Channel URL {interface.channelURL}")
            url = pyqrcode.create(interface.channelURL)
            print(url.terminal())
    except Exception as ex:
        print(ex)

    # if the user didn't ask for serial debugging output, we might want to exit after we've done our operation
    if (not args.seriallog) and closeNow:
        interface.close()  # after running command then exit
Esempio n. 48
0
import pyqrcode

url = pyqrcode.create("www.google.com")
url.svg('uca-url.svg', scale=8)
print(url.terminal(quiet_zone=1))
Esempio n. 49
0
#!/usr/bin/pyhton3

import pyqrcode
from pyqrcode import QRCode

qcode = [
    "www.linkedin.com/in/harsh-mangal-1108",
    "https://www.instagram.com/_harsh_mangal_/"
]
for i in range(len(qcode)):

    url = pyqrcode.create(qcode[i])
    url.svg("qcode" + str(i) + ".svg", scale=8)
Esempio n. 50
0
def create_qr(link):
    url = pyqrcode.create(link)
    url.svg('uca-url.svg', scale=8)
    print(url.terminal(quiet_zone=1))
    print('QR code stored in local directory! ')
Esempio n. 51
0
import pyqrcode
url = pyqrcode.create('https://www.azhar.eg/splash.html')
url.svg('uca-url.svg', scale=8)
print(url.terminal(quiet_zone=1))
Esempio n. 52
0
def clicked():
    res = ""+txt.get()
    url=pyqrcode.create(res)
    url.svg('qr.svg',scale=8)
    res="QR code created successfully for :-"+res
    lbl.configure(text=res)
Esempio n. 53
0
import pyqrcode
for i in range(300):
    code = pyqrcode.create(f'{i}', error='H')
    code.png(f'codes/{i}.png', scale=6)
Esempio n. 54
0
def main():
    print("Command Line Wallet - BitcoinLib %s\n" % BITCOINLIB_VERSION)
    # --- Parse commandline arguments ---
    args = parse_args()

    db_uri = args.database

    if args.generate_key:
        passphrase = get_passphrase(args)
        passphrase = ' '.join(passphrase)
        seed = Mnemonic().to_seed(passphrase).hex()
        hdkey = HDKey.from_seed(seed, network=args.network)
        print(
            "Private Master key, to create multisig wallet on this machine:\n%s"
            % hdkey.wif_private())
        print(
            "Public Master key, to share with other cosigner multisig wallets:\n%s"
            % hdkey.public_master(witness_type=args.witness_type,
                                  multisig=True).wif())
        print("Network: %s" % hdkey.network.name)
        clw_exit()

    # List wallets, then exit
    if args.list_wallets:
        print("BitcoinLib wallets:")
        for w in wallets_list(db_uri=db_uri):
            if 'parent_id' in w and w['parent_id']:
                continue
            print("[%d] %s (%s) %s" %
                  (w['id'], w['name'], w['network'], w['owner']))
        clw_exit()

    # Delete specified wallet, then exit
    if args.wallet_remove:
        if not wallet_exists(args.wallet_name, db_uri=db_uri):
            clw_exit("Wallet '%s' not found" % args.wallet_name)
        inp = input(
            "\nWallet '%s' with all keys and will be removed, without private key it cannot be restored."
            "\nPlease retype exact name of wallet to proceed: " %
            args.wallet_name)
        if inp == args.wallet_name:
            if wallet_delete(args.wallet_name, force=True, db_uri=db_uri):
                clw_exit("\nWallet %s has been removed" % args.wallet_name)
            else:
                clw_exit("\nError when deleting wallet")
        else:
            clw_exit("\nSpecified wallet name incorrect")

    wlt = None
    if args.wallet_name and not args.wallet_name.isdigit(
    ) and not wallet_exists(args.wallet_name, db_uri=db_uri):
        if not args.create_from_key and input(
                "Wallet %s does not exist, create new wallet [yN]? " %
                args.wallet_name).lower() != 'y':
            clw_exit('Aborted')
        wlt = create_wallet(args.wallet_name, args, db_uri)
        args.wallet_info = True
    else:
        try:
            wlt = Wallet(args.wallet_name, db_uri=db_uri)
            if args.passphrase is not None:
                print(
                    "WARNING: Using passphrase option for existing wallet ignored"
                )
            if args.create_from_key is not None:
                print(
                    "WARNING: Using create_from_key option for existing wallet ignored"
                )
        except WalletError as e:
            clw_exit("Error: %s" % e.msg)

    if wlt is None:
        clw_exit("Could not open wallet %s" % args.wallet_name)

    if args.import_private:
        if wlt.import_key(args.import_private):
            clw_exit("Private key imported")
        else:
            clw_exit("Failed to import key")

    if args.wallet_recreate:
        wallet_empty(args.wallet_name)
        print("Removed transactions and generated keys from this wallet")
    if args.update_utxos:
        wlt.utxos_update()
    if args.update_transactions:
        wlt.scan(scan_gap_limit=5)

    if args.export_private:
        if wlt.scheme == 'multisig':
            for w in wlt.cosigner:
                if w.main_key and w.main_key.is_private:
                    print(w.main_key.wif)
        elif not wlt.main_key or not wlt.main_key.is_private:
            print("No private key available for this wallet")
        else:
            print(wlt.main_key.wif)
        clw_exit()

    if args.network is None:
        args.network = wlt.network.name

    tx_import = None
    if args.import_tx_file:
        try:
            fn = args.import_tx_file
            f = open(fn, "r")
        except FileNotFoundError:
            clw_exit("File %s not found" % args.import_tx_file)
        try:
            tx_import = ast.literal_eval(f.read())
        except (ValueError, SyntaxError):
            tx_import = f.read()
    if args.import_tx:
        try:
            tx_import = ast.literal_eval(args.import_tx)
        except (ValueError, SyntaxError):
            tx_import = args.import_tx
    if tx_import:
        if isinstance(tx_import, dict):
            wt = wlt.transaction_import(tx_import)
        else:
            wt = wlt.transaction_import_raw(tx_import, network=args.network)
        wt.sign()
        if args.push:
            res = wt.send()
            if res:
                print("Transaction pushed to network. Transaction ID: %s" %
                      wt.txid)
            else:
                print("Error creating transaction: %s" % wt.error)
        wt.info()
        print("Signed transaction:")
        print_transaction(wt)
        clw_exit()

    if args.receive:
        cosigner_id = args.receive
        if args.receive == -1:
            cosigner_id = None
        key = wlt.get_key(network=args.network, cosigner_id=cosigner_id)
        print("Receive address: %s" % key.address)
        if QRCODES_AVAILABLE:
            qrcode = pyqrcode.create(key.address)
            print(qrcode.terminal())
        else:
            print(
                "Install qr code module to show QR codes: pip install pyqrcode"
            )
        clw_exit()
    if args.create_transaction == []:
        clw_exit("Missing arguments for --create-transaction/-t option")
    if args.create_transaction:
        if args.fee_per_kb:
            clw_exit("Fee-per-kb option not allowed with --create-transaction")
        try:
            wt = create_transaction(wlt, args.create_transaction, args)
        except WalletError as e:
            clw_exit("Cannot create transaction: %s" % e.msg)
        wt.sign()
        print("Transaction created")
        wt.info()
        if args.push:
            wt.send()
            if wt.pushed:
                print("Transaction pushed to network. Transaction ID: %s" %
                      wt.txid)
            else:
                print("Error creating transaction: %s" % wt.error)
        else:
            print(
                "\nTransaction created but not sent yet. Transaction dictionary for export: "
            )
            print_transaction(wt)
        clw_exit()
    if args.sweep:
        if args.fee:
            clw_exit("Fee option not allowed with --sweep")
        offline = True
        print("Sweep wallet. Send all funds to %s" % args.sweep)
        if args.push:
            offline = False
        wt = wlt.sweep(args.sweep,
                       offline=offline,
                       network=args.network,
                       fee_per_kb=args.fee_per_kb)
        if not wt:
            clw_exit(
                "Error occurred when sweeping wallet: %s. Are UTXO's available and updated?"
                % wt)
        wt.info()
        if args.push:
            if wt.pushed:
                print("Transaction pushed to network. Transaction ID: %s" %
                      wt.txid)
            elif not wt:
                print("Cannot sweep wallet, are UTXO's updated and available?")
            else:
                print("Error sweeping wallet: %s" % wt.error)
        else:
            print(
                "\nTransaction created but not sent yet. Transaction dictionary for export: "
            )
            print_transaction(wt)
        clw_exit()

    # print("Updating wallet")
    if args.network == 'bitcoinlib_test':
        wlt.utxos_update()
    print("Wallet info for %s" % wlt.name)
    wlt.info()
Esempio n. 55
0
def encode_qr(data: str, filepath='encrypted.png'):
    return pyqrcode.create(data).png(filepath)
Esempio n. 56
0
#!/usr/bin/python3
import pyqrcode
import random
import string
import sys


def gen_rand_string(length=32):
    charset = list(string.printable[:62])
    random.shuffle(charset)
    return ''.join(charset)[:length]


flag = 'shellmates{4lR1g|-|t_@lriGh7_1_tH1nK_y0u`R3_f4st_en0ugh}'
rand_string = gen_rand_string()
qr_code = pyqrcode.create(rand_string).terminal()

sys.stdout.write(
    "Hello there Soldier! Let's see how fast you are, you got only 1 second!")
sys.stdout.write(qr_code)
sys.stdout.write('Decoded string: ')
sys.stdout.flush()

if sys.stdin.readline().strip() == rand_string:
    sys.stdout.write('[+] Congratulations! Here is your flag: {}'.format(flag))
else:
    sys.stdout.write('[-] Wrong!')

sys.stdout.flush()
Esempio n. 57
0
from PIL import Image
from pyzbar.pyzbar import decode
import pyqrcode

# To create QR Code
qr = pyqrcode.create('http://127.0.0.1:8000/')
qr.png('greet.png', scale=10)

# To read QR Code
d = decode(Image.open('greet.png'))
print(d[0].data.decode('ascii'))
Esempio n. 58
0
#!/usr/bin/env python3

import pyotp
import pyqrcode
import json
import base64
import sys

file_json = "response.json"

with open('response.json', "r") as f:
    response = json.loads(f.read())['response']

with open('duotoken.hotp', "r") as f:
    counter = int(f.readlines()[1])

label = response['customer_name']
issuer = 'Duo'
# base32 encoded hotp secret, with the padding ("=") stripped.
secret = base64.b32encode(bytes(response['hotp_secret'],
                                'utf-8')).decode('utf-8').replace('=', '')
qrdata = 'otpauth://hotp/{label}?secret={secret}&issuer={issuer}&counter={counter}'.format(
    label=label, secret=secret, issuer=issuer, counter=counter)
qrcode = pyqrcode.create(qrdata)
print(qrcode.terminal(quiet_zone=1))
print(qrdata)
def generate_qr_code(data):
    return pyqrcode.create(data)
Esempio n. 60
0
import pyqrcode
import png
from pyqrcode import QRCode

QRcreate = "https://www.instagram.com/__beginnerscode__/"

url = pyqrcode.create(QRcreate)
url.png('Desktop/qr.png', scale=8)