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/>.
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, mode):
36 key = curve.exp(prv, pub[0], pub[1])
37 key = curve.exp(curve.cofactor * ukm, key[0], key[1])
38 return pub_marshal(key, mode)
41 def kek_34102001(curve, prv, pub, ukm):
42 """ Key agreement (34.10-2001, 34.11-94)
44 :param GOST3410Curve curve: curve to use
45 :param long prv: private key
46 :param pub: public key
47 :type pub: (long, long)
48 :param long ukm: user keying material, VKO-factor
49 :returns: Key Encryption Key (shared key)
50 :rtype: bytes, 32 bytes
52 Shared Key Encryption Key computation is based on
53 :rfc:`4357` VKO GOST R 34.10-2001 with little-endian
57 kek(curve, prv, pub, ukm, mode=2001),
58 sbox="id-GostR3411-94-CryptoProParamSet",
62 def kek_34102012256(curve, prv, pub, ukm=1, mode=2012):
63 """ Key agreement (34.10-2012, 34.11-2012 256 bit)
65 :param GOST3410Curve curve: curve to use
66 :param long prv: private key
67 :param pub: public key
68 :type pub: (long, long)
69 :param long ukm: user keying material, VKO-factor
70 :returns: Key Encryption Key (shared key)
71 :rtype: bytes, 32 bytes
73 Shared Key Encryption Key computation is based on
74 :rfc:`7836` VKO GOST R 34.10-2012.
76 return GOST34112012256(kek(curve, prv, pub, ukm, mode=mode)).digest()
79 def kek_34102012512(curve, prv, pub, ukm=1):
80 """ Key agreement (34.10-2012, 34.11-2012 512 bit)
82 :param GOST3410Curve curve: curve to use
83 :param long prv: private key
84 :param pub: public key
85 :type pub: (long, long)
86 :param long ukm: user keying material, VKO-factor
87 :returns: Key Encryption Key (shared key)
88 :rtype: bytes, 32 bytes
90 Shared Key Encryption Key computation is based on
91 :rfc:`7836` VKO GOST R 34.10-2012.
93 return GOST34112012512(kek(curve, prv, pub, ukm, mode=2012)).digest()