Having Trouble converting a string to bytes - hex

I'm trying to convert a string to a byte, thats what I've done.
I want to send out a Modbusprotocol via serial and put it together in bitstring:
tiger = '01'
read = '03'
ac_val = '0031'
word = '0002'
code = tiger+read+ac_val+word
print(code)
010300310002
#now i want to put thist string in a bitstring with the function:
codeh = bytes.fromhex(code)
codeh = b'\x01\x03\x001\x00\x02 #This is what i got
But i was expecting:
codeh = b'\x01\x03\x00\x31\x00\x02
I have no idea why the output is like this.

What it's showing in the output is the ASCII representation of the byte values. Hex 31 corresponds to the ascii character '1'. Try this to see a demonstration:
bytes.fromhex('415343494921')
Here's a chart that shows these low values: https://en.wikipedia.org/wiki/ASCII#Control_code_chart

Related

The encryption won't decrypt

I was given an encrypted copy of the study guide here, but how do you decrypt and read it???
In a file called pa11.py write a method called decode(inputfile,outputfile). Decode should take two parameters - both of which are strings. The first should be the name of an encoded file (either helloworld.txt or superdupertopsecretstudyguide.txt or yet another file that I might use to test your code). The second should be the name of a file that you will use as an output file.
Your method should read in the contents of the inputfile and, using the scheme described in the hints.txt file above, decode the hidden message, writing to the outputfile as it goes (or all at once when it is done depending on what you decide to use).
The penny math lecture is here.
"""
Program: pennyMath.py
Author: CS 1510
Description: Calculates the penny math value of a string.
"""
# Get the input string
original = input("Enter a string to get its cost in penny math: ")
cost = 0
Go through each character in the input string
for char in original:
value = ord(char) #ord() gives us the encoded number!
if char>="a" and char<="z":
cost = cost+(value-96) #offset the value of ord by 96
elif char>="A" and char<="Z":
cost = cost+(value-64) #offset the value of ord by 64
print("The cost of",original,"is",cost)
Another hint: Don't forget about while loops...
Another hint: After letters -
skip ahead by their pennymath value positions + 2
After numbers - skip ahead by their number + 7 positions
After anything else - just skip ahead by 1 position
The issue I'm having in that I cant seem to get the coding right to decode the file it comes out looking the same. This is the current code I have been using. But once I try to decrypt the message it stays the same.
def pennycost(c):
if c >="a" and c <="z":
return ord(c)-96
elif c>="A" and c<="Z":
return ord(c)-64
def decryption(inputfile,outputfile):
with open(inputfile) as f:
fo = open(outputfile,"w")
count = 0
while True:
c = f.read(1)
if not c:
break;
if count > 0:
count = count -1;
continue
elif c.isalpha():
count = pennycost(c)
fo.write(c)
elif c.isdigit():
count = int(c)
fo.write(c)
else:
count = 6
fo.write(c)
fo.close()
inputfile = input("Please enter the input file name: ")
outputfile = input("Plese enter the output file name(EXISTING FILE WILL BE OVER WRITTEN!): ")
decryption(inputfile,outputfile)

Decrypt des with openssl_decrypt in PHP

