translate a string message into a set of numbers python - 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')

Related

Converting text to a binary string gives a different binary string than what was used to make the text

I am creating a simple XOR program in python. The user inputs simple plaintext which is converted to a string of bits. A key is generated of equal length to the plaintext bits, and it is XOR'd. I convert the XOR'd bits back to text and write it as ciphertext. This all works perfectly without issues.
The issue I am having is I want to take that same ciphertext and convert it back to its binary form in preparation for decryption. When I do so, I get a completely different string of bits.
Reproducible example:
import secrets
import sys
def encrypt(plaintext):
binary_plaintext = [format(x, 'b').zfill(8) for x in bytearray(plaintext, 'utf-8')] # Convert Plaintext to Binary and separates into bytes in a list
binary_plaintext = "".join(binary_plaintext) # Take list of bytes and join together in one long binary string
key = key_generator(binary_plaintext) # Create key of 'n' bits where n == len(binary_plaintext)
ciphertext_binary_string = "".join([str(int(bit1, 2) ^ int(bit2, 2)) for bit1, bit2 in zip(binary_plaintext, key[0])]) # XOR Operation with Key and Plaintext
ciphertext_binary_bytes = " ".join([ciphertext_binary_string[idex:idex+8] for idex in range(0, len(ciphertext_binary_string), 8)]) # Split the Ciphertext into bytes
ciphertext = ''.join([chr(int(byte,2)) for byte in ciphertext_binary_bytes.split(" ")]) # Convert Ciphertext to text i.e. ~ýÄÞ$~Ý
decrypt(ciphertext, key[0], ciphertext_binary_string) # Pass the exact same ciphertext to the decryption
def decrypt(ciphertext, key, previous_ciphertext):
ciphertext_binary = bin(int.from_bytes(ciphertext.encode('utf-8'), sys.byteorder))
print(f"{ciphertext_binary[2:]} does not match {previous_ciphertext}")
def key_generator(binary_plaintext):
integer_key = secrets.randbits(len(binary_plaintext)) # Build a random key that is the same length as the plaintext
binary_key = bin(integer_key)[2:].zfill(len(binary_plaintext))
return binary_key, integer_key
encrypt("Hello There")
Essentially there is:
Ciphertext in the form of bits on line 10
Convert this Ciphertext to text on line 12
Pass this same Ciphertext to decryption()
Convert the same Ciphertext back to it's binary format (as we have on line 10) on line 17 text back to bits on line 17.
Line 10 and line 17 do not match. This is what I am trying to understand. Binary > Text > Binary but the two binary forms do not match.
Any insight is appreciated. Thanks

Base64 to string of 1s and 0s convertor

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}')

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 (" ","\\"))

Rijndael Padding in Python

I know where the problem is but I don't know how to fix it. The problem is with the padding. I have absolutely no idea about it and how it works. I tried searching online but nothing seemed to help. I am trying to implement this function to work with my website. The python encrypts and sends the data and PHP decrypts it.
Here's the actual code of my python:
from rijndael.cipher.crypt import new
from rijndael.cipher.blockcipher import MODE_CBC
import base64
PADDING = b'.'
def r_pad(payload, block_size=32):
return payload + (block_size - len(payload) % block_size) * PADDING
KEY = 'lkirwf897+22#bbtrm8814z5qq=498j5'
IV = '741952hheeyy66#cs!9hjv887mxx7#8y'
plain_text = "A padded string to BLOCKSIZE length."
rjn = new(KEY, MODE_CBC, IV, blocksize=32)
encd = rjn.encrypt(r_pad(plain_text))
data = base64.b64encode(encd)
print(data)
rjn = new(KEY, MODE_CBC, IV, blocksize=32)
data = base64.b64decode(data)
decd = rjn.decrypt(r_pad(data))
print (decd)
This is the output:
Dv0Y/AFXdFMlDrcldFCu8v5o9zAlLNgyM+vO+PFeSrqWdzP1S1cumviFiEjNAjz5njnMMC9lfxsBl71x5y+xCw==
A padded string to BLOCKSIZE length.............................Å¿:è°⌐┘n┤«╞Px╜:æC┬♣╬Q┤▼«U_♦â☻ìr
I need the output of the encrypted string to be something like this:
Dv0Y/AFXdFMlDrcldFCu8v5o9zAlLNgyM+vO+PFeSrpO8Ve82mdUcc4rkzp9afDYc75NmkSd4mdflt38kceOdA==
A padded string to BLOCKSIZE length
I tried to make RIJNDAEL256 function out of this code:
EncryptRJ256("lkirwf897+22#bbtrm8814z5qq=498j5", "741952hheeyy66#cs!9hjv887mxx7#8y", "A padded string to BLOCKSIZE length.")
Public Function EncryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_encrypt As String) As String
Dim s As String = prm_text_to_encrypt
Dim managed2 As New RijndaelManaged With {
.Padding = PaddingMode.Zeros,
.Mode = CipherMode.CBC,
.BlockSize = 256
}
Dim stream As New MemoryStream
Dim stream2 As New CryptoStream(stream, managed2.CreateEncryptor(Encoding.ASCII.GetBytes(prm_key), Encoding.ASCII.GetBytes(prm_iv)), CryptoStreamMode.Write)
Dim bytes As Byte() = Encoding.ASCII.GetBytes(s)
stream2.Write(bytes, 0, bytes.Length)
stream2.FlushFinalBlock()
Return Convert.ToBase64String(stream.ToArray)
End Function
Can anyone please help? I am lost at this point. :/

Python RSA Decrypt for class using vs2013

For my class assignment we need to decrypt a message that used RSA Encryption. We were given code that should help us with the decryption, but its not helping.
def block_decode(x):
output = ""
i = BLOCK_SIZE+1
while i > 0:
b1 = int(pow(95,i-1))
y = int(x/b1)
i = i - 1
x = x - y*b1
output = output + chr(y+32)
return output
I'm not great with python yet but it looks like it is doing something one character at a time. What really has me stuck is the data we were given. Can't figure out where or how to store it or if it is really decrypted data using RSA. below are just 3 lines of 38 lines some lines have ' or " or even multiple.
FWfk ?0oQ!#|eO Wgny 1>a^ 80*^!(l{4! 3lL qj'b!.9#'!/s2_
!BH+V YFKq _#:X &?A8 j_p< 7\[0 la.[ a%}b E`3# d3N? ;%FW
KyYM!"4Tz yuok J;b^!,V4) \JkT .E[i i-y* O~$? o*1u d3N?
How do I get this into a string list?
You are looking for the function ord which is a built-in function that
Returns the integer ordinal of a one-character string.
So for instance, you can do:
my_file = open("file_containing_encrypted_message")
data = my_file.read()
to read in the encrypted contents.
Then, you can iterate over each character doing
char_val = ord(each_character)
block_decode(char_val)

Categories

Resources