def checksum(self, samples):
if samples is None:
return None
completed = []
for sentence in samples:
assert sentence[0] == "$"
cksum = reduce(xor, (ord(s) for s in sentence[1:]))
completed.append("%s*%02X" % (sentence, cksum))
if len(completed) == 0:
return None
# NMEA0183 uses \r\n as line separator even on Unix systems.
s = ""
for line in completed:
s = s + line + "\r\n"
return s
python类xor()的实例源码
def __init__(self, n_out, n_state=31, taps=[27, 30]):
self.o = Signal(n_out)
# # #
state = Signal(n_state)
curval = [state[i] for i in range(n_state)]
curval += [0]*(n_out - n_state)
for i in range(n_out):
nv = ~reduce(xor, [curval[tap] for tap in taps])
curval.insert(0, nv)
curval.pop()
self.sync += [
state.eq(Cat(*curval[:n_state])),
self.o.eq(Cat(*curval))
]
def calc_structured_append_parity(content):
"""\
Calculates the parity data for the Structured Append mode.
:param str content: The content.
:rtype: int
"""
if not isinstance(content, str_type):
content = str(content)
try:
data = content.encode('iso-8859-1')
except UnicodeError:
try:
data = content.encode('shift-jis')
except (LookupError, UnicodeError):
data = content.encode('utf-8')
if _PY2:
data = (ord(c) for c in data)
return reduce(xor, data)
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
"""Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` time and produces a
key of `keylen` bytes. By default SHA-1 is used as hash function,
a different hashlib `hashfunc` can be provided.
"""
hashfunc = hashfunc or hashlib.sha1
mac = hmac.new(data, None, hashfunc)
def _pseudorandom(x, mac=mac):
h = mac.copy()
h.update(x)
return map(ord, h.digest())
buf = []
for block in xrange(1, -(-keylen // mac.digest_size) + 1):
rv = u = _pseudorandom(salt + _pack_int(block))
for i in xrange(iterations - 1):
u = _pseudorandom(''.join(map(chr, u)))
rv = starmap(xor, izip(rv, u))
buf.extend(rv)
return ''.join(map(chr, buf))[:keylen]
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
"""Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` time and produces a
key of `keylen` bytes. By default SHA-1 is used as hash function,
a different hashlib `hashfunc` can be provided.
"""
hashfunc = hashfunc or hashlib.sha1
mac = hmac.new(data, None, hashfunc)
def _pseudorandom(x, mac=mac):
h = mac.copy()
h.update(x)
return map(ord, h.digest())
buf = []
for block in xrange(1, -(-keylen // mac.digest_size) + 1):
rv = u = _pseudorandom(salt + _pack_int(block))
for i in xrange(iterations - 1):
u = _pseudorandom(''.join(map(chr, u)))
rv = starmap(xor, izip(rv, u))
buf.extend(rv)
return ''.join(map(chr, buf))[:keylen]
def binary_back_substitute(W, s):
"""
Perform back substitution on a binary system of equations, i.e. it performs Gauss elimination
over the field :math:`GF(2)`. It finds an :math:`\\mathbf{x}` such that
:math:`\\mathbf{\\mathit{W}}\\mathbf{x}=\\mathbf{s}`, where all arithmetic is taken bitwise
and modulo 2.
:param 2darray W: A square :math:`n\\times n` matrix of 0s and 1s,
in row-echelon (upper-triangle) form
:param 1darray s: An :math:`n\\times 1` vector of 0s and 1s
:return: The :math:`n\\times 1` vector of 0s and 1s that solves the above
system of equations.
:rtype: 1darray
"""
# iterate backwards, starting from second to last row for back-substitution
m = np.copy(s)
n = len(s)
for row_num in range(n - 2, -1, -1):
row = W[row_num]
for col_num in range(row_num + 1, n):
if row[col_num] == 1:
m[row_num] = xor(s[row_num], s[col_num])
return m[::-1]
def pbkdf2_bin(data, salt, iterations=1000, key_len=24, hash_func=None):
"""Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` time and produces a
key of `key_len` bytes. By default SHA-1 is used as hash function,
a different hashlib `hash_func` can be provided.
"""
hash_func = hash_func or hashlib.sha1
mac = hmac.new(data, None, hash_func)
def _pseudo_random(x):
h = mac.copy()
h.update(x)
return h.digest()
buf = bytearray()
for block in range(1, -(-key_len // mac.digest_size) + 1):
rv = u = _pseudo_random(salt + _pack_int(block))
for i in range(iterations - 1):
u = _pseudo_random(u)
rv = starmap(xor, zip(rv, u))
buf.extend(rv)
return bytes(buf[:key_len])
def __init__(self, n_out, n_state=23, taps=[17, 22]):
self.o = Signal(n_out)
# # #
state = Signal(n_state, reset=1)
curval = [state[i] for i in range(n_state)]
curval += [0]*(n_out - n_state)
for i in range(n_out):
nv = reduce(xor, [curval[tap] for tap in taps])
curval.insert(0, nv)
curval.pop()
self.sync += [
state.eq(Cat(*curval[:n_state])),
self.o.eq(Cat(*curval))
]
def __init__(self, code, objects=None):
self._OPERATORS = [
('|', operator.or_),
('^', operator.xor),
('&', operator.and_),
('>>', operator.rshift),
('<<', operator.lshift),
('-', operator.sub),
('+', operator.add),
('%', operator.mod),
('/', operator.truediv),
('*', operator.mul),
]
self._ASSIGN_OPERATORS = [(op + '=', opfunc)
for op, opfunc in self._OPERATORS]
self._ASSIGN_OPERATORS.append(('=', lambda cur, right: right))
self._VARNAME_PATTERN = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
if objects is None:
objects = {}
self.code = code
self._functions = {}
self._objects = objects
def encrypt():
ciphertext = ''
with open(args.filename, 'r') as arq:
content = arq.readlines()
for index in range(len(content)):
content[index] = content[index].rstrip('\n')
try:
for line in content:
for index in range(len(line)):
bin_text = format(int(line[index]), '#06b')
bin_secret = format(int(args.secret[index]), '#06b')
for item in range(len(bin_text)):
if item < 2:
ciphertext += bin_text[item]
else:
ciphertext += str(xor(int(bin_text[item]), int(bin_secret[item])))
except IndexError:
print '[*] WARNING: The key and the text must be of the same size.'
quit()
return ciphertext
def number_of_args(fn):
"""Return the number of positional arguments for a function, or None if the number is variable.
Looks inside any decorated functions."""
try:
if hasattr(fn, '__wrapped__'):
return number_of_args(fn.__wrapped__)
if any(p.kind == p.VAR_POSITIONAL for p in signature(fn).parameters.values()):
return None
else:
return sum(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in signature(fn).parameters.values())
except ValueError:
# signatures don't work for built-in operators, so check for a few explicitly
UNARY_OPS = [len, op.not_, op.truth, op.abs, op.index, op.inv, op.invert, op.neg, op.pos]
BINARY_OPS = [op.lt, op.le, op.gt, op.ge, op.eq, op.ne, op.is_, op.is_not, op.add, op.and_, op.floordiv, op.lshift, op.mod, op.mul, op.or_, op.pow, op.rshift, op.sub, op.truediv, op.xor, op.concat, op.contains, op.countOf, op.delitem, op.getitem, op.indexOf]
TERNARY_OPS = [op.setitem]
if fn in UNARY_OPS:
return 1
elif fn in BINARY_OPS:
return 2
elif fn in TERNARY_OPS:
return 3
else:
raise NotImplementedError("Bult-in operator {} not supported".format(fn))
def validate(sentence_bytes):
"""Validate an NMEA sentence, returning either a tuple of substrings or an
:exc:`AssertionError`.
:param sentence_bytes: A bytes object with the raw sentence.
:returns: tuple with individual fields, suitable for use with a
:class:`Sentence_Factory` isntance.
:raises AssertionError: If the sentence is incomplete in some way.
"""
assert sentence_bytes.startswith(b'$'), "Sentence fragment"
content, _, checksum_txt = sentence_bytes[1:].partition(b"*")
if checksum_txt:
checksum_exp = int(checksum_txt, 16)
checksum_act = reduce(xor, content)
assert checksum_exp == checksum_act, "Invalid checksum"
return tuple(content.split(b','))
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
"""Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` time and produces a
key of `keylen` bytes. By default SHA-1 is used as hash function,
a different hashlib `hashfunc` can be provided.
"""
hashfunc = hashfunc or hashlib.sha1
mac = hmac.new(data, None, hashfunc)
def _pseudorandom(x, mac=mac):
h = mac.copy()
h.update(x)
return map(ord, h.digest())
buf = []
for block in xrange(1, -(-keylen // mac.digest_size) + 1):
rv = u = _pseudorandom(salt + _pack_int(block))
for i in xrange(iterations - 1):
u = _pseudorandom(''.join(map(chr, u)))
rv = starmap(xor, izip(rv, u))
buf.extend(rv)
return ''.join(map(chr, buf))[:keylen]
def pbkdf2_bin(hash_fxn, password, salt, iterations, keylen=16):
# https://github.com/mitsuhiko/python-pbkdf2
_pack_int = struct.Struct('>I').pack
hashfunc = sha1
mac = hmac.new(password, None, hashfunc)
def _pseudorandom(x, mac=mac):
h = mac.copy()
h.update(x)
return map(ord, h.digest())
buf = []
for block in xrange(1, -(-keylen // mac.digest_size) + 1):
rv = u = _pseudorandom(salt + _pack_int(block))
for i in xrange(iterations - 1):
u = _pseudorandom("".join(map(chr, u)))
rv = itertools.starmap(operator.xor, itertools.izip(rv, u))
buf.extend(rv)
return "".join(map(chr, buf))[:keylen]
def get_arguments():
ap = argparse.ArgumentParser()
ap.add_argument('-f', '--filter', required=True,
help='Range filter. RGB or HSV')
ap.add_argument('-i', '--image', required=False,
help='Path to the image')
ap.add_argument('-w', '--webcam', required=False,
help='Use webcam', action='store_true')
ap.add_argument('-p', '--preview', required=False,
help='Show a preview of the image after applying the mask',
action='store_true')
args = vars(ap.parse_args())
if not xor(bool(args['image']), bool(args['webcam'])):
ap.error("Please specify only one image source")
if not args['filter'].upper() in ['RGB', 'HSV']:
ap.error("Please speciy a correct filter.")
return args
def get_config(data):
config_list = []
config_string = data.split(split_string)
for x in range(1, len(config_string)):
try:
output = ""
hex_pairs = [config_string[x][i:i+2] for i in range(0, len(config_string[x]), 2)]
for i in range(0,len(config_string[x])/2):
data_slice = int(hex_pairs[i], 16)#get next hex value
key_slice = ord(enc_key[i+1])#get next Char For Key
output += chr(xor(data_slice,key_slice)) # xor Hex and Key Char
print output
except:
output = "DecodeError"
config_list.append(output)
return config_list
# returns pretty config
def eval_expr(expr):
import ast
import operator as op
op = {
ast.Add: op.add,
ast.Sub: op.sub,
ast.Mult: op.mul,
ast.Div: op.truediv,
ast.Pow: op.pow,
ast.BitXor: op.xor,
ast.USub: op.neg,
}
def eval_(node):
if isinstance(node, ast.Num):
return fractions.Fraction(node.n)
elif isinstance(node, ast.BinOp):
return op[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp):
return op[type(node.op)](eval_(node.operand))
raise TypeError(node)
return eval_(ast.parse(str(expr), mode='eval').body)
def __xor__(self, trc):
return self.apply_op2(trc, operator.xor)
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
"""Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` time and produces a
key of `keylen` bytes. By default SHA-1 is used as hash function,
a different hashlib `hashfunc` can be provided.
"""
hashfunc = hashfunc or hashlib.sha1
mac = hmac.new(data, None, hashfunc)
def _pseudorandom(x, mac=mac):
h = mac.copy()
h.update(x)
return map(ord, h.digest())
buf = []
for block in xrange(1, -(-keylen // mac.digest_size) + 1):
rv = u = _pseudorandom(salt + _pack_int(block))
for i in xrange(iterations - 1):
u = _pseudorandom(''.join(map(chr, u)))
rv = starmap(xor, izip(rv, u))
buf.extend(rv)
return ''.join(map(chr, buf))[:keylen]
def __hash__(self):
# ????????????????????
hashes = (hash(x) for x in self)
# ???operator?xor?? ???????? ?????0????
return functools.reduce(operator.xor, hashes, 0)
def __hash__(self):
# ????????????????????
hashes = (hash(x) for x in self)
# ???operator?xor?? ???????? ?????0????
return functools.reduce(operator.xor, hashes, 0)
def exec(self, proc: Processor):
self.proc = proc
self.args = map(self.expand, self.o_args) # load register values
val = reduce(self.operator, self.args) # apply operator
if operator is addc or operator is subc:
val += int(self.proc.external.carry)
proc.memory.set_register(self.register, val) # set result
if operator is operator.and_ or operator is operator.or_ or operator is operator.xor:
self.proc.set_carry(False)
# increment pc
self.proc.manager.next()
def lineReceived(self, line):
if not line.startswith('$'):
if self.ignore_invalid_sentence:
return
raise InvalidSentence("%r does not begin with $" % (line,))
# message is everything between $ and *, checksum is xor of all ASCII values of the message
strmessage, checksum = line[1:].strip().split('*')
message = strmessage.split(',')
sentencetype, message = message[0], message[1:]
dispatch = self.dispatch.get(sentencetype, None)
if (not dispatch) and (not self.ignore_unknown_sentencetypes):
raise InvalidSentence("sentencetype %r" % (sentencetype,))
if not self.ignore_checksum_mismatch:
checksum, calculated_checksum = int(checksum, 16), reduce(operator.xor, map(ord, strmessage))
if checksum != calculated_checksum:
raise InvalidChecksum("Given 0x%02X != 0x%02X" % (checksum, calculated_checksum))
handler = getattr(self, "handle_%s" % dispatch, None)
decoder = getattr(self, "decode_%s" % dispatch, None)
if not (dispatch and handler and decoder):
# missing dispatch, handler, or decoder
return
# return handler(*decoder(*message))
try:
decoded = decoder(*message)
except Exception, e:
raise InvalidSentence("%r is not a valid %s (%s) sentence" % (line, sentencetype, dispatch))
return handler(*decoded)
def pbkdf2( password, salt, itercount, keylen, hashfn = hashlib.sha1 ):
def pbkdf2_F( h, salt, itercount, blocknum ):
def prf( h, data ):
hm = h.copy()
try:
hm.update(bytearray(data))
except TypeError: #python 3 support
hm.update(bytes(data))
d = hm.digest()
return bytearray(d)
U = prf( h, salt + pack('>i',blocknum ) )
T = U
for i in range(2, itercount + 1):
U = prf( h, U )
T = starmap(xor, zip(T, U))
return T
digest_size = hashfn().digest_size
l = int(keylen / digest_size)
if keylen % digest_size != 0:
l += 1
h = hmac.new(bytes(password), None, hashfn )
T = bytearray()
for i in range(1, l+1):
tmp = pbkdf2_F( h, salt, itercount, i )
T.extend(tmp)
return T[0: keylen]
def keccak_f(state):
def round(A, RC):
W, H = state.W, state.H
rangeW, rangeH = state.rangeW, state.rangeH
lanew = state.lanew
zero = state.zero
# theta
C = [functools.reduce(xor, A[x]) for x in rangeW]
D = [0] * W
for x in rangeW:
D[x] = C[(x - 1) % W] ^ rol(C[(x + 1) % W], 1, lanew)
for y in rangeH:
A[x][y] ^= D[x]
# rho and pi
B = zero()
for x in rangeW:
for y in rangeH:
B[y % W][(2 * x + 3 * y) % H] = rol(A[x][y], RotationConstants[y][x], lanew)
# chi
for x in rangeW:
for y in rangeH:
A[x][y] = B[x][y] ^ ((~ B[(x + 1) % W][y]) & B[(x + 2) % W][y])
# iota
A[0][0] ^= RC
l = int(log(state.lanew, 2))
nr = 12 + 2 * l
for ir in range(nr):
round(state.s, RoundConstants[ir])
def lrc(data):
"""
Calc. LRC from data. Checksum
:param bytes|str data: Data from which LRC checksum should be computed
:return: 0x00 < Result < 0xFF
:rtype: int
"""
if isinstance(data, str):
data = data.encode(TERMINAL_DATA_ENCODING)
elif not isinstance(data, bytes):
raise TypeError("Cannot compute LRC of type {0}. Expect string or bytes.".format(str(type(data))))
return reduce(xor, [c for c in data]) if six.PY3 else reduce(xor, [ord(c) for c in data])
def get_track_cipher(self, track_id):
""" Get track-specific cipher from `track_id` """
track_md5 = get_md5(str(track_id).lstrip('-'))
key_parts = map(lambda v: array('B', v), ('g4el58wc0zvf9na1', track_md5[:16], track_md5[16:]))
blowfish_key = b''.join(chr(reduce(xor, x)) for x in zip(*key_parts))
IV = pack('B' * 8, *range(8))
def track_cipher():
return Blowfish.new(blowfish_key, mode=Blowfish.MODE_CBC, IV=IV)
return track_cipher
def test_xor_scalar(self):
self.check_array_scalar_op(operator.xor)
def test_rxor_scalar(self):
self.check_array_scalar_op(operator.xor, swap=True)
def test_xor_scalarzero(self):
self.check_array_scalarzero_op(operator.xor)