]> Cypherpunks.ru repositories - pygost.git/blobdiff - pygost/gost341194.py
Separate 34.11-94 PBKDF2 function could be useful
[pygost.git] / pygost / gost341194.py
index adc0925f6e53e32cbbb909dfc978f9b08dd87530..0a71518cb445d6c733eb2b24237dcb8409d3420c 100644 (file)
@@ -29,8 +29,10 @@ from pygost.gost28147 import encrypt
 from pygost.gost28147 import ns2block
 from pygost.gost28147 import validate_sbox
 from pygost.iface import PEP247
+from pygost.utils import bytes2long
 from pygost.utils import hexdec
 from pygost.utils import hexenc
+from pygost.utils import long2bytes
 from pygost.utils import strxor
 from pygost.utils import xrange
 
@@ -183,3 +185,36 @@ class GOST341194(PEP247):
 
 def new(data=b"", sbox=DEFAULT_SBOX):
     return GOST341194(data, sbox)
+
+
+# This implementation is based on Python 3.5.2 source code's one.
+# PyGOST does not register itself in hashlib anyway, so use it instead.
+def pbkdf2(password, salt, iterations, dklen):
+    """PBKDF2 implementation for GOST R 34.11-94
+
+    Based on http://tc26.ru/methods/containers_v1/Addition_to_PKCS5_v1_0.pdf
+    """
+    inner = GOST341194(sbox="GostR3411_94_CryptoProParamSet")
+    outer = GOST341194(sbox="GostR3411_94_CryptoProParamSet")
+    password = password + b"\x00" * (inner.block_size - len(password))
+    inner.update(strxor(password, len(password) * b"\x36"))
+    outer.update(strxor(password, len(password) * b"\x5C"))
+
+    def prf(msg):
+        icpy = inner.copy()
+        ocpy = outer.copy()
+        icpy.update(msg)
+        ocpy.update(icpy.digest())
+        return ocpy.digest()
+
+    dkey = b''
+    loop = 1
+    while len(dkey) < dklen:
+        prev = prf(salt + long2bytes(loop, 4))
+        rkey = bytes2long(prev)
+        for _ in xrange(iterations - 1):
+            prev = prf(prev)
+            rkey ^= bytes2long(prev)
+        loop += 1
+        dkey += long2bytes(rkey, inner.digest_size)
+    return dkey[:dklen]