Saturday, October 22, 2016

encrypt and decrypt data using GOST 28147

1- install pygost library
$ sudo pip install pygost

2- below is the script to generate 32 bytes key and decrypt and encrypt file, save it as encryptgost.py

import pygost
import os
import sys
import base64
import re


if sys.argv[1] == "genkey":
    if os.path.isfile("gost.key") == True:
        print "gost.key file already exist, to generate a new key remove it first"
        sys.exit()
    key = os.urandom(32)
    f = open("gost.key", "w+")
    f.write(base64.b64encode(key))
    f.close()
elif sys.argv[1] == "enc":
    key = sys.argv[2]
    data = sys.argv[3]
  
    with open(key, "r") as f:
        key = base64.b64decode(f.read())
    with open(data, "r") as f1:
        encdata = pygost.gost28147.cfb_encrypt(key, f1.read(), iv='\x00\x00\x00\x00\x00\x00\x00\x00', sbox='Gost28147_CryptoProParamSetA', mesh=False)
    with open(data + ".enc", "w+") as f2:
        f2.write(encdata)
elif sys.argv[1] == "dec":
    key = sys.argv[2]
    data = sys.argv[3]
    datafile = re.sub(r"enc$", "dec", data)
  
    with open(key, "r") as f:
        key = base64.b64decode(f.read())
    with open(data, "r") as f1:
        decdata = pygost.gost28147.cfb_decrypt(key, f1.read(), iv='\x00\x00\x00\x00\x00\x00\x00\x00', sbox='Gost28147_CryptoProParamSetA', mesh=False)
    with open(datafile, "w+") as f2:
        f2.write(decdata)  



3- usage,

- generate key
$ python encryptgost.py genkey

contain of the key look something like
$ cat gost.key
HGPG2H4KLgE1VJHFhroK680+1T9P/95PsRGbp9L2fKA=


-encrypt data python encryptgost.py enc key filetoencypt
 $ python encryptgost.py enc gost.key topsec.doc

it will generate a new file with the same name and add .enc at the end of the file name
$ cat topsec.doc.enc
Κ6N*¯U0¬&c¼b

 -decrypt data python encryptgost.py dec key filetodecrypt
  $ python encryptgost.py dec gost.key topsec.doc.enc

it will generate a new file with the same name but change .enc to .dec of the file name 
$ cat topsec.doc.dec
document top secret

No comments:

Post a Comment