Base64 to string of 1s and 0s convertor - python

I did some search for this question, but I can not find relevant answer. I am trying to convert some string form input() function to Base64 and from Base64 to raw string of 1s and 0s. My converter is working, but its output are not the raw bits, but something like this: b'YWhvag=='.
Unfortunately, I need string of 1s and 0s, because I want to send this data via "flickering" of LED.
Can you help me figure it out please? Thank you for any kind of help!
import base64
some_text = input()
base64_string = (base64.b64encode(some_text.encode("ascii")))
print(base64_string)

If I have understood it corretly you want binary equivalent of string like 'hello' to ['1101000', '1100101', '1101100', '1101100', '1101111'] each for h e l l o
import base64
some_text = input('enter a string to be encoded(8 bit encoding): ')
def encode(text):
base64_string = (base64.b64encode(text.encode("ascii")))
return ''.join([bin(i)[2:].zfill(8) for i in base64_string])
def decode(binary_digit):
b = str(binary_digit)
c = ['0b'+b[i:i+8] for i in range(0,len(b), 8)]
c = ''.join([chr(eval(i)) for i in c])
return base64.b64decode(c).decode('ascii')
encoded_value = encode(some_text)
decoded_value = decode(encoded_value)
print(f'encoded value of {some_text} in 8 bit encoding is: {encoded_value}')
print(f'decoded value of {encoded_value} is: {decoded_value}')

Related

Converting user input into hex, joined with NULL?

I need to convert user input to Hex, but with NULL characters between each character.
Eg:
User input = 111
Output = b'3100310031
My best attempt looks like this, but it's nowhere near...
import binascii
content5 = rb"111"
print(content5)
joiner = "00"
content4 = binascii.hexlify(content5)
print(content4)
content3 = joiner.join(str(content4))
print(content3)
content2 = bytes(content3, 'utf-8')
print(content2)
content = binascii.hexlify(content2)
print(content)
But this returns:
b'111'
b'313131'
b00'00300100300100300100'
b"b00'00300100300100300100'"
b'62303027303033303031303033303031303033303031303027'
b'3632333033303237333033303333333033303331333033303333333033303331333033303333333033303331333033303237'
Any help would be greatly appreciated! 😁
Hexlify change every byte if the input byte string to its (2 bytes) hexa representation. Just process one byte at a time and join the result:
import binascii
content5 = rb"111"
print(content5)
joiner = "00"
content4 = joiner.encode().join(binascii.hexlify(bytes((i,))) for i in content5)
print(content4)
It gives as expected:
b'111'
b'3100310031'

How to convert Binary to Strings?

I am currently working on a binary encryption code: [Sender(Msg Input=> Binary Conversion)] : [Receiver (Binary Conversion => Msg Output)]
As of now I am able to convert text based Msgs , e.g) How are you? etc.
print("Enter Msg:")
def Binary_Encryption(message):
message = ''.join(format(i, 'b') for i in bytearray(message, encoding ='utf-8'))
print(message)
Binary_Encryption(input("").replace (" ","\\"))
Output: 10010001101111111011110111001100001111001011001011011100111100111011111110101111111
After the binary string is obtained, by just copying the string and placing it within this block of code will decrypt it.
def Binary_Decryption(binary):
string = int(binary, 2)
return string
bin_data = (input("Enter Binary:\n"))
str_data =''
for i in range(0, len(bin_data), 7):
temp_data = bin_data[i:i + 7]
decimal_data = Binary_Decryption(temp_data)
str_data = str_data + chr(decimal_data)
print("Decrypted Text:\n"+str_data.replace("\\"," "))
Output: How are you?
But I am not able to convert a certain inputs , e.g) ?? , 8879 , Oh! How are You? etc.
basically the msgs that are not being converted are Msgs with multiple uses of numbers or special
characters.
Msg Input for ?? gives "⌂▼" and 8879 gives "qc?☺" while Oh! How are You? gives "OhC9◄_o9CeK93_k▼
I think the problem is that the special characters (!, ?) contains only 6 bits, while the other characters 7.This messes things up if there are other characters behind the special one I think. Maybe something like this should work. There is probably a better way to solve this though.
def Binary_Encryption(message):
s = ""
for i in bytearray(message, encoding="utf-8"):
c = format(i, "b")
addon = 7 - len(c)
c = addon * "0" + c # prepend 0 if len shorter than 7
s += c # Add to string
print(s)
Your problem is that you are copying the output from binary_encrypt directly which truncate leading zeros so 8 instead of being 00111000 it became 111000 which result in 2 bits being used from next ASCII binary character since ASCII characters are represented as 8-bits values to print number 8897 use0011100000111000001110010011011100001010 as input to binary_decrypt. look for ASCII table to see the binary equivalents for each character.Just edit your code like this.
print("Enter Msg:")
def Binary_Encryption(message):
# pass 08b to format
message = ''.join(format(i, '08b') for i in bytearray(message, encoding ='utf-8'))
print(message)
Binary_Encryption(input("").replace (" ","\\"))

