2 # PyGOST -- Pure Python GOST cryptographic functions library
3 # Copyright (C) 2015-2018 Sergey Matveev <stargrave@stargrave.org>
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 from codecs import getdecoder
19 from codecs import getencoder
20 from sys import version_info
23 xrange = range if version_info[0] == 3 else xrange # pylint: disable=redefined-builtin
27 """ XOR of two strings
29 This function will process only shortest length of both strings,
30 ignoring remaining one.
32 mlen = min(len(a), len(b))
33 a, b, xor = bytearray(a), bytearray(b), bytearray(mlen)
34 for i in xrange(mlen):
39 _hexdecoder = getdecoder("hex")
40 _hexencoder = getencoder("hex")
46 return _hexdecoder(data)[0]
52 return _hexencoder(data)[0].decode("ascii")
56 """ Deserialize big-endian bytes into long number
58 :param bytes raw: binary string
59 :returns: deserialized long number
62 return int(hexenc(raw), 16)
65 def long2bytes(n, size=32):
66 """ Serialize long number into big-endian bytestring
68 :param long n: long number
69 :returns: serialized bytestring
72 res = hex(int(n))[2:].rstrip("L")
77 s = (size - len(s)) * b"\x00" + s
82 """ Modular multiplicative inverse
84 :returns: inverse number. -1 if it does not exist
86 Realization is taken from:
87 https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
90 # k^-1 = p - (-k)^-1 mod p
91 return n - modinvert(-a, n)
96 t, newt = newt, t - quotinent * newt
97 r, newr = newr, r - quotinent * newr