TypeError: ord() expected string of length 1, but int found, Traceback (most recent call last): - python-3.x

I am getting an error while encrypting a file.
C:\Users\username>python xor_encryptor.py raw.txt > new.txt
Traceback (most recent call last):
File "C:\Users\username\xor_encryptor.py", line 19, in <module>
ciphertext = xor(plaintext, KEY)
File "C:\Users\username\xor_encryptor.py", line 10, in xor
output_str += chr(ord(current) ^ ord(current_key))
TypeError: ord() expected string of length 1, but int found
The xor_encryptor script is:
import sys
KEY = "x"
def xor(data, key):
key = str(key)
l = len(key)
output_str = ""
for i in range(len(data)):
current = data[i]
current_key = key[i % len(key)]
output_str += chr(ord(current) ^ ord(current_key))
return output_str
def printCiphertext(ciphertext):
print('{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in ciphertext) + ' };')
try:
plaintext = open(sys.argv[1], "rb").read()
except:
print("File argument needed! %s " % sys.argv[0])
sys.exit()
ciphertext = xor(plaintext, KEY)
print('{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in ciphertext) + ' };')
Kindly give an appropriate solution.

Related

struct.error: unpack requires a buffer of 2 bytes - file problem

script tells me that unpack requires a buffer of 2 bytes.
maybe someone finds that error.
Thats a script to read a file with hex adresses and compare it with clear text file.
But everytime i get this struct.error
Traceback (most recent call last):
File "/home/starshield/deye/test.py", line 290, in <module>
params.parse(raw_msg, start, end - start + 1)
File "/home/starshield/deye/test.py", line 30, in parse
self.parsers[j['rule']](rawdata, j, start, length)
File "/home/starshield/deye/test.py", line 96, in try_parse_unsigned
temp = struct.unpack('>H', rawData[offset:offset + 2])[0]
struct.error: unpack requires a buffer of 2 bytes
code line 27 to 34:
def parse(self, rawdata, start, length):
for i in self._lookups['parameters']:
for j in i['items']:
self.parsers[j['rule']](rawdata, j, start, length)
return
def get_result(self):
return self.result
code line 91 to 101
for r in definition['registers']:
index = r - start # get the decimal value of the register'
# print("Reg: %s, index: %s" % (r, index))
if (index >= 0) and (index < length):
offset = OFFSET_PARAMS + (index * 2)
temp = struct.unpack('>H', rawData[offset:offset + 2])[0]
value += (temp & 0xFFFF) << shift
shift += 16
else:
found = False
if found:
The last block is from 292 to 299
for i in range(start, end):
value = getRegister(raw_msg, i)
name = "Unknown"
for paramters in parameter_definition["parameters"]:
for item in paramters["items"]:
for reg in item["registers"]:
if reg == i:
name = item["name"]
not able to find the error

'map' object is not subscriptable