Python Print Hex variable

I have hex variable that I want to print as hex
data = '\x99\x02'
print (data)
Result is: ™
I want to the python to print 0x9902
Thank you for your help
Please check this one.
data = r'\x99\x02'
a, b = [ x for x in data.split(r'\x') if x]
d = int(a+b, base=16)
print('%#x'%d)
You have to convert every char to its number - ord(char) - and convert every number to hex value - '{:02x}'.format() - and concatenate these values to string. And add string '0x'.
data = '\x99\x02'
print('0x' + ''.join('{:02x}'.format(ord(char)) for char in data))
EDIT: The same but first string is converted to bytes using encode('raw_unicode_escape')
data = '\x99\x02'
print('0x' + ''.join('{:02x}'.format(code) for code in data.encode('raw_unicode_escape')))
and if you have already bytes then you don't have to encode()
data = b'\x99\x02'
print('0x' + ''.join('{:02x}'.format(code) for code in data))
BTW: Similar way you can convert to binary using {:08b}
data = '\x99\x02'
print(''.join('{:08b}'.format(code) for code in data.encode('raw_unicode_escape')))

translate a string message into a set of numbers python

I implemented a RSA algorithm on python. But I have a problem with the fact that you need to present any message in numerical form (a set of digits) in order to raise to a power. The difficulty is that if you do this with the ascii, how do you know how many digits are in the ascii code of the character 1, 2 or 3, for the unambiguous decode. Are there other options?
def decodeMessage(self, encodedMessage):
decodedBlocks = []
for block in encodedMessage:
decoded = self.mod_exp(block, self.e, self.N)
decodedBlocks.append(decoded)
return decodedBlocks
Found a solution in binascii, which gives me the conversion of a string into a set of numbers.
message = message.strip()
b = message.encode('utf-8')
hex_data = binascii.hexlify(b)
cipher = int(hex_data, 16)
after all the manipulations I convert back:
h2 = hex(result)[2:]
b2 = h2.encode('ascii')
b3 = binascii.unhexlify(b2)
answer = b3.decode('utf-8')

How to convert a word in string to binary

I was working on a module(the import module stuff) which would help to convert words in string to hex and binary(And octal if possible).I finished the hex part.But now I am struggling in case of the binary.I don't know where to start from or what to do.What I want to do is simple.It would take an input string such as 'test'.The function inside the module would convert it to binary.
What I have done till now is given below:
def string_hex(string): # Converts a word to hex
keyword = string.encode()
import binascii
hexadecimal=str(binascii.hexlify(keyword), 'ascii')
formatted_hex=':'.join(hexadecimal[i:i+2] for i in range(0, len(hexadecimal), 2))
return formatted_hex
def hex_string(hexa):
# hexa(Given this name because there is a built-in function hex()) should be written as string.For accuracy on words avoid symbols(, . !)
string = bytes.fromhex(hexa)
formatted_string = string.decode()
return formatted_string
I saved in the directory where I have installed my python in the name experiment.py.This is the way I call it.
>>> from experiment import string_hex
>>> string_hex('test')
'74:65:73:74'
Just like that I am able to convert it back also like this:
>>> from experiment import hex_string
>>> hex_string('74657374')
'test'
Just like this wanted to convert words in strings to binary.And one more thing I am using python 3.4.2.Please help me.
You can do it as follows. You don't even have to import binascii.
def string_hex(string):
return ':'.join(format(ord(c), 'x') for c in string)
def hex_string(hexa):
hexgen = (hexa[i:i+2] for i in range(0, len(hexa), 2))
return ''.join(chr(eval('0x'+n)) for n in hexgen)
def string_bin(string):
return ':'.join(format(ord(c), 'b') for c in string)
def bin_string(binary):
bingen = (binary[i:i+7] for i in range(0, len(binary), 7))
return ''.join(chr(eval('0b'+n)) for n in bingen)
And here is the output:
>>> string_hex('test')
'74:65:73:74'
>>> hex_string('74657374')
'test'
>>> string_bin('test')
'1110100:1100101:1110011:1110100'
>>> bin_string('1110100110010111100111110100')
'test'

Categories

Resources