Trying to decrypt a single des encrypted data using this code:
$keyValue ='0123456789abcdef'; //hex value
$encryptedOrderId = '88C10F0B8C084E5F'; //hex value
$binaryEncrypted = hex2bin($encryptedOrderId);
$decodeValueByOnlineTool = '2020202039353538'; // this is hex
$opensslDecrypt = openssl_decrypt( $encryptedOrderId ,'DES-ECB', $keyValue, OPENSSL_RAW_DATA , '' );
var_dump($opensslDecrypt);
The output is false. I do not know what wrong I'm doing.
The output from my tool is as follows:
Your inputs are in hex. openssl_decrypt expects binary. Use hex2bin on each input before passing to openssl_decrypt.
openssl_decrypt(hex2bin($encryptedOrderId), 'DES-ECB', hex2bin($keyValue), ...
Remember to convert the result back into hex to get the result you want. Make sure you've set OPENSSL_ZERO_PADDING as per your screenshot.
EDIT: The exact code I used...
$keyValue ='0123456789abcdef'; //hex value
$encryptedOrderId = '88C10F0B8C084E5F'; //hex value
$binaryEncrypted = hex2bin($encryptedOrderId);
$decodeValueByOnlineTool = '2020202039353538'; // this is hex
$opensslDecrypt = openssl_decrypt( $binaryEncrypted ,'des-ecb', hex2bin($keyValue), OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING , '');
var_dump($opensslDecrypt);

symbols being printed when english alphabet wanted

I am writing this code and have recently come across an error. I have no idea why this is happening. In theory, the english alphabet should be being printed. However, instead of the english alphabet, symbols are being printed instead.
I can not paste the symbols for some reason, but if you ran the code yourself, you'll understand what I mean.
My full code is posted below.
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ0123456789"
choice = input("Would you like to encrypt or decrypt? [e/d]: ")
if choice == "e":
message = input("Please insert the message you would like to use: ")
keyword = input("Please insert the keyword you would like to use: ")
ik = len(keyword)
i = 0
string = ''
for A in message:
message1 = (ord(A)) - 96
key1 = (ord(keyword[i])) - 96
addition = message1 + key1
string += (chr(addition))
if i >= ik:
i = 0
else:
i += 1
print (string)
You need to add back the 96 you originally took away :) Alternatively, use the Caesar cipher formula as adding back 96 will still result in symbols appearing (I did the ocr coursework already)
addition = message1 + key1 + 96
your code will not work if the keyword is shorter than the message, so use the modulo operator (%) on i with the length of the keyword inside the line:
key1 = (ord(keyword[i])) - 96

String recognition in idl

I have the following strings:
F:\Sheyenne\ROI\SWIR32_subset\SWIR32_2005210_East_A.dat
F:\Sheyenne\ROI\SWIR32_subset\SWIR32_2005210_Froemke-Hoy.dat
and from each I want to extract the three variables, 1. SWIR32 2. the date and 3. the text following the date. I want to automate this process for about 200 files, so individually selecting the locations won't exactly work for me.
so I want:
variable1=SWIR32
variable2=2005210
variable3=East_A
variable4=SWIR32
variable5=2005210
variable6=Froemke-Hoy
I am going to be using these to add titles to graphs later on, but since the position of the text in each string varies I am unsure how to do this using strmid
I think you want to use a combination of STRPOS and STRSPLIT. Something like the following:
s = ['F:\Sheyenne\ROI\SWIR32_subset\SWIR32_2005210_East_A.dat', $
'F:\Sheyenne\ROI\SWIR32_subset\SWIR32_2005210_Froemke-Hoy.dat']
name = STRARR(s.length)
date = name
txt = name
foreach sub, s, i do begin
sub = STRMID(sub, 1+STRPOS(sub, '\', /REVERSE_SEARCH))
parts = STRSPLIT(sub, '_', /EXTRACT)
name[i] = parts[0]
date[i] = parts[1]
txt[i] = STRJOIN(parts[2:*], '_')
endforeach
You could also do this with a regular expression (using just STRSPLIT) but regular expressions tend to be complicated and error prone.
Hope this helps!

check if a string's first 16 char is a number

I'm storing some files in database which has filename like 1839341255115211butterflies.jpg.I need to show this filename to the user as butterflies.jpg.I need to remove the first 16 digit and then show the filename.Added to it I also have few filenames which don't have this 16digit addition prior to the filename.Now my question is how do I identify if this string has 16digit numeric value prior to the filename, based on it remove the 1st 16digit and display just the filename. I'm aware of how to remove the first 16digit and retrive the filename but need help on how to identify a string that has 16digit.
Any suggestion is much appreciated.
A regular expression looks like a good fit here:
^[0-9]{16}
The above will match on strings that start with 16 digits (0 to 9).
Usage:
if(Regex.Match(fileName, #"^[0-9]{16}").Success)
{
fileName = fileName.Remove(0, 16);
}
string.Remove will work quite nicely:
var str = "1839341255115211butterflies.jpg";
str = str.Remove(0, 16);
Console.WriteLine(str);
With Linq:
remove all digits at the beginning until 16 digits:
string file = "1839341255115211butterflies.jpg";
string extension = Path.GetExtension(file);
string fileName = Path.GetFileNameWithoutExtension(file);
fileName = new string(fileName.Where((c, i) => i >= 17 || !Char.IsDigit(c)).ToArray());
file = fileName + extension;
Demo
Edit: If you just want to know if the first 16 chars are digits, it's easier and more readable:
bool startsWith16Digits = file.Take(16).All(Char.IsDigit);

Resources