I am trying to execute the codes from this link
https://zulko.github.io/blog/2014/06/21/some-more-videogreping-with-python/
import re # module for regular expressions
def convert_time(timestring):
""" Converts a string into seconds """
nums = map(float, re.findall(r'\d+', timestring))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
with open("Identity_2003.srt") as f:
lines = f.readlines()
times_texts = []
current_times , current_text = None, ""
for line in lines:
times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)
if times != []:
current_times = map(convert_time, times)
elif line == '\n':
times_texts.append((current_times, current_text))
current_times, current_text = None, ""
elif current_times is not None:
current_text = current_text + line.replace("\n"," ")
print (times_texts)
from collections import Counter
whole_text = " ".join([text for (time, text) in times_texts])
all_words = re.findall("\w+", whole_text)
counter = Counter([w.lower() for w in all_words if len(w)>5])
print (counter.most_common(10))
cuts = [times for (times,text) in times_texts
if (re.findall("please",text) != [])]
from moviepy.editor import VideoFileClip, concatenate
video = VideoFileClip("Identity_2003.mp4")
def assemble_cuts(cuts, outputfile):
""" Concatenate cuts and generate a video file. """
final = concatenate([video.subclip(start, end)
for (start,end) in cuts])
final.to_videofile(outputfile)
assemble_cuts(cuts, "please.mp4")
But the assemble_cuts function is not working . I am using python3.x
it is giving me an error
Traceback (most recent call last):
File "<ipython-input-64-939ee3d73a4a>", line 47, in <module>
assemble_cuts(cuts, "please.mp4")
File "<ipython-input-64-939ee3d73a4a>", line 44, in assemble_cuts
for (start,end) in cuts])
File "<ipython-input-64-939ee3d73a4a>", line 43, in <listcomp>
final = concatenate([video.subclip(start, end)
File "<ipython-input-64-939ee3d73a4a>", line 6, in convert_time
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
TypeError: 'map' object is not subscriptable
Could you help me to solve this problem?
Fixed it.
def convert_time(timestring):
""" Converts a string into seconds """
nums = list(map(float, re.findall(r'\d+', timestring)))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000

TypeError: can't concat bytes to str in Python 3.5.1

I'm getting an error even after setting base64 encoding:
Traceback (most recent call last):
File "api_tufin_5.py", line 41, in <module>
main(sys.argv[1:])
File "api_tufin_5.py", line 28, in main
headers['Authorization'] = 'Basic ' + base64.b64encode(user + ':' +
password)
TypeError: can't concat bytes to str
This is my code:
import requests, sys, base64, collections, json
# global vars
server_ip = 'url'
headers = {}
user = b'username'
password = b'password'
debug = False
def http_get(url, headers=headers):
try:
r = requests.get(url=url, headers=headers, verify=False)
except requests.exceptions.RequestException as e:
print >> sys.stderr, e
return
if debug:
print (r.text)
http_result = collections.namedtuple('HTTP_Result', ['status',
'text'])
return http_result(r.status_code, r.text)
def main(argv):
headers['Accept'] = 'application/json'
headers['Authorization'] = 'Basic ' + base64.b64encode(user + ':' +
password)
r = http_get('url/securechangeworkflow/api/securechange/tickets?
status=In Progress&count=10&start=1&expand_links=false')
if r.status != 200:
print >> sys.stderr, "Failed to get devices"
print >> sys.stderr, "Status: ", r.status
return -1
print (r.text)
if __name__ =='__main__':
main(sys.argv[1:])
Why would it still show an error when base64 has been encoded? What would cause it to not concat bytes to str? Use of the + should be able to merge two strings into a single object.

String interpreted as a bool?

I'm trying to find the length of a password before going on with my program but python keeps telling me that I'm instead trying to compute the length of a bool:
input_name = input('\nWe need you name: ')
if input_name in members:
while True:
input_pass = input('Input your password: ')
if len(input_pass == 0):
print("Can't be null!")
continue
else: break
else:
print('Sorry, your not part of the League.')
bin_1 = input('Would you like to join?')
Traceback:
Traceback (most recent call last):
File "hoteltranselvania.py", line 25, in <module>
if len(input_pass == 0):
TypeError: object of type 'bool' has no len()

Python 3 Bottle on RPi invalid literal for int() with base 10: 'favicon.ico'

I recently got a raspberry pi and a book to go along with it(Raspberry Pi Cookbook). One of the projects is controlling the GPIO pins on the RPi via a webpage. When I first ran the code after typing it out, I received a bunch of errors so, I tried running the code listed on the books github page:
from bottle import route, run
import RPi.GPIO as GPIO
host = '192.168.1.8'
GPIO.setmode(GPIO.BCM)
led_pins = [18, 23, 24]
led_states = [0, 0, 0]
switch_pin = 25
GPIO.setup(led_pins[0], GPIO.OUT)
GPIO.setup(led_pins[1], GPIO.OUT)
GPIO.setup(led_pins[2], GPIO.OUT)
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def switch_status():
state = GPIO.input(switch_pin)
if state:
return 'Up'
else:
return 'Down'
def html_for_led(led):
l = str(led)
result = " <input type='button' onClick='changed(" + l + ")' value='LED " + l + "'/>"
return result
def update_leds():
for i, value in enumerate(led_states):
GPIO.output(led_pins[i], value)
#route('/')
#route('/<led>')
def index(led="n"):
print(led)
if led != "n":
led_num = int(led)
led_states[led_num] = not led_states[led_num]
update_leds()
response = "<script>"
response += "function changed(led)"
response += "{"
response += " window.location.href='/' + led"
response += "}"
response += "</script>"
response += '<h1>GPIO Control</h1>'
response += '<h2>Button=' + switch_status() + '</h2>'
response += '<h2>LEDs</h2>'
response += html_for_led(0)
response += html_for_led(1)
response += html_for_led(2)
return response
run(host=host, port=80)
When I run the code(sudo python web_control.py) I get a invalid literal for int() with base 10: 'favicon.ico' error. Here is the traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 744, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1480, in wrapper
rv = callback(*a, **ka)
File "web_control.py", line 42, in index
response += " window.location.href='/' + led"
UnboundLocalError: local variable 'response' referenced before assignment
192.168.0.108 - - [29/Dec/2014 21:31:46] "GET / HTTP/1.1" 500 740
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 744, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1480, in wrapper
rv = callback(*a, **ka)
File "web_control.py", line 36, in index
led_num = int(led)ValueError: invalid literal for int() with base 10: 'favicon.ico'
Any idea what is going on here? Any help is greatly appreciated.
what does your
print led
show ?
they say that led is not an int so the error could be from there

Resources