2 # PyGOST -- Pure Python GOST cryptographic functions library
3 # Copyright (C) 2015-2020 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, version 3 of the License.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 from codecs import getdecoder
18 from codecs import getencoder
19 from sys import version_info
22 xrange = range if version_info[0] == 3 else xrange
26 """ XOR of two strings
28 This function will process only shortest length of both strings,
29 ignoring remaining one.
31 mlen = min(len(a), len(b))
32 a, b, xor = bytearray(a), bytearray(b), bytearray(mlen)
33 for i in xrange(mlen):
38 _hexdecoder = getdecoder("hex")
39 _hexencoder = getencoder("hex")
45 return _hexdecoder(data)[0]
51 return _hexencoder(data)[0].decode("ascii")
55 """ Deserialize big-endian bytes into long number
57 :param bytes raw: binary string
58 :returns: deserialized long number
61 return int(hexenc(raw), 16)
64 def long2bytes(n, size=32):
65 """ Serialize long number into big-endian bytestring
67 :param long n: long number
68 :returns: serialized bytestring
71 res = hex(int(n))[2:].rstrip("L")
76 s = (size - len(s)) * b"\x00" + s
81 """ Modular multiplicative inverse
83 :returns: inverse number. -1 if it does not exist
85 Realization is taken from:
86 https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
89 # k^-1 = p - (-k)^-1 mod p
90 return n - modinvert(-a, n)
95 t, newt = newt, t - quotinent * newt
96 r, newr = newr, r - quotinent * newr