2 # PyGOST -- Pure Python GOST cryptographic functions library
3 # Copyright (C) 2015-2023 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 agreement functions, VKO GOST R 34.10-2001/2012
19 from pygost.gost3410 import pub_marshal
20 from pygost.gost34112012256 import GOST34112012256
21 from pygost.gost34112012512 import GOST34112012512
22 from pygost.gost341194 import GOST341194
23 from pygost.utils import bytes2long
26 def ukm_unmarshal(ukm):
27 """Unmarshal UKM value
29 :type ukm: little-endian bytes
32 return bytes2long(ukm[::-1])
35 def kek(curve, prv, pub, ukm):
36 if not curve.contains(pub):
37 raise ValueError("pub is not on the curve")
38 key = curve.exp(prv, pub[0], pub[1])
39 key = curve.exp(curve.cofactor * ukm, key[0], key[1])
40 return pub_marshal(key)
43 def kek_34102001(curve, prv, pub, ukm):
44 """Key agreement (34.10-2001, 34.11-94)
46 :param GOST3410Curve curve: curve to use
47 :param long prv: private key
48 :param pub: public key
49 :type pub: (long, long)
50 :param long ukm: user keying material, VKO-factor
51 :returns: Key Encryption Key (shared key)
52 :rtype: bytes, 32 bytes
54 Shared Key Encryption Key computation is based on
55 :rfc:`4357` VKO GOST R 34.10-2001 with little-endian
59 kek(curve, prv, pub, ukm),
60 sbox="id-GostR3411-94-CryptoProParamSet",
64 def kek_34102012256(curve, prv, pub, ukm=1):
65 """Key agreement (34.10-2012, 34.11-2012 256 bit)
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 long ukm: user keying material, VKO-factor
72 :returns: Key Encryption Key (shared key)
73 :rtype: bytes, 32 bytes
75 Shared Key Encryption Key computation is based on
76 :rfc:`7836` VKO GOST R 34.10-2012.
78 return GOST34112012256(kek(curve, prv, pub, ukm)).digest()
81 def kek_34102012512(curve, prv, pub, ukm=1):
82 """Key agreement (34.10-2012, 34.11-2012 512 bit)
84 :param GOST3410Curve curve: curve to use
85 :param long prv: private key
86 :param pub: public key
87 :type pub: (long, long)
88 :param long ukm: user keying material, VKO-factor
89 :returns: Key Encryption Key (shared key)
90 :rtype: bytes, 32 bytes
92 Shared Key Encryption Key computation is based on
93 :rfc:`7836` VKO GOST R 34.10-2012.
95 return GOST34112012512(kek(curve, prv, pub, ukm)).digest()