Code conversion from Python to Lua almost completed - python

I found a Python script that I'm trying to convert to Lua. I believe I have it just about converted, but the code isn't quite working properly, so I need assistance as I do not know Python at all, and can only guess at the intentions. This is merely a color converter to convert RGB color to xterm 256. The table is quite huge, so I've truncated it for ease of reading.
Python code:
import sys, re
CLUT = [ # color look-up table
# 8-bit, RGB hex
# Primary 3-bit (8 colors). Unique representation!
('00', '000000'),
('01', '800000'),
('02', '008000'),
('03', '808000'),
('04', '000080'),
('05', '800080'),
('06', '008080'),
('07', 'c0c0c0'),
]
def _str2hex(hexstr):
return int(hexstr, 16)
def _strip_hash(rgb):
# Strip leading `#` if exists.
if rgb.startswith('#'):
rgb = rgb.lstrip('#')
return rgb
def _create_dicts():
short2rgb_dict = dict(CLUT)
rgb2short_dict = {}
for k, v in short2rgb_dict.items():
rgb2short_dict[v] = k
return rgb2short_dict, short2rgb_dict
def short2rgb(short):
return SHORT2RGB_DICT[short]
def print_all():
""" Print all 256 xterm color codes.
"""
for short, rgb in CLUT:
sys.stdout.write('\033[48;5;%sm%s:%s' % (short, short, rgb))
sys.stdout.write("\033[0m ")
sys.stdout.write('\033[38;5;%sm%s:%s' % (short, short, rgb))
sys.stdout.write("\033[0m\n")
print "Printed all codes."
print "You can translate a hex or 0-255 code by providing an argument."
def rgb2short(rgb):
""" Find the closest xterm-256 approximation to the given RGB value.
#param rgb: Hex code representing an RGB value, eg, 'abcdef'
#returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231', 'ffffff')
>>> rgb2short('0DADD6') # vimeo logo
('38', '00afd7')
"""
rgb = _strip_hash(rgb)
incs = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
# Break 6-char RGB code into 3 integer vals.
parts = [ int(h, 16) for h in re.split(r'(..)(..)(..)', rgb)[1:4] ]
res = []
for part in parts:
i = 0
while i < len(incs)-1:
s, b = incs[i], incs[i+1] # smaller, bigger
if s <= part <= b:
s1 = abs(s - part)
b1 = abs(b - part)
if s1 < b1: closest = s
else: closest = b
res.append(closest)
break
i += 1
#print '***', res
res = ''.join([ ('%02.x' % i) for i in res ])
equiv = RGB2SHORT_DICT[ res ]
#print '***', res, equiv
return equiv, res
RGB2SHORT_DICT, SHORT2RGB_DICT = _create_dicts()
#---------------------------------------------------------------------
if __name__ == '__main__':
import doctest
doctest.testmod()
if len(sys.argv) == 1:
print_all()
raise SystemExit
arg = sys.argv[1]
if len(arg) < 4 and int(arg) < 256:
rgb = short2rgb(arg)
sys.stdout.write('xterm color \033[38;5;%sm%s\033[0m -> RGB exact \033[38;5;%sm%s\033[0m' % (arg, arg, arg, rgb))
sys.stdout.write("\033[0m\n")
else:
short, rgb = rgb2short(arg)
sys.stdout.write('RGB %s -> xterm color approx \033[38;5;%sm%s (%s)' % (arg, short, short, rgb))
sys.stdout.write("\033[0m\n")
And my nearly complete translated Lua code:
CLUT = {
-- Primary 3-bit (8 colors). Unique representation!
['00'] = '000000',
['01'] = '800000',
['02'] = '008000',
['03'] = '808000',
['04'] = '000080',
['05'] = '800080',
['06'] = '008080',
['07'] = 'c0c0c0',
}
function _str2hex(hexstr)
return tonumber(hexstr, 16)
end
function _strip_hash(rgb)
-- Strip leading # if exists
return rgb:gsub("^#", "")
end
function _create_dicts()
short2rgb_dict = CLUT
rgb2short_dict = {}
for k,v in pairs(short2rgb_dict) do
rgb2short_dict[v] = k
end
return rgb2short_dict, short2rgb_dict
end
function short2rgb(short)
return short2rgb_dict[short]
end
function rgb2short(rgb)
-- Find closest xterm-256 approximation to the given RGB value
_create_dicts()
rgb = _strip_hash(rgb)
local res = ""
local equiv = ""
local incs = {"0x00", "0x5f", "0x87", "0xaf", "0xd7", "0xff"}
for part in string.gmatch(rgb, "(..)") do
part = tonumber(part, 16)
i = 1
while i < #incs - 1 do
s, b = tonumber(incs[i]), tonumber(incs[i+1])
if s <= part and part <= b then
s1 = math.abs(s - part)
b1 = math.abs(b - part)
end
if s1 < b1 then
closest = s
else
closest = b
res = res .. closest
break
end
i = i + 1
end
end
equiv = rgb2short_dict[res]
return equiv, res
end
I realize that I'm missing the printing portion of the code, but I wasn't sure if that was at all relevant, and I know some of the code I've translated is not correct at all, as the script would be working otherwise. The failures I get are with the rgb2short function with it not returning the proper equiv and res values. How far off am I with my revision? What changes do I need to make to make it absolutely work?

