2 # PyGOST -- Pure Python GOST cryptographic functions library
3 # Copyright (C) 2015-2022 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/>.
16 """Key derivation functions, Р 50.1.113-2016, Р 1323565.1.020-2018
21 from pygost.gost3410_vko import kek_34102012256
22 from pygost.gost3410_vko import kek_34102012512
23 from pygost.gost34112012256 import GOST34112012256
24 from pygost.utils import bytes2long
25 from pygost.utils import long2bytes
28 def kdf_gostr3411_2012_256(key, label, seed):
29 """KDF_GOSTR3411_2012_256
31 :param bytes key: initial key
32 :param bytes label: label
33 :param bytes seed: seed
38 msg=b"".join((b"\x01", label, b"\x00", seed, b"\x01\x00")),
39 digestmod=GOST34112012256,
43 def kdf_tree_gostr3411_2012_256(key, label, seed, keys, i_len=1):
44 """KDF_TREE_GOSTR3411_2012_256
46 :param bytes key: initial key
47 :param bytes label: label
48 :param bytes seed: seed
49 :param int keys: number of generated keys
50 :param int i_len: length of iterations value (called "R")
51 :returns: list of 256-bit keys
54 _len = long2bytes(keys * 32 * 8, size=1)
56 keymat.append(hmac.new(
58 msg=b"".join((long2bytes(i + 1, size=i_len), label, b"\x00", seed, _len)),
59 digestmod=GOST34112012256,
64 def keg(curve, prv, pub, h):
65 """Export key generation (Р 1323565.1.020-2018)
67 :param GOST3410Curve curve: curve to use
68 :param long prv: private key
69 :param pub: public key
70 :type pub: (long, long)
71 :param bytes h: "h"-value, 32 bytes
74 raise ValueError("h must be 32 bytes long")
75 ukm = bytes2long(h[:16])
78 if curve.point_size == 64:
79 return kek_34102012512(curve, prv, pub, ukm)
80 k_exp = kek_34102012256(curve, prv, pub, ukm)
81 return b"".join(kdf_tree_gostr3411_2012_256(k_exp, b"kdf tree", h[16:24], 2))