Transmitting encoded bytes data via JSON

Currently, I am developing a Python RESTful API and facing the challenge of transmitting bytes-encoded data (specifically encrypted data using a public RSA key from the rsa package) over the network in JSON format.

This is what the scenario looks like:

>>> import rsa
>>> pubkey, privkey = rsa.newkeys(512, True) # Generating a pair of 512-bit public/private RSA keys for demonstration purposes.
>>> encStr = rsa.encrypt(b"Test string", pubkey) # Encrypting a bytes object with the public key
>>> encStr
b'r\x10\x03e\xc6*\xa8\xb1\xee\xbd\x18\x0f\x7f\xecz\xcex\xabP~\xb3]\x8f)R\x9b>i\x03\xab-m\x0c\x19\xd7\xa5f$\x07\xc1;X\x0b\xaa2\x99\xa8&\xfc/\x9f\x05!nk\x93%\xc0\xf5\x1d\xf8C\x1fo'

The variable "encStr" contains the data to be sent. However, the encoding used is not immediately clear, as it's not specified in the package documentation. If you have any insights on this, please do share :)

>>> encStr.decode("utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec cannot decode byte 0x8e in position 0: invalid start byte
>>> encStr.decode("latin1")
'\x8eM\x96Æ\'zÈZ\x89\x85±\x98Z¯Ûzùæ¯;£zñ8\x9b§Ù\x9dÏ\x8eâ0®\x89ó(*?\x92ªg\x12ôsä\x1d\x96\x19\x82\x19-3\x15SBýh"3òÖß\x91Ô' # This could be it
>>> encStr.decode("latin1").encode("latin1")
b'\x8eM\x96\xc6\'z\xc8Z\x89\x85\xb1\x98Z\xaf\xdbz\xf9\xe6\xaf;\xa3z\xf18\x9b\xa7\xd9\x9d\xcf\x8e\xe20\xae\x89\xf3(*?\x92\xaag\x12... # Garbled data

After some experimentation, I managed to obtain a readable string using base64 encoding.

>>> import base64
>>> b64_encStr = base64.b64encode(encStr)
>>> b64_encStr
b'jk2Wxid6yFqJhbGYWq/bevnmrzujevE4m6fZnc+O4jCuifMoKj+SqmcS9HPkHZYZghktMxVTQv1oIjPy1t+R1A=='
>>> b64_encStr.decode("utf-8")
'jk2Wxid6yFqJhbGYWq/bevnmrzujevE4m6fZnc+O4jCuifMoKj+SqmcS9HPkHZYZghktMxVTQv1oIjPy1t+R1A=='

At this point, all that remains is transmitting this encoded data. Yet, I am curious if there exists a more efficient method (shorter strings, fewer operations considering client-side encoding and server-side decoding, etc).

Thank you!

Shawn

Answer №1

Base64 serves as a practical method for transmitting bytes as text, with each character representing 6 bits (or 8 bits per byte in standard single-byte character encoding). These bytes can encompass any value, including those typically found in ciphertext. While alternative encodings like basE91 exist, their benefits are outweighed by the added complexity they introduce.

Nevertheless, it's common to see ciphertext needlessly "stringified," even though various systems like files, HTTP, and sockets handle all byte values effectively. In scenarios where data is needed for a GET request, using base64url instead of traditional base 64 encoding would be more suitable. Often, developers encode strings unnecessarily simply for readability within logs or traces; however, only the log output itself requires encoding.

It's worth noting that opting for OAEP padding over PKCS#1, along with utilizing a key size of at least 3072 bits, is recommended—especially when encrypting data intended for transmission, rather than encryption solely "in situ."

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

populate the autocomplete text view with the items from the JSON array

My goal is to retrieve a list of services from a web service and display it in an autocompletetextview. For example, if you type "a", you should see the following list of services in the autocompletetextview. I believe it's a JSON array, but I'm ...

Flaskdance does not provide a secure HTTPS URI

Looking to integrate Google sign-in with Flask Dance for a website built on Flask: from flask_dance.contrib.google import make_google_blueprint, google blueprint = make_google_blueprint( client_id= "CLIENT_ID", client_secret="CLIENT_SECRET", scope=[ " ...

How to organize dates in an Excel spreadsheet using Python

I am looking to extract specific data based on date from an imported excel file in Python. My goal is to provide a start and end date, and receive the data for that particular period. I have attempted various methods to install pandas_datareader in order t ...

Extract data from a DataFrame column using Spark Scala and convert it into an RDD with multiple columns

In my SparkScala RDD, the structure looks like this : df.printSchema() |-- stock._id: string (nullable = true) |-- stock.value: string (nullable = true) The second column of the RDD contains nested JSON data: [ { "warehouse" : "Type1" , "amount" : "0 ...

Looking to query JSON using jQuery - how can I accomplish this?

Currently, I am utilizing session storage to temporarily store data and attempting to search for a specific string (CatalogNumber) within the session data. If the string is not found, my goal is to add it. Despite my efforts, I have encountered issues wit ...

Tips for establishing control when retrieving the JSON information

I have encountered a challenge while developing a currency converter application. The issue I am facing is related to the order of data. My app fetches information from two JSON files - one containing prices and the other containing full names of currencie ...

Learn the steps to automate clicking on the "next" button using Selenium or Scrapy in Python

While attempting to gather data from flipkart.com using scrapy, I successfully collected everything except for navigating to the next page. Initially, I attempted to use scrapy followed by selenium. Interestingly, a class contains two links - one for the p ...

Malformed PHP Array Structure

I am facing an issue with formatting the results of my query in an array and then encoding it into JSON. I want the data to be structured like this: array[0] = project1, project2, project3; array[1] = item1, item2, item3; However, currently, my data ...

What is the best way to exclude a specific part of text, enclosed in quotation marks, when editing a line of text in Python?

I have a log file from Apache that I want to convert to csv. The challenge is that the spaces in the file need to be replaced with commas, but some of the columns contain fields with spaces between them. However, these particular fields are enclosed in quo ...

Extracting Nested Numpy Arrays

I am dealing with a pandas Series that contains one numpy array per entry, all of the same length. My goal is to convert this into a 2D numpy array. Despite knowing that Series and DataFrames don't handle containers well, when using np.histogram(.,.)[ ...

Sending the value from a for loop through AJAX and populating it into a form field

Currently, I have implemented a piece of JavaScript code that captures user input, sends a request to an endpoint using AJAX, and appends a specific field from the returned results as an option within a datalist. This functionality is working perfectly fin ...

"What is the total count of numbers and letters in the input provided by the user

I have this code snippet as the base of my program: from tkinter import * def click(event=None): global text_input user_text = text_input.get("1.0",'end-1c') # what should I do next? window = Tk() text_input = Text(window, height= ...

What is the best way to save a dictionary with tuple keys into a .txt file?

Is it possible to save a dictionary containing tuples as keys into a .txt file? The program works fine with integer keys, but encounters an error when using tuple keys. dict = {(1, 1): 11, (2, 2): 22, (3, 3): 33, (4, 4): 44, (5, 5): 55, (6, 6): 66, (7, 7) ...

I am eager to generate a variable that can adapt to various situations and effectively integrate it

I'm delving into creating and utilizing dynamic variables in Python for the first time. for i in range(0,len(test_data)): globals()["test_list_{}".format(test_data[i])]=[] globals()["test_calculation_{}".format(test_data[ ...

Navigating a JSON dictionary using Python's programmatic approach

In my code, I am attempting to assign a value from a dictionary that has been formatted in JSON to a variable. Here is the JSON-formatted dictionary: "Monetarios": [{"MIFID_NO_CURR_RISK":"B1"},{"MIFID_CURR_RISK":"B2"}], "Monetario Dinamico": [{ ...

Currently caught up creating an Instagram bot

Here is the code snippet I have been working on: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys # initiating browser session browser = webdriver.Chrome() browser.get("https://instagram.com") time.sleep ...

Executing cursor.callproc does not produce any results

Here is a method that I have: from app.database import db def get_channels_list(user_token): data = jwt.decode(user_token, app.config.get('JWT_SECRET')) connection = db.engine.raw_connection() try: cursor = connection.cursor ...

Storing a pair of distinct data fields in a c# Array Json from a Class

Greetings! I have been working on a code snippet where I define all the necessary classes to create a JSON string for a put request. My goal is to include both the AttributeColor and AttributeSize fields in the attributes array so that the JSON output look ...

Selenium-powered Python Web Scraping

I am attempting to gather product information from Amazon, but I keep encountering the error NoElementException: Message: unable to find element: {"method":"xpath","selector":"//li[@class='a-last']"} (Session info: chrome=102.0.5005.115) The cod ...

Unable to determine the dimensions of the Kafka JSON message

My task involves sending a JSON message through Kafka, but my application has limitations on the size of messages it can handle. To construct the message, I am using a Python script. This script reads a base JSON from a file, transforms it, and then saves ...