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, mask=None):
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])
41 key = curve.exp(mask, key[0], key[1])
42 return pub_marshal(key)
45 def kek_34102001(curve, prv, pub, ukm):
46 """Key agreement (34.10-2001, 34.11-94)
48 :param GOST3410Curve curve: curve to use
49 :param long prv: private key
50 :param pub: public key
51 :type pub: (long, long)
52 :param long ukm: user keying material, VKO-factor
53 :returns: Key Encryption Key (shared key)
54 :rtype: bytes, 32 bytes
56 Shared Key Encryption Key computation is based on
57 :rfc:`4357` VKO GOST R 34.10-2001 with little-endian
61 kek(curve, prv, pub, ukm),
62 sbox="id-GostR3411-94-CryptoProParamSet",
66 def kek_34102012256(curve, prv, pub, ukm=1):
67 """Key agreement (34.10-2012, 34.11-2012 256 bit)
69 :param GOST3410Curve curve: curve to use
70 :param long prv: private key
71 :param pub: public key
72 :type pub: (long, long)
73 :param long ukm: user keying material, VKO-factor
74 :returns: Key Encryption Key (shared key)
75 :rtype: bytes, 32 bytes
77 Shared Key Encryption Key computation is based on
78 :rfc:`7836` VKO GOST R 34.10-2012.
80 return GOST34112012256(kek(curve, prv, pub, ukm)).digest()
83 def kek_34102012512(curve, prv, pub, ukm=1):
84 """Key agreement (34.10-2012, 34.11-2012 512 bit)
86 :param GOST3410Curve curve: curve to use
87 :param long prv: private key
88 :param pub: public key
89 :type pub: (long, long)
90 :param long ukm: user keying material, VKO-factor
91 :returns: Key Encryption Key (shared key)
92 :rtype: bytes, 32 bytes
94 Shared Key Encryption Key computation is based on
95 :rfc:`7836` VKO GOST R 34.10-2012.
97 return GOST34112012512(kek(curve, prv, pub, ukm)).digest()