如何使用ElGamal加密/解密文本文件 [英] How to encrypt/decrypt text files using ElGamal

查看:120
本文介绍了如何使用ElGamal加密/解密文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ElGamal对文本文件进行加密和解密,但似乎无法使其正常工作. 我有一组范围从1kb-1mb的文本文件,并且我使用512位作为我的密钥大小.我已经知道,就像RSA一样,ELGamal不能加密的值超过其模数,因此,作为我的初始解决方案,我决定将每个文件分成多个块(小于其模数),以便能够对其进行加密幸运的是,这些解决方案适用于加密.我的问题是,当我尝试解密它时,生成的输出不是我期望看到的实际输出.我不知道是什么原因造成的,我真的需要在几天内找到解决方案.

I'm trying to encrypt and decrypt text files using ElGamal for my study but it seems that I could not make it work correctly. I have a group of text files ranging from 1kb - 1mb, and I'm using 512bit for my key size. I already know that just like RSA, ELGamal can't encrypt values more than its modulus so as my initial solution, I've decided to divide each file into chunks(which is smaller than its modulus) for me to be able to encrypt it and luckily these solution works for encryption. My problem is this,when I tried to decrypt it, outputs that has been generated is not the actual output I'm expecting to see. I don't know what's the cause of my problem and I really need to find a solution within few days.

为了清楚起见,我将向您展示一些代码片段.

I'll be showing you some of my code snippets just to make it clear.

我已经用以下内容生成了密钥对

I had generated my keypair with the following

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ElGamal", "BC";
keyGen.initialize(512);

我通过致电

public static void encryptFile(String srcFileName, String destFileName, PublicKey key) throws Exception
{
    encryptDecryptFile(srcFileName,destFileName, key, Cipher.ENCRYPT_MODE);
}

然后我通过调用

public static void decryptFile(String srcFileName, String destFileName, PrivateKey key) throws Exception
{
    encryptDecryptFile(srcFileName,destFileName, key, Cipher.DECRYPT_MODE);
}

这是cryptoDecryptFile(..)方法的定义

Here's the definition of encryptDecryptFile(..) method

public static void encryptDecryptFile(String srcFileName, String destFileName, Key key, int cipherMode) throws Exception
    {
        OutputStream outputWriter = null;
        InputStream inputReader = null;
        try
        {
            Cipher cipher = Cipher.getInstance("ElGamal/None/NoPadding", "BC"");
            String textLine = null;
    //buffer(my chunks) depends wether it is encyption or decryption
            byte[] buf = (cipherMode == Cipher.ENCRYPT_MODE? new byte[50] : new byte[64]);
            int bufl;
            // init the Cipher object for Encryption...
            cipher.init(cipherMode, key);

            // start FileIO
            outputWriter = new FileOutputStream(destFileName);
            inputReader = new FileInputStream(srcFileName);
            while ( (bufl = inputReader.read(buf)) != -1)
            {
                byte[] encText = null;
                if (cipherMode == Cipher.ENCRYPT_MODE)
                {
                      encText = encrypt(copyBytes(buf,bufl),(PublicKey)key);
                }
                else
                {
                    if (_log.isDebugEnabled())
                    {
                        System.out.println("buf = " + new String(buf));
                    }
                    encText = decrypt(copyBytes(buf,bufl),(PrivateKey)key);
                }
                outputWriter.write(encText);
                if (_log.isDebugEnabled())
                {
                    System.out.println("encText = " + new String(encText));
                }
            }
            outputWriter.flush();

        }
        catch (Exception e)
        {
            _log.error(e,e);
            throw e;
        }
        finally
        {
            try
            {
                if (outputWriter != null)
                {
                    outputWriter.close();
                }
                if (inputReader != null)
                {
                    inputReader.close();
                }
            }
            catch (Exception e)
            {
                // do nothing...
            } // end of inner try, catch (Exception)...
        }
    }

对于copyBytes:

For copyBytes:

public static byte[] copyBytes(byte[] arr, int length)
{
    byte[] newArr = null;
    if (arr.length == length)
    {
        newArr = arr;
    }
    else
    {
        newArr = new byte[length];
        for (int i = 0; i < length; i++)
        {
            newArr[i] = (byte) arr[i];
        }
    }
    return newArr;
}

对于entpt(...)

For encypt(...)

    public static byte[] encrypt(byte[] text, PublicKey key) throws Exception
{
    byte[] cipherText = null;
    try
    {

        Cipher cipher = Cipher.getInstance("ElGamal/None/NoPadding", "BC"");
        if (_log.isDebugEnabled())
        {
            _log.debug("\nProvider is: " + cipher.getProvider().getInfo());
            _log.debug("\nStart encryption with public key");
        }

        // encrypt the plaintext using the public key
        cipher.init(Cipher.ENCRYPT_MODE, key);
        cipherText = cipher.doFinal(text);
    }
    catch (Exception e)
    {
        _log.error(e, e);
        throw e;
    }
    return cipherText;
}

然后解密(..)

   public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception
    {
        byte[] dectyptedText = null;
        try
        {
            // decrypt the text using the private key
            Cipher cipher = Cipher.getInstance("ElGamal/None/NoPadding", "BC"");
              cipher.init(Cipher.DECRYPT_MODE, key);
            dectyptedText = cipher.doFinal(text);
        }
        catch (Exception e)
        {
            _log.error(e, e);
            throw e;
        }
        return dectyptedText;

    }

Aviran Mondo的原始代码

Original code by Aviran Mondo

我认为这就是您所需要的,只是告诉我是否要查看完整的源代码. 谢谢,

I thinks that's all what you need, just tell me if you want to see the full source code. Thanks,

推荐答案

我终于有了解决方案,无论如何,我还是把它放在这里,以防万一有人也遇到我同样的问题.您要做的就是替换

I finally have the solution, anyway I'll just put it here just in case someone also got the same problem with me. All you have to do is to replace

byte[] buf = (cipherMode == Cipher.ENCRYPT_MODE? new byte[50] : new byte[64]);

在cryptoDecryptFile(..)方法中,

in encryptDecryptFile(..) method with

byte[] buf = (cipherMode == Cipher.ENCRYPT_MODE? new byte[50] : new byte[128]);

因为具有512密钥大小的ElGamal在加密50b时会产生128b.我希望这足够清楚.

since ElGamal with 512 key size produces 128b when encrypting 50b. I hope this is clear enough.

这篇关于如何使用ElGamal加密/解密文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