I read this : https://stackoverflow.com/a/37605582/6426449
START_TIME = a constant that represents a unix timestamp
def make_id():
t = int(time.time()*1000) - START_TIME
u = random.SystemRandom().getrandbits(23)
id = (t << 23 ) | u
return id
def reverse_id(id):
t = id >> 23
return t + START_TIME
From above def, How to get t and u of id(It's generated from def make_id)?
Like
def get_t(id):
some methods
return t
def get_u(id):
some methods
return u
To get t, just undo the left shift with a right shift.
def get_t(id):
return id >> 23
To get u, use a bit mask with the rightmost 23 bits set
def get_u(id):
return id & 0x7fffff
Related
Im trying to subtract with prefixes as objects.
Here is my code
class Prefix:
def __init__(self, m=0, cm=0):
self.m = m
self.cm = cm
def __sub__(self, other):
centim = self.cm - other.cm
meter = (self.m - other.m) - abs(centim/100)
if meter < 1:
centim = m*100
meter = 0
return Prefix(meter, cm)
Im trying to subtract in a way which creates a negative centimeter value and take 1m from the meter object such that this is fulfilled
Prefix(2, 20) - Prefix(1, 30) == Prefix(0, 90)
First, keep in mind that for a given length, everything to the right of the hundreds place goes into cm, and everything at it or to its left gets divided by 100, and then goes into m.
Given this, we can recast the problem as converting both Prefix objects into their full lengths, performing calculations there, and then creating a new Prefix from the result:
class Prefix:
def __init__(self, m=0, cm=0):
self.m = m
self.cm = cm
def __sub__(self, other):
self_length = self.m * 100 + self.cm
other_length = other.m * 100 + other.cm
result_length = self_length - other_length
result_m, result_cm = divmod(result_length, 100)
return Prefix(result_m, result_cm)
result = Prefix(2, 20) - Prefix(1, 30)
print(result.m, result.cm)
Output:
0 90
Since we've come this far, we might as well store a "length" and overload __repr__ to make the result prettier:
class Prefix:
def __init__(self, length):
self.length = length
def __sub__(self, other):
result_length = self.length - other.length
return Prefix(result_length)
def __repr__(self):
result_m, result_cm = self.split_up(self.length)
if result_m > 0:
return f'{result_m}m {result_cm}cm'
else:
return f'{result_cm}cm'
#staticmethod
def split_up(length):
return divmod(length, 100)
Prefix(220) - Prefix(130)
Output:
90cm
So I defined a function such that it returns a sum of two Time objects as a new Time object, but the sum of the minutes in that resulting Time object cannot exceed 59 and I don't know how to implement that.
Here's my code:
from timer import Time
sum_of_time = Time(0, 0)
sum_of_time.hours= time1.hours + time2.hours
sum_of_time.minutes = time1.minutes + time2.minutes
return sum_of_time
if sum_of_time.minutes >= 60: # where I try to make minutes within 0 to 59
sum_of_time.minutes = sum_of_time.minutes - 60
sum_of_time.hours = sum_of_time.hours + 1
return sum_of_time
This is what datetime.timedelta is used for.
from datetime import timedelta
delta1 = timedelta(hours=1, minutes=30)
delta2 = timedelta(minutes=31)
sum_time = delta1 + delta2
print(sum_time) #2:01:00
You want to get the quotient and remainder when dividing by 60; the quotient gets added to the hour, and the remainder is used as the number of minutes.
sum_of_time = Time(0,0)
hours = time1.hours + time2.hours
minutes = time1.minutes + time2.minutes
q, r = divmod(minutes, 60) # e.g. divmod(117, 60) == (1, 57)
hours += q
minutes = r
sum_of_time.hours = hours
sum_of_time.minutes = minutes
This is logic that should probably be implemented by methods of the Time class. For example:
class Time:
def __init__(self, h, m):
self.hours = 0
self.minutes = 0
# For simplicity here, assume other is an instance of Time
def __add__(self, other):
hours = self.hours + other.hours
minutes = self.minutes + other.minutes
q, r = divmod(minutes, 60)
return Time(hours + q, r)
sum_of_time = time1 + time2
class Time:
def __init__(self,h,m):
self.h = h
self.m = m
q, r = divmod(m, 60)
self.h += q
self.m = r
def __add__(self, o):
return Time(self.h+o.h,self.m+o.m)
def __str__(self):
return "{0}:{1}".format(self.h,self.m)
t1 = Time(1,60)
t2 = Time(1,60)
print (t1+t2)
I am wondering in the following code,
In the code below i is set to min child, why is this done instead of say just having i = i*2. Both ways 'lower' the level of the binary heap, I am just curious as to why the minimum would be chosen (Assuming both children are NOT smaller than parent, why is the smaller of the two larger children chosen instead of one of them arbitrarily)
To be clear these methods below also belong to the binaryheap class
def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i*2] < self.heapList[i*2+1]:
return i * 2
else:
return i * 2 + 1
The code for the binary heap class is
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapList.pop()
self.percDown(1)
return retval
Why "can't assign to operator" error for this line point * hours = QP?
class Student(object):
def __init__(self, name, surname, grade, hours, QP):
self.name = name
self.surname = surname
self.grade = grade
self.hours = hours
self.QP = QP
def getName(self):
return '{}'.format(self.name)
def getSurname(self):
return '{}'.format(self.surname)
def getGrade(self):
return list(zip(self.grade, self.hours))
def getHours(self):
return '{}'.format(self.hours)
def point(self):
if grade == A:
point = 4.0
elif grade == B:
point = 3.0
elif grade == C:
point = 2.0
elif grade == D:
point = 1.0
else:
point = 0.0
def getQPoints(self):
point * hours = QP
return QP
stud1 = Student("John","Brown",["A","B","A"],["15.0","25.0","20.0"],"")
stud2 = Student("Mary","Watson",["C","A","B"],["15.0","25.0","20.0"],"")
print (stud1.getQPoints())
I don't believe that you can reverse that. Instead, do
QP = point * hours
That way, you instantiate the new variable, and set it to the product of the points and the hours.
Some other issues: your point variable isn't defined either. You need
self.point = point
in order to have the variable as an actual variable. Also, it might cause some confusion between the point function and the point variable, because of the two being the same name. One or the other, I'd name one as points.
If I understood what are you trying to do:
You are trying to assign points * hours to QP which is not possible in python that way, so you have to do it normally like this:
`QP = points * hours`
First of all I must say my knowledge with using Sage math is really very limited, but I really want to improve and to be able to solve these problems I'm having. I have been asked to implement the following:
Use an Sage implementation of the cryptosystem NTRU and the library “cryptography” to build a KEM/DEM system with security of 128 bits, generated key of 128 bits and, on the DEM phase, use the cipher AES of 128 bits.
While trying to solve I came across an implementation of NTRU-Prime in sage and wanted to use it to solve this problem:
My Attemp:
p = 739; q = 9829; t = 204
Zx.<x> = ZZ[]; R.<xp> = Zx.quotient(x^p-x-1)
Fq = GF(q); Fqx.<xq> = Fq[]; Rq.<xqp> = Fqx.quotient(x^p-x-1)
F3 = GF(3); F3x.<x3> = F3[]; R3.<x3p> = F3x.quotient(x^p-x-1)
import itertools
def concat(lists):
return list(itertools.chain.from_iterable(lists))
def nicelift(u):
return lift(u + q//2) - q//2
def nicemod3(u): # r in {0,1,-1} with u-r in {...,-3,0,3,...}
return u - 3*round(u/3)
def int2str(u,bytes):
return ''.join([chr((u//256^i)%256) for i in range(bytes)])
def str2int(s):
return sum([ord(s[i])*256^i for i in range(len(s))])
def encodeZx(m): # assumes coefficients in range {-1,0,1,2}
m = [m[i]+1 for i in range(p)] + [0]*(-p % 4)
return ''.join([int2str(m[i]+m[i+1]*4+m[i+2]*16+m[i+3]*64,1) for i in range(0,len(m),4)])
def decodeZx(mstr):
m = [str2int(mstr[i:i+1]) for i in range(len(mstr))]
m = concat([[m[i]%4,(m[i]//4)%4,(m[i]//16)%4,m[i]//64] for i in range(len(m))])
return Zx([m[i]-1 for i in range(p)])
def encodeRq(h, nBits = 9856):
h = [lift(h[i]) for i in range(p)] + [0]*(-p % 3)
h = ''.join([int2str(h[i]+h[i+1]*10240+h[i+2]*10240^2,5) for i in range(0,len(h),3)])
return h[0:(nBits/8)]
def decodeRq(hstr):
h = [str2int(hstr[i:i+5]) for i in range(0,len(hstr),5)]
h = concat([[h[i]%10240,(h[i]//10240)%10240,h[i]//10240^2] for i in range(len(h))])
if max(h) >= q: raise Exception("pk out of range")
return Rq(h)
def encoderoundedRq(c,nBits):
c = [1638 + nicelift(c[i]/3) for i in range(p)] + [0]*(-p % 2)
c = ''.join([int2str(c[i]+c[i+1]*4096,3) for i in range(0,len(c),2)])
return c[0:1109]
def decoderoundedRq(cstr):
c = [str2int(cstr[i:i+3]) for i in range(0,len(cstr),3)]
c = concat([[c[i]%4096,c[i]//4096] for i in range(len(c))])
if max(c) > 3276: raise Exception("c out of range")
return 3*Rq([c[i]-1638 for i in range(p)])
def randomR(): # R element with 2t coeffs +-1
L = [2*randrange(2^31) for i in range(2*t)]
L += [4*randrange(2^30)+1 for i in range(p-2*t)]
L.sort()
L = [(L[i]%4)-1 for i in range(p)]
return Zx(L)
def keygen():
while True:
g = Zx([randrange(3)-1 for i in range(p)])
if R3(g).is_unit(): break
f = randomR()
h = Rq(g)/(3*Rq(f))
pk = encodeRq(h)
return pk,encodeZx(f) + encodeZx(R(lift(1/R3(g)))) + pk
import hashlib
def hash(s): h = hashlib.sha512(); h.update(s); return h.digest()
def encapsulate(pk):
h = decodeRq(pk)
r = randomR()
hr = h * Rq(r)
m = Zx([-nicemod3(nicelift(hr[i])) for i in range(p)])
c = Rq(m) + hr
fullkey = hash(encodeZx(r))
return fullkey[:32] + encoderoundedRq(c,128),fullkey[32:]
def decapsulate(cstr,sk):
f,ginv,h = decodeZx(sk[:185]),decodeZx(sk[185:370]),decodeRq(sk[370:])
confirm,c = cstr[:32],decoderoundedRq(cstr[32:])
f3mgr = Rq(3*f) * c
f3mgr = [nicelift(f3mgr[i]) for i in range(p)]
r = R3(ginv) * R3(f3mgr)
r = Zx([nicemod3(lift(r[i])) for i in range(p)])
hr = h * Rq(r)
m = Zx([-nicemod3(nicelift(hr[i])) for i in range(p)])
checkc = Rq(m) + hr
fullkey = hash(encodeZx(r))
if sum([r[i]==0 for i in range(p)]) != p-2*t: return False
if checkc != c: return False
if fullkey[:32] != confirm: return False
return fullkey[32:]
print("Exe 2")
print("")
pk,sk = keygen()
c,k = encapsulate(pk)
k == decapsulate(c,sk)
print("")
print("{:d} bytes in public key that is {:d} bits".format(len(pk),len(pk)*8))
print("{:d} bytes in secret key that is {:d} bits".format(len(sk),len(sk)*8))
print("{:d} bytes in ciphertext that is {:d} bits".format(len(c),len(c)*8))
print("{:d} bytes in shared secret that is {:d} bits".format(len(k),len(k)*8))
Now I know I can use this to get to the solution of the question mentioned above. I assume the key mentioned in the question is the private key because that is the one we generate (am I right?) so I know I have to edit this function:
def keygen():
while True:
g = Zx([randrange(3)-1 for i in range(p)])
if R3(g).is_unit(): break
f = randomR()
h = Rq(g)/(3*Rq(f))
pk = encodeRq(h) #Encode private key with 128 bits
return pk,encodeZx(f) + encodeZx(R(lift(1/R3(g)))) + pk
In order to do this I tried editing the function encodeRq used on this one to encode 128 bits only but that brought up lots of compiling errors that I just couldn't understand. But at least am I right to assume it's here where I have to set my key to be generated with 128 bits?
I believe the KEM mentioned in the question is handled with the function encapsulate and believe that I don't have to change anything there (am I right?)
The biggest problem is really the DEM phase wich I believe is being implemented on the function decapsulate (am I right?) but how should I change this to use AES? How do I do it on sage? any library I should know about?
I am a bit lost here and just want to know if my assumptions are correct and to be indicated on the right path. Thanks for any answer in advance.