I wound up figuring it out on my own after some hardcore trial and error. The function rgb2short should have been:
function rgb2short(rgb)
-- Find closest xterm-256 approximation to the given RGB value
_create_dicts()
rgb = _strip_hash(rgb)
local res = ""
local equiv = ""
local incs = {"0x00", "0x5f", "0x87", "0xaf", "0xd7", "0xff"}
for part in string.gmatch(rgb, "(..)") do
part = tonumber(part, 16)
i = 1
while i < #incs-1 do
s, b = tonumber(incs[i]), tonumber(incs[i+1])
if s <= part and part <= b then
s1 = math.abs(s - part)
b1 = math.abs(b - part)
--break
--end
if s1 < b1 then
closest = s
else
closest = b
end
res = res .. string.format("%02x", closest)
break
end
i = i + 1
end
end
equiv = rgb2short_dict[res]
return equiv, res
end

Related

Issue Related To DCT Based Steganography

I am trying to perform DCT Steganography by converting the image to HSV and applying DCT and quantizing it and hiding the text message and stiching the image. In decoding process, applying DCT and quantizing it and extracting the text message from it. But, here I am getting incorrect answer in it. I am using HSV for getting the same image color similar to original image. I used saturation channel to hide the text in it. Now, I am stuck in it and not getting the correct answer. Please help me out in this.
Here is the code:
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 11:13:50 2021
#author: SM
"""
from PIL import Image
import numpy as np
import itertools
import types
import cv2
from Crypto.Cipher import AES
#creation of quantization matrix of quality factor as 50
quant = np.array([[16,11,10,16,24,40,51,61],
[12,12,14,19,26,58,60,55],
[14,13,16,24,40,57,69,56],
[14,17,22,29,51,87,80,62],
[18,22,37,56,68,109,103,77],
[24,35,55,64,81,104,113,92],
[49,64,78,87,103,121,120,101],
[72,92,95,98,112,100,103,99]])
class DiscreteCosineTransform:
#created the constructor
def __init__(self):
self.message = None
self.bitMessage = None
self.oriCol = 0
self.oriRow = 0
self.numBits = 0
#utility and helper function for DCT Based Steganography
#helper function to stich the image back together
def chunks(self,l,n):
m = int(n)
for i in range(0,len(l),m):
yield l[i:i+m]
#function to add padding to make the function dividable by 8x8 blocks
def addPadd(self,img,row,col):
img = cv2.resize(img,(col+(8-col%8),row+(8-row%8)))
return img
#function to transform the message that is wanted to be hidden from plaintext to a list of bits
def toBits(self):
bits = []
for char in self.message:
binval = bin(char)[2:].rjust(8,'0')
#print('bin '+binval)
bits.append(binval)
self.numBits = bin(len(bits))[2:].rjust(8,'0')
return bits
#main part
#encoding function
#applying dct for encoding
def DCTEncoder(self,img,secret):
self.message = str(len(secret)).encode()+b'*'+secret
self.bitMessage = self.toBits()
#get the size of the image in pixels
row, col = img.shape[:2]
self.oriRow = row
self.oriCol = col
if((col/8)*(row/8)<len(secret)):
print("Error: Message too large to encode in image")
return False
if(row%8!=0 or col%8!=0):
img = self.addPadd(img,row,col)
row,col = img.shape[:2]
#split image into RGB channels
hImg,sImg,vImg = cv2.split(img)
#message to be hid in blue channel so converted to type float32 for dct function
#print(bImg.shape)
sImg = np.float32(sImg)
#breaking the image into 8x8 blocks
imgBlocks = [np.round(sImg[j:j+8,i:i+8]-128) for (j,i) in itertools.product(range(0,row,8),range(0,col,8))]
#print(imgBlocks[0])
#blocks are run through dct / apply dct to it
dctBlocks = [np.round(cv2.dct(ib)) for ib in imgBlocks]
#print('DCT Blocks')
#print(dctBlocks[0])
#blocks are run through quantization table / obtaining quantized dct coefficients
quantDCT = [np.round(dbk/quant) for dbk in dctBlocks]
#print('Quant Blocks')
#print(quantDCT[0])
#set LSB in DC value corresponding bit of message
messIndex=0
letterIndex=0
print(self.bitMessage)
for qb in quantDCT:
#find LSB in DCT cofficient and replace it with message bit
#print(len(qb))
DC = qb[0][0]
#print(DC.shape)
DC = np.uint8(DC)
#print(DC)
DC = np.unpackbits(DC)
#print(DC[0])
#print(self.bitMessage[messIndex][letterIndex])
#print(DC[7])
#print(type(DC[7]))
#print(DC[7].shape)
#print(type(self.bitMessage))
#a=self.bitMessage[messIndex][letterIndex]
#print(a)
DC[7] = self.bitMessage[messIndex][letterIndex]
DC = np.packbits(DC)
DC = np.float32(DC)
DC = DC - 255
qb[0][0] = DC
letterIndex = letterIndex + 1
if (letterIndex == 8):
letterIndex = 0
messIndex = messIndex + 1
if (messIndex == len(self.message)):
break
#writing the stereo image
#blocks run inversely through quantization table
sImgBlocks = [quantizedBlock *quant+128 for quantizedBlock in quantDCT]
#blocks run through inverse DCT
#sImgBlocks = [cv2.idct(B)+128 for B in quantizedDCT]
#puts the new image back together
aImg=[]
for chunkRowBlocks in self.chunks(sImgBlocks, col/8):
for rowBlockNum in range(8):
for block in chunkRowBlocks:
aImg.extend(block[rowBlockNum])
print(len(aImg))
aImg = np.array(aImg).reshape(row, col)
#converted from type float32
aImg = np.uint8(aImg)
#show(sImg)
aImg = cv2.merge((hImg,aImg,vImg))
return aImg
#decoding
#apply dct for decoding
def DCTDecoder(self,img):
row, col = img.shape[:2]
messSize = None
messageBits = []
buff = 0
#split the image into RGB channels
hImg,sImg,vImg = cv2.split(img)
#message hid in blue channel so converted to type float32 for dct function
sImg = np.float32(sImg)
#break into 8x8 blocks
imgBlocks = [sImg[j:j+8,i:i+8]-128 for (j,i) in itertools.product(range(0,row,8),range(0,col,8))]
#dctBlocks = [np.round(cv2.dct(ib)) for ib in imgBlocks]
# the blocks are run through quantization table
quantDCT = [ib/quant for ib in imgBlocks]
i=0
flag = 0
nb = ''
#message is extracted from LSB of DCT coefficients
for qb in quantDCT:
DC = qb[0][0]
DC = np.uint8(DC)
#unpacking of bits of DCT
DC = np.unpackbits(DC)
#print('DC',DC,end=' ')
if (flag == 0):
if (DC[7] == 1):
buff+=(0 & 1) << (7-i)
elif (DC[7] == 0):
buff+=(1&1) << (7-i)
else:
if (DC[7] == 1):
nb+='0'
elif (DC[7] == 0):
nb+='1'
i=1+i
#print(i)
if (i == 8):
#print(buff,end=' ')
if (flag == 0):
messageBits.append(buff)
#print(buff,end=' ')
buff = 0
else:
messageBits.append(nb)
#print(nb,end=' ')
nb = ''
i =0
if (messageBits[-1] == 42 and messSize is None):
try:
flag = 1
messSize = int(str(chr(messageBits[0]))+str(chr(messageBits[1])))#int(''.join(messageBits[:-1]))
print(messSize,'a')
except:
print('b')
pass
if (len(messageBits) - len(str(messSize)) - 1 == messSize):
#print(''.join(messageBits)[len(str(messSize))+1:])
return messageBits
pass
print(messageBits)
return ''
def msg_encrypt(msg,cipher):
if (len(msg)%16 != 0):
#a = len(msg)%16 != 0
#print(a)
msg = msg + ' '*(16 - len(msg)%16)
#nonce = cipher.nonce
t1 = msg.encode()
enc_msg = cipher.encrypt(t1)
return enc_msg
def msg_decrypt(ctext,cipher):
dec_msg = cipher.decrypt(ctext)
msg1 = dec_msg.decode()
return msg1
image = cv2.imread('C://Users//hp//Desktop//Lenna.jpg',cv2.IMREAD_UNCHANGED)
image = cv2.cvtColor(image,cv2.COLOR_BGR2HSV_FULL)
#image = cv2.cvtColor(image,cv2.COLOR_RGB2HSV)
secret_msg = 'Shaina'
print(secret_msg)
key = b'Sixteen byte key'
#encryption of message
cipher = AES.new(key,AES.MODE_ECB)
enc_msg = msg_encrypt(secret_msg,cipher)
print(enc_msg)
d = DiscreteCosineTransform()
dct_img_encoded = d.DCTEncoder(image, enc_msg)
dct_img_encoded = cv2.cvtColor(dct_img_encoded,cv2.COLOR_HSV2BGR_FULL)
#dct_img_encoded = cv2.cvtColor(dct_img_encoded,cv2.COLOR_BGR2RGB)
cv2.imwrite('C://Users//hp//Desktop//DCT1.png',dct_img_encoded)
eimg = cv2.imread('C://Users//hp//Desktop//DCT1.png',cv2.IMREAD_UNCHANGED)
eimg = cv2.cvtColor(eimg,cv2.COLOR_BGR2HSV_FULL)
#eimg = cv2.cvtColor(eimg,cv2.COLOR_RGB2HSV)
text = d.DCTDecoder(eimg)
ntext = []
print(text)
for i in range(len(text)):
if(type(text[i]) == str):
ntext.append(text[i])
print(ntext)
#print(type(text))
#print(next)
#binary_data = ''.join([ format(ord(i), "08b") for i in next ])
#all_bytes = [ binary_data[i: i+8] for i in range(0,len(binary_data),8)]
decoded_data = b''
for byte in next:
try:
decoded_data += int (byte,2).to_bytes (len(byte) // 8, byteorder='big')
except Exception as e:
print(byte)
break
print(decoded_data)
#decryption of message
dtext = msg_decrypt(decoded_data,cipher)
print(dtext)
The result I am getting it as:
Please help me out with this.
OK, I've simplified a lot of things and made some changes, and this seems to work with my sample images.
The biggest overall problem you seem to be facing is that the RGB/HSV conversion screws up your least significant bits, thereby losing the embedded message. I'm not convinced manipulating the saturation is the right method. What I've done here is left it in RGB, and I'm manipulating the green band. I'm not doing the quantizing, because I don't think that's a correct method, but I am embedding the message in the bottom 5 bits of the 0th DCT element. That way, I can do some rounding during the decode to allow for a few bits of slop.
Maybe this can help you move forward.
from PIL import Image
import numpy as np
import itertools
import cv2
class DiscreteCosineTransform:
#created the constructor
def __init__(self):
self.message = None
self.numBits = 0
#utility and helper function for DCT Based Steganography
#helper function to stich the image back together
def chunks(self,l,n):
m = int(n)
for i in range(0,len(l),m):
yield l[i:i+m]
#function to add padding to make the function dividable by 8x8 blocks
def addPadd(self,img,row,col):
img = cv2.resize(img,(col+(8-col%8),row+(8-row%8)))
return img
#main part
#encoding function
#applying dct for encoding
def DCTEncoder(self,img,secret):
self.message = str(len(secret)).encode()+b'*'+secret
#get the size of the image in pixels
row, col = img.shape[:2]
if((col/8)*(row/8)<len(secret)):
print("Error: Message too large to encode in image")
return False
if row%8 or col%8:
img = self.addPadd(img,row,col)
row,col = img.shape[:2]
#split image into RGB channels
hImg,sImg,vImg = cv2.split(img)
#message to be hid in saturation channel so converted to type float32 for dct function
#print(bImg.shape)
sImg = np.float32(sImg)
#breaking the image into 8x8 blocks
imgBlocks = [np.round(sImg[j:j+8,i:i+8]-128) for (j,i) in itertools.product(range(0,row,8),range(0,col,8))]
#print('imgBlocks',imgBlocks[0])
#blocks are run through dct / apply dct to it
dctBlocks = [np.round(cv2.dct(ib)) for ib in imgBlocks]
print('imgBlocks', imgBlocks[0])
print('dctBlocks', dctBlocks[0])
#blocks are run through quantization table / obtaining quantized dct coefficients
quantDCT = dctBlocks
print('quantDCT', quantDCT[0])
#set LSB in DC value corresponding bit of message
messIndex=0
letterIndex=0
print(self.message)
for qb in quantDCT:
#find LSB in DCT cofficient and replace it with message bit
bit = (self.message[messIndex] >> (7-letterIndex)) & 1
DC = qb[0][0]
DC = (int(DC) & ~31) | (bit * 15)
qb[0][0] = np.float32(DC)
letterIndex += 1
if letterIndex == 8:
letterIndex = 0
messIndex += 1
if messIndex == len(self.message):
break
#writing the stereo image
#blocks run inversely through quantization table
#blocks run through inverse DCT
sImgBlocks = [cv2.idct(B)+128 for B in quantDCT]
#puts the new image back together
aImg=[]
for chunkRowBlocks in self.chunks(sImgBlocks, col/8):
for rowBlockNum in range(8):
for block in chunkRowBlocks:
aImg.extend(block[rowBlockNum])
aImg = np.array(aImg).reshape(row, col)
#converted from type float32
aImg = np.uint8(aImg)
#show(sImg)
return cv2.merge((hImg,aImg,vImg))
#decoding
#apply dct for decoding
def DCTDecoder(self,img):
row, col = img.shape[:2]
messSize = None
messageBits = []
buff = 0
#split the image into RGB channels
hImg,sImg,vImg = cv2.split(img)
#message hid in saturation channel so converted to type float32 for dct function
sImg = np.float32(sImg)
#break into 8x8 blocks
imgBlocks = [sImg[j:j+8,i:i+8]-128 for (j,i) in itertools.product(range(0,row,8),range(0,col,8))]
dctBlocks = [np.round(cv2.dct(ib)) for ib in imgBlocks]
# the blocks are run through quantization table
print('imgBlocks',imgBlocks[0])
print('dctBlocks',dctBlocks[0])
quantDCT = dctBlocks
i=0
flag = 0
#message is extracted from LSB of DCT coefficients
for qb in quantDCT:
if qb[0][0] > 0:
DC = int((qb[0][0]+7)/16) & 1
else:
DC = int((qb[0][0]-7)/16) & 1
#unpacking of bits of DCT
buff += DC << (7-i)
i += 1
#print(i)
if i == 8:
messageBits.append(buff)
#print(buff,end=' ')
buff = 0
i =0
if messageBits[-1] == 42 and not messSize:
try:
messSize = int(chr(messageBits[0])+chr(messageBits[1]))
print(messSize,'a')
except:
print('b')
if len(messageBits) - len(str(messSize)) - 1 == messSize:
return messageBits
print("msgbits", messageBits)
return None
image = cv2.imread('20210827_092821.jpg',cv2.IMREAD_UNCHANGED)
enc_msg = b'Shaina Sixteen byte key'
#print(enc_msg)
d = DiscreteCosineTransform()
dct_img_encoded = d.DCTEncoder(image, enc_msg)
cv2.imwrite('2021_encoded.png',dct_img_encoded)
eimg = cv2.imread('2021_encoded.png',cv2.IMREAD_UNCHANGED)
text = d.DCTDecoder(eimg)
print(text)
decoded = bytes(text[3:])
print(decoded)

How to implement HMAC in python without using the hmac library?

I want to implement the hmac algorithm with SHA-1 by the definition from RFC 2104. The code is running but the results aren't the same as the test-vectors from RFC. I'm not sure if I'm loading the values correctly(String to Hex, or String to Bytes?).
As template I've used the pseudo-code from wikipedia
I'm not sure about the terms 'blocksize' and 'output size'. In the code from wikipedia the outputsize is one of the input values but never used.
This is my code so far:
First I'm setting up a hash-function, then I'm converting my input-strings (key and message) into hex values. Next step is to to look if key hast go get hashed or filled with zeros. Next I'm xor-ing the single chars from the key with those values (I don't know where they come from, but they're in every example without any comment). Last but not least I'm combining an inner string(I_key_pad + message) and hash it which results in an outer strings that im combining with the outer pad and hash it again.
import hashlib
from functools import reduce
def hmac(key, message, hashfunc):
hasher = hashlib.sha1
blocksize = 40
message = toHex(message) #is this right?
key = toHex(key)
#alternative: loading values as bytes
#message = bytes(message, 'utf-8')
#key = bytes(key, 'utf-8')
if len(key) > blocksize:
key = hasher(key)
else:
#key = key.ljust(blocksize, '0') #filling from right to left
#key = key.ljust(blocksize, b'\0') #same as above but for bytes
key = pad(key, blocksize) #filling from left to right
val1 = 0x5c
val2 = 0x36
i = 0
o_key_pad = ""
i_key_pad = ""
while i < blocksize:
o_key_pad += str(ord(key[i]) ^ val1)
i_key_pad += str(ord(key[i]) ^ val2)
i += 1
tmp_string = str(i_key_pad) + str(message)
tmp_string = tmp_string.encode()
inner_hash = hasher(tmp_string).hexdigest()
fullstring = str(o_key_pad) + inner_hash
fullstring = fullstring.encode()
fullstring = hasher(fullstring).hexdigest()
print(fullstring)
def pad(key, blocksize):
key = str(key)
while len(key) < blocksize:
key = '0' + key
key = key
return key
def toHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0' + hv
lst.append(hv)
return reduce(lambda x, y: x + y, lst)
def main():
while (1):
key = input("key = ")
message = input("message = ")
hash = input("hash (0: SHA-256, 1: SHA-1) = ")
hmac(key, message, hash)
if __name__ == "__main__":
main()
I'm not understanding all the steps in your code, but here's a short example showing HMAC-SHA1 using only hashlib.sha1, with a helper function xor.
import hashlib
def xor(x, y):
return bytes(x[i] ^ y[i] for i in range(min(len(x), len(y))))
def hmac_sha1(key_K, data):
if len(key_K) > 64:
raise ValueError('The key must be <= 64 bytes in length')
padded_K = key_K + b'\x00' * (64 - len(key_K))
ipad = b'\x36' * 64
opad = b'\x5c' * 64
h_inner = hashlib.sha1(xor(padded_K, ipad))
h_inner.update(data)
h_outer = hashlib.sha1(xor(padded_K, opad))
h_outer.update(h_inner.digest())
return h_outer.digest()
def do_tests():
# test 1
k = b'\x0b' * 20
data = b"Hi There"
result = hmac_sha1(k, data)
print(result.hex())
# add tests as desired

SHA256 doesn't yield same result

I'm following on this tutorial and in part 2 (picture below) it shows that the SHA256 yields a result different than what I get when I ran my python code:
the string is: 0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
While the tutorial SHA256 comes to: 600FFE422B4E00731A59557A5CCA46CC183944191006324A447BDB2D98D4B408
My short python shows:
sha_result = sha256(bitconin_addresss).hexdigest().upper()
print sha_result
32511E82D56DCEA68EB774094E25BAB0F8BDD9BC1ECA1CEEDA38C7A43ACEDDCE
in fact, any online sha256 shows the same python result; so am I missing here something?
You're hashing the string when you're supposed to be hashing the bytes represented by that string.
>>> hashlib.sha256('0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'.decode('hex')).hexdigest().upper()
'600FFE422B4E00731A59557A5CCA46CC183944191006324A447BDB2D98D4B408'
You could use Gavin's "base58.py", which I believe he no longer shares it on his github page. However you probably could easily google and find different versions of it from github.
Here is one version edited a little by me:
#!/usr/bin/env python
"""encode/decode base58 in the same way that Bitcoin does"""
import math
import sys
__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
__b58base = len(__b58chars)
def b58encode(v):
""" encode v, which is a string of bytes, to base58.
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += ord(c) << (8*i) # 2x speedup vs. exponentiation
result = ''
while long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value] + result
# Bitcoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == '\0': nPad += 1
else: break
return (__b58chars[0]*nPad) + result
def b58decode(v):
""" decode v into a string of len bytes
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += __b58chars.find(c) * (__b58base**i)
result = ''
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + result
long_value = div
result = chr(long_value) + result
nPad = 0
for c in v:
if c == __b58chars[0]: nPad += 1
else: break
result = chr(0)*nPad + result
return result
try:
import hashlib
hashlib.new('ripemd160')
have_crypto = True
except ImportError:
have_crypto = False
def hash_160(public_key):
if not have_crypto:
return ''
h1 = hashlib.sha256(public_key).digest()
r160 = hashlib.new('ripemd160')
r160.update(h1)
h2 = r160.digest()
return h2
def hash_160_to_bc_address(h160, version="\x00"):
if not have_crypto:
return ''
vh160 = version+h160
h3=hashlib.sha256(hashlib.sha256(vh160).digest()).digest()
addr=vh160+h3[0:4]
return b58encode(addr)
def public_key_to_bc_address(public_key, version="\x00"):
if not have_crypto or public_key is None:
return ''
h160 = hash_160(public_key)
return hash_160_to_bc_address(h160, version=version)
def sec_to_bc_key(sec, version="\x80"):
if not have_crypto or sec is None:
return ''
vsec = version+sec +"\x01"
hvsec=hashlib.sha256(hashlib.sha256(vsec).digest()).digest()
return b58encode(vsec+hvsec[0:4])
def bc_key_to_sec(prv):
return b58decode(prv)[1:33]
def bc_address_to_hash_160(addr):
bytes = b58decode(addr)
return bytes[1:21]
if __name__ == '__main__':
if len(sys.argv) > 1:
if sys.argv[1] == '-en':
print b58encode(sys.argv[2].decode('hex_codec'))
if sys.argv[1] == '-de':
print b58decode(sys.argv[2]).encode('hex_codec')
if sys.argv[1] == '-pub':
print public_key_to_bc_address(sys.argv[2].decode('hex_codec'))
if sys.argv[1] == '-adr':
print bc_address_to_hash_160(sys.argv[2]).encode('hex_codec')
if sys.argv[1] == '-sec':
print sec_to_bc_key(sys.argv[2].decode('hex_codec'))
if sys.argv[1] == '-prv':
print bc_key_to_sec(sys.argv[2]).encode('hex_codec')
else:
print ''
print 'Usage: ./base58.py [options]'
print ''
print ' -en converts hex to base58'
print ' -de converts base58 to hex'
print
print ' -pub public_key_to_bc_address'
print ' -adr bc_address_to_hash_160'
print
print ' -sec sec_to_bc_key'
print ' -prv bc_key_to_sec'
print
To answer your specific question, based on above code you could use this command:
hashlib.sha256('0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'.decode('hex_codec')).digest().encode('hex_codec').upper()

Python 3: ValueError: invalid literal for int() with base 10: '0001.0110010110010102e+22'

I'm a beginner, so sorry if this is obvious.
I'm at a loss here. I've been trying to make an encryption/decryption program, but I keep getting this error. I'm aware that there are other questions on this issue, but I still can't resolve it.
Encryptor:
import binascii
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
n = int(bits, 2)
return int2bytes(n).decode(encoding, errors)
def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
#ENCRYPTION ALGORITHM
algorithm = 61913299
#ASCII ----> NUMBERS
raw = input("Enter text to encrypt:")
binary = text_to_bits(raw)
binary = int(binary)
algorithm = int(algorithm)
encrypted = binary * algorithm
encrypted = str(encrypted)
print(encrypted)
print("Done")
Decryptor:
import sys
import time
def to_bin(string):
res = ''
for char in string:
tmp = bin(ord(char))[2:]
tmp = '%08d' %int(tmp)
res += tmp
return res
def to_str(string):
res = ''
for idx in range(len(string)/8):
tmp = chr(int(string[idx*8:(idx+1)*8], 2))
res += tmp
return res
incorrectpasswords = 0
password=("password")
originpassword = password
x = 1
algorithm = 61913299
while x==1:
passwordattempt =input("Enter Password:")
if passwordattempt == password:
print("Correct")
x = 2
if passwordattempt!= password:
print("Incorrect")
incorrectpasswords = incorrectpasswords + 1
if incorrectpasswords > 2:
if x == 1:
print("Too many wrong attempts, please try again in one minute.")
time.sleep(60)
encrypted = input("Enter numbers to unencrypt:")
encrypted = int(encrypted)
one = encrypted / algorithm
size = sys.getsizeof(one)
one = str(one).zfill(size + 1)
one = int(one)
unencrypted = to_str(one)
x = unencrypted
For the conversion between binary and text, and text and binary, I used some code I found online.
I believe your code is not working because:
one = encrypted / algorithm
generates a float
to turn your string back into a number you should apply
eval(one)
or
float(one)
instead of
int(one)
(You can also turn it into an int after applying float or eval)
alternatively you might be able to get it by using integer division // as opposed to / , which will make one the type int by flooring the decimal result of the divison, but I'm not sure if that is the behavior you are looking for
Example in python 3 shell:
>>> import sys
>>> one = 15/25
>>> size = sys.getsizeof(one)
>>> one = str(one).zfill(size+1)
>>> one
'00000000000000000000000.6'
>>> type(one)
<class 'str'>
>>> one = eval(one)
>>> one
0.6
>>> type(one)
<class 'float'>

How to give each Category a color?

We have a code to draw circles on the Location on the map with the name of each category. Now the circles and text are one color. How do we get them in different color's by category? Example: Category Garden: Blue, Category Stone: Grey.
So far the code:
size(1500,800)
background(1)
nofill()
stroke('#f91')
pen(.2)
fill('#f91', 0.05)
rotate(90)
font("Avenir", "bold", 10)
align('left')
def mapValue(value, fromMin, fromMax, toMin, toMax):
# Figure out how 'wide' each range is
fromSpan = fromMax - fromMin
toSpan = toMax - toMin
# Convert the from range into a 0-1 range (float)
valueScaled = float(value - fromMin) / float(fromSpan)
# Convert the 0-1 range into a value in the to range.
return toMin + (valueScaled * toSpan)
def xOfDot(lon):
return mapValue(lon, -100, 100, 0, WIDTH)
def yOfDot(lat):
return mapValue(lat, -90, 90, HEIGHT, 0)
with open('theft-alerts.json', 'r') as inputFile:
data = json.load(inputFile)
print len(data)
artworksPerCity = {}
for stolenArt in data:
if stolenArt.has_key('Category'):
city = stolenArt['Category']
if stolenArt.has_key('nItemsStolen'):
numbersStolen = int(stolenArt['nItemsStolen'])
if artworksPerCity.has_key(city):
# Adjust the value stored for this city
artworksPerCity[city] = artworksPerCity[city] + numbersStolen
else:
# Create new key with new value
artworksPerCity[city] = numbersStolen
# Draw circle on the map
radius = artworksPerCity[city] /2
x = xOfDot(stolenArt['Lon'])
y = yOfDot(stolenArt['Lat'])
arc(x, y, radius)
text(city, x, y)
print artworksPerCity
Here is a sketch of what I intend to include in my pure python data utility.
def hexidecimalDiget(n,deHex = false):
if(n<0):
print "negitive values not supported by call to hexidecimalDiget("+str(n)+")"
return None
elif(n < 10):
return str(n)
elif(n < 15):
return ["a","b","c","d","e"][n-10]
elif(n in ["a","b","c","d","e"]):
if deHex:
return ["a","b","c","d","e"].index(n)
return n
else:
print "call to hexidecimalDiget("+str(n)+") not supported!"
return None
def colorFormHexArray(arr):
if len(arr)!=3 and len(arr)!=6:
print "invalid length for color on call to colorFormHexArray("+str(arr)+")"
return None
elif None in arr:
print "cannot make color from None arguments in "+str(arr)
return None
else:
ret = "#"
for k in arr:
if(type(k) == list):
for k2 in k:
ret+=hexidecimalDiget(k)
else:
ret+=hexidecimalDiget(k)
return ret
def arrayFromColor(c):
c = c.replace("#","")
col = []
for n,k in enumerate(c):
if(len(c) == 3):
col.append([hexidecimalDiget(k,deHex = True)])
elif(len(c) == 6):
col.append([hexidecimalDiget(c[(n+1)*2-2],deHex = True),hexidecimalDiget(c[(n+1)*2-2],deHex = True)])
return(col)
def intFromHexPair(hp):
ret = 0
for n,k in enumerate(hp):
digBase = 16**(len(hp)-n-1)
ret+=digBase*hexidecimalDiget(hp[0],deHex = True)
return ret
def hexPairFromInt(I,minDigits = 1,maxDigits = 256):
if I<0:
print "negitive numbers not supported by hexPairFromInt"
k= 0
while(16**(k+1) <= I):
k+=1
if k < minDigits:
k = minDigits
if k > minDigits:
print("maxDigitsExceeded")
ret = []
while k>=0
dig = 16**k
ret.append(hexidecimalDiget(int(I)%(dig))
I -= dig
k-=1
return ret
def specColor(start,end,bottom,top):
start = arrayFromColor(start)
end = arrayFromColor(end)
def ret(v):
if( v<start or c>end ):
print("value out of range "+str([start,end]))
return('#aa0000') #eyo <- error red
else:
starts = [intFromHexPair(k) for k in start]
ends = [intFromHexPair(hp) for k in end]
normalized = (v-bottom)/(top-bottom)
return colorFormHexArray([hexPairFromInt(int((starts[n]-ends[n])*normalized),minDigits = 1,maxDigits = 256) for n,k in enumerate(starts)])
return ret
This seems excessive and hasn't even been slightly tested yet (just a stetch up atm) but I'll be testing and incorporating this code here tonight :: http://krewn.github.io/KPlot/

Categories

Resources