Encrypt Radius password in python3 - python-3.x

I have used the following code in python2 to encrypt the Radius Password attribue:
def Encrypt_Pass(password, authenticator, secret):
m = md5()
m.update(secret + authenticator)
return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(password.ljust(16, '\0')[:16], m.digest()[:16]))
That does not work in python3, error for m.update line:
TypeError: Unicode-objects must be encoded before hashing
After i do add encoding:
def Encrypt_Pass(password, authenticator, secret):
m = md5()
m.update(secret.encode('ascii') + authenticator.encode('ascii'))
return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(password.ljust(16, '\0')[:16], m.digest()[:16]))
I do still fail with:
TypeError: ord() expected string of length 1, but int found
Now i am lost and forget the details of the algorithm, are you able to help ? How to change that last line to work with python3 ? (working perfectly fine for python2).
Update: I've did troubleshooting, with the code like this:
m = md5()
m.update(secret.encode('ascii') + authenticator.encode('ascii'))
print("Secret {}, encode {}".format(secret,secret.encode('ascii')))
print("auth {}, encode {}".format(authenticator, authenticator.encode('ascii')))
print("m digest: {}".format(m.digest()[:16]))
print("passwd: {}".format(password.ljust(16, '\0')[:16]))
#return "".join(chr(ord(x) ^ y) for x, y in zip(password.ljust(16, '\0')[:16], m.digest()[:16]))
for x, y in zip(password.ljust(16, '\0')[:16], m.digest()[:16]):
print("JOIN ord x: {} y: {}".format(ord(x),y))
a = "".join(chr(ord(x) ^ y))
print("a: {}".format(chr(ord(x) ^ y)))
i got:
Secret cisco, encode b'cisco'
auth 5002CVWVKCX13QTN, encode b'5002CVWVKCX13QTN'
m digest: b'\xf8\xb9\xc2\x1foZ~h\xff#,\x87\x07\xcc:m'
passwd: cisco
JOIN ord x: 99 y: 248
a:
JOIN ord x: 105 y: 185
a: Ð
JOIN ord x: 115 y: 194
a: ±
JOIN ord x: 99 y: 31
a: |
JOIN ord x: 111 y: 111
a:
JOIN ord x: 0 y: 90
a: Z
JOIN ord x: 0 y: 126
a: ~
JOIN ord x: 0 y: 104
a: h
JOIN ord x: 0 y: 255
a: ÿ
JOIN ord x: 0 y: 64
a: #
JOIN ord x: 0 y: 44
a: ,
JOIN ord x: 0 y: 135
a:
JOIN ord x: 0 y: 7
a:
JOIN ord x: 0 y: 204
a: Ì
JOIN ord x: 0 y: 58
a: :
JOIN ord x: 0 y: 109
a: m
So it looks like instead of ord(y) i just have to use y ? But even with that password is still encoded incorrectly with python3 :(

Related

replacements for big int in rust

I made a program to calculate the prime numbers of 1 to n in python and rust. Surprisingly python wins with the difference of 0.008 and 0.590. Rust won all other questions with the difference of 0.001 and 0.008.
The only difference here, is that I need to calculate a large number. Python is fine with large numbers, but rust requires a crate knows as num. Without using the num crate, rust wins.
Is there some how that I can avoid using num, without changing my solution?
Here are the rust and python solutions.
from functools import reduce
fact = lambda x: reduce(lambda y, z: y*z, range(1,x+1))
is_prime = lambda x: False if x <= 1 else fact(x-1) % x == x - 1
primes = lambda x, y: tuple(filter(is_prime, range(x,y+1)))
import sys
print(primes(1, int(sys.argv[1])))
macro_rules! number {
(+ $($args:tt),*) => {
num::BigInt::new(num::bigint::Sign::Plus, vec![$($args),*])
};
(- $($args:tt),*) => {
num::BigInt::new(num::bigint::Sign::Minus, vec![$($args),*])
};
}
fn fact(x: u32) -> num::BigInt {
(1..x+1).map(|x| number!(+ x)).reduce(|x, y| x * y).unwrap()
}
fn is_prime(x: u32) -> bool {
x > 1 && fact(x - 1) % x == number!(+ (x - 1))
}
fn main() {
let n = &(std::env::args().collect::<Vec<String>>())[1];
println!("{:#?}", (1..=n.parse::<u32>().unwrap()).filter(|x| is_prime(*x)).collect::<Vec<u32>>());
}

Sympy TypeError - cannot interpret float object as Integer

i am using the Sympy package and trying to integrate, for this i have written a small function:
from sympy import *
from __future__ import division
init_printing()
x, Rn = symbols('x Rn')
def minimum(k):
expr = (x**(k/2-1)*exp(-x/2))/(2**(k/2)*gamma(k/2))
linkes_int = integrate(x*expr,(x,0,Rn))
rechtes_int = integrate(Rn*expr,(x,Rn,oo))
minimum1 = linkes_int + rechtes_int
return(minimum1,linkes_int,rechtes_int)
ergebnis = minimum(6)
Now when calling the method with an even parameter of 6 or higher i get a TypeError stating that a float object cannot be interpreted as an Integer. I am not sure why this is the case especially since it´s only for k>=6.
Another question i have is, is there a possibility to give boundaries to symbols in Sympy ? Something like it has to be greater than zero or and Integer or something?
My error is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-1a7d2848e620> in <module>()
7 return(minimum1,linkes_int,rechtes_int)
8 k = Symbol("k", properties = [lambda s: (s/2).is_Integer])
----> 9 ergebnis = minimum(6)
10 #ergebnis[0]
11 asd = simplify(ergebnis[0])
<ipython-input-4-1a7d2848e620> in minimum(k)
2 def minimum(k):
3 expr = (x**(k/2-1)*exp(-x/2))/(2**(k/2)*gamma(k/2))
----> 4 linkes_int = integrate(x*expr,(x,1,Rn))
5 rechtes_int = integrate(Rn*expr,(x,Rn,oo))
6 minimum1 = linkes_int + rechtes_int
C:\ProgramData\Anaconda3\lib\site-packages\sympy\integrals\integrals.py in integrate(*args, **kwargs)
1293 if isinstance(integral, Integral):
1294 return integral.doit(deep=False, meijerg=meijerg, conds=conds,
-> 1295 risch=risch, manual=manual)
1296 else:
1297 return integral
C:\ProgramData\Anaconda3\lib\site-packages\sympy\integrals\integrals.py in doit(self, **hints)
484 function, xab[0],
485 meijerg=meijerg1, risch=risch, manual=manual,
--> 486 conds=conds)
487 if antideriv is None and meijerg1 is True:
488 ret = try_meijerg(function, xab)
C:\ProgramData\Anaconda3\lib\site-packages\sympy\integrals\integrals.py in _eval_integral(self, f, x, meijerg, risch, manual, conds)
906 # rewrite using G functions
907 try:
--> 908 h = meijerint_indefinite(g, x)
909 except NotImplementedError:
910 from sympy.integrals.meijerint import _debug
C:\ProgramData\Anaconda3\lib\site-packages\sympy\integrals\meijerint.py in meijerint_indefinite(f, x)
1610 results = []
1611 for a in sorted(_find_splitting_points(f, x) | {S(0)}, key=default_sort_key):
-> 1612 res = _meijerint_indefinite_1(f.subs(x, x + a), x)
1613 if not res:
1614 continue
C:\ProgramData\Anaconda3\lib\site-packages\sympy\integrals\meijerint.py in _meijerint_indefinite_1(f, x)
1675 if b < 0 or f.subs(x, 0).has(nan, zoo):
1676 place = None
-> 1677 r = hyperexpand(r.subs(t, a*x**b), place=place)
1678
1679 # now substitute back
C:\ProgramData\Anaconda3\lib\site-packages\sympy\simplify\hyperexpand.py in hyperexpand(f, allow_hyper, rewrite, place)
2471 if not r.has(nan, zoo, oo, -oo):
2472 return r
-> 2473 return f.replace(hyper, do_replace).replace(meijerg, do_meijer)
C:\ProgramData\Anaconda3\lib\site-packages\sympy\core\basic.py in replace(self, query, value, map, simultaneous, exact)
1406 return expr
1407
-> 1408 rv = bottom_up(self, rec_replace, atoms=True)
1409
1410 # restore original expressions for Dummy symbols
C:\ProgramData\Anaconda3\lib\site-packages\sympy\simplify\simplify.py in bottom_up(rv, F, atoms, nonbasic)
997 if args != rv.args:
998 rv = rv.func(*args)
--> 999 rv = F(rv)
1000 elif atoms:
1001 rv = F(rv)
C:\ProgramData\Anaconda3\lib\site-packages\sympy\core\basic.py in rec_replace(expr)
1391 result = _query(expr)
1392 if result or result == {}:
-> 1393 new = _value(expr, result)
1394 if new is not None and new != expr:
1395 mapping[expr] = new
C:\ProgramData\Anaconda3\lib\site-packages\sympy\core\basic.py in <lambda>(expr, result)
1334 _value = lambda expr, result: value(*expr.args)
1335 elif callable(value):
-> 1336 _value = lambda expr, result: value(*expr.args)
1337 else:
1338 raise TypeError(
C:\ProgramData\Anaconda3\lib\site-packages\sympy\simplify\hyperexpand.py in do_meijer(ap, bq, z)
2468 def do_meijer(ap, bq, z):
2469 r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
-> 2470 allow_hyper, rewrite=rewrite, place=place)
2471 if not r.has(nan, zoo, oo, -oo):
2472 return r
C:\ProgramData\Anaconda3\lib\site-packages\sympy\simplify\hyperexpand.py in _meijergexpand(func, z0, allow_hyper, rewrite, place)
2345
2346 t = Dummy('t')
-> 2347 slater1, cond1 = do_slater(func.an, func.bm, func.ap, func.bq, z, z0)
2348
2349 def tr(l):
C:\ProgramData\Anaconda3\lib\site-packages\sympy\simplify\hyperexpand.py in do_slater(an, bm, ap, bq, z, zfinal)
2279 premult = (t/k)**bh
2280 hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
-> 2281 t, premult, bh, rewrite=None)
2282 res += fac * hyp
2283 else:
C:\ProgramData\Anaconda3\lib\site-packages\sympy\simplify\hyperexpand.py in _hyperexpand(func, z, ops0, z0, premult, prem, rewrite)
2002 # Try to recognise a shifted sum.
2003 p = S(0)
-> 2004 res = try_shifted_sum(func, z0)
2005 if res is not None:
2006 func, nops, p = res
C:\ProgramData\Anaconda3\lib\site-packages\sympy\simplify\hyperexpand.py in try_shifted_sum(func, z)
1656
1657 ops = []
-> 1658 for n in range(r - 1):
1659 ops.append(ShiftA(n + 1))
1660 ops.reverse()
TypeError: 'Float' object cannot be interpreted as an integer
The problem is this integral:
In [59]: Integral(0.0625*x**3.0*exp(-x/2), (x, 0, Rn))
Out[59]:
Rn
⌠
⎮ -x
⎮ ───
⎮ 3.0 2
⎮ 0.0625⋅x ⋅ℯ dx
⌡
0
It should be fine but sympy gives a TypeError. That's just a bug in sympy:
In [60]: Integral(0.0625*x**3.0*exp(-x/2), (x, 0, Rn)).doit()
---------------------------------------------------------------------------
TypeError
However the bug is only seen when there are floats in the input and there's no need for these floats:
In [61]: nsimplify(Integral(0.0625*x**3.0*exp(-x/2), (x, 0, Rn)))
Out[61]:
Rn
⌠
⎮ -x
⎮ ───
⎮ 3 2
⎮ x ⋅ℯ
⎮ ─────── dx
⎮ 16
⌡
0
In [62]: nsimplify(Integral(0.0625*x**3.0*exp(-x/2), (x, 0, Rn))).doit()
Out[62]:
-Rn
────
⎛ 3 2 ⎞ 2
⎝- Rn - 6⋅Rn - 24⋅Rn - 48⎠⋅ℯ
────────────────────────────────── + 6
8
The simplest solution is to sympify the integer 6: ergebnis = minimum(S(6))

Python reduce function not working the way it is expected

I have a very simple use case in which i have a list of names and i have to calculate the total length of all the words in the names list. Below is my code base but it does not work the way i expect :
In [13]: names = ['John', 'Arya', 'Maya', 'Mary']
In [14]: from functools import reduce
In [15]: check = reduce(lambda x, y: len(x) + len(y), names)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-39802d43150a> in <module>
----> 1 check = reduce(lambda x, y: len(x) + len(y), names)
<ipython-input-15-39802d43150a> in <lambda>(x, y)
----> 1 check = reduce(lambda x, y: len(x) + len(y), names)
TypeError: object of type 'int' has no len()
Can someone please point out where i am going wrong .
For completeness thought I'd also show map, a more functional approach:
total_length = sum(map(len, names))
Just use a generator expression with sum. reduce will only sometimes be better or clearer for specific use cases.
names = ['John', 'Arya', 'Maya', 'Mary']
total_length = sum(len(name) for name in names)
If you do want to use reduce, the first parameter is the accumulated value and the second is the next element of the list. You'll need to provide a starting value and only call len on the your y value:
total_length = reduce(lambda x, y: x + len(y), names, 0)
Here's a pure-python implementation of reduce():
>>> def reduce(fun, seq, initial=0):
... acc = initial
... for item in seq:
... acc = fun(acc, item)
... return acc
We can see that fun() receives the accumulator and the current value from seq. This is apparent when you trace the execution:
>>> def foo(x, y):
... print("foo(%s, %s) -> %s" % (x, y, x+y))
... return x+y
...
>>> reduce(foo, range(6))
foo(0, 1) -> 1
foo(1, 2) -> 3
foo(3, 3) -> 6
foo(6, 4) -> 10
foo(10, 5) -> 15
15

Variable number of nested for loops with fixed range

I'm looking for a method to have a variable number of nested for loops instead of the following code. For example if the variable n represents the number of nested for loops and n = 3, my code would be:
p = []
for i in range(26):
for j in range(26):
for k in range(26):
p.append([i,j,k])
Instead, if n = 2 my code would be:
p = []
for i in range(26):
for j in range(26):
p.append([i,j])
I understand this can be done using recursion but I'm a bit confused as to how I'd go about doing this.
It's important for one to develop the skills to reason about these problems. In this case, Python includes itertools.product but what happens the next time you need to write a behaviour specific to your program? Will there be another magical built-in function? Maybe someone else will have published a 3rd party library to solve your problem?
Below, we design product as a simple recursive function that accepts 1 or more lists.
def product (first, *rest):
if not rest:
for x in first:
yield (x,)
else:
for p in product (*rest):
for x in first:
yield (x, *p)
for p in product (range(2), range(2), range(2)):
print ('x: %d, y: %d z: %d' % p)
# x: 0, y: 0 z: 0
# x: 1, y: 0 z: 0
# x: 0, y: 1 z: 0
# x: 1, y: 1 z: 0
# x: 0, y: 0 z: 1
# x: 1, y: 0 z: 1
# x: 0, y: 1 z: 1
# x: 1, y: 1 z: 1
Assuming you want a more conventional iteration ordering, you can accomplish do so by using an auxiliary loop helper
def product (first, *rest):
def loop (acc, first, *rest):
if not rest:
for x in first:
yield (*acc, x)
else:
for x in first:
yield from loop ((*acc, x), *rest)
return loop ((), first, *rest)
for p in product (range(2), range(2), range(2)):
print ('x: %d, y: %d z: %d' % p)
# x: 0, y: 0 z: 0
# x: 0, y: 0 z: 1
# x: 0, y: 1 z: 0
# x: 0, y: 1 z: 1
# x: 1, y: 0 z: 0
# x: 1, y: 0 z: 1
# x: 1, y: 1 z: 0
# x: 1, y: 1 z: 1
Something like this should work:
import itertools
n=3
fixed=26
p = list(itertools.product(range(fixed), repeat=n))
This solution uses the optimized functions of itertools, so it should be quite fast.
Mind that itertools.product returns an iterator, so one needs to transform it to get an array.

Pyspark - Max / Min Parameter

I have a query. In Pyspark when we need to get total(SUM) based on (Key,Value), our query reads like:
RDD1 = RDD.reduceByKey(lambda x , y: x + y)
where as when we need to find MAX / MIN value for (Key,Value) our query reads like
RDD1 = RDD.reduceByKey(lambda x , y: x if x[1] >= y[1] else y)
Why when we Sum data not using x[1], Y[1], where as same is use for MAX / MIN?. Please clarify the doubt.
Rgd's
You're wrong and you've taken this code out of context. In both cases x and y refer to values.
lambda x , y: x if x[1] >= y[1] else y
is equivalent to:
lambda x, y: max(x, y, key=lambda x: x[1])
It compares values by their second element and means that each value:
Is indexable (implements __getitem__).
Has at least two elements.
Example
sc.parallelize([(1, ("a", -3)), (1, ("b", 3))]) \
.reduceByKey(lambda x , y: x if x[1] >= y[1] else y).first()
will be (1, ('b', 3)) because 3 is larger than -3.

Resources