使用RSA Bouncy Castle加密/解密无法正常工作

时间:2013-03-05 23:52:29

标签: java encryption rsa bouncycastle

我正在尝试使用RSAEngine库在充气城堡加密/解密,密钥长度为2048位。我能够创建密钥,存储在不同的文件中并从文件中获取,但是当我解密图像时,它会产生一些我不知道解密文件没有正确显示的内容。文件创建正确,我认为问题在于加密和/或解密时的processBlock方法。加密的代码如下:

InputStream clearTextFile;
    FileOutputStream textFileProcessed=new FileOutputStream(fileName);
            //getKey is a method I implemented and works correctly
    RSAKeyParameters key=getKey(keyFileName);
    RSAEngine rsaEngine=new RSAEngine();
    rsaEngine.init(true,key);           
    clearTextFile=new FileInputStream(nameClearTextFile);
    byte[] bytesReaded;
    int nBytesReaded;
    int inputBlockSize=rsaEngine.getInputBlockSize();
    do
    {
        bytesReaded = new byte[inputBlockSize];
        nBytesReaded=clearTextFile.read(bytesReaded);
        if(nBytesReaded>-1)
        {       //This is for the last block if it's not 256 byte length
            if(nBytesReaded<inputBlockSize)
            {
                byte[] temp=new byte[nBytesReaded];
                for(int i=0;i<nBytesReaded;i++)
                {
                    temp[i]=bytesReaded[i];
                }
                byte[] encryptedText=rsaEngine.processBlock(temp,0,nBytesReaded);
                textFileProcessed.write(encryptedText);
            }
            else
            {
                byte[] encryptedText=rsaEngine.processBlock(bytesReaded,0,inputBlockSize);
                textFileProcessed.write(encryptedText); 
            }
        }
    }while(nBytesReaded>-1);
    textFileProcessed.flush();
    textFileProcessed.close();
    textFileProcessed.close();

并解密:

InputStream encryptedTextFile=new FileInputStream(nameOfFile);
    OutputStream decryptedTextFile=new FileOutputStream(nameOfFile);
    RSAKeyParameters key=getKey(nameKeyFile);
    RSAEngine rsaEngine=new RSAEngine();
    rsaEngine.init(false,key);
    byte[] bytesReaded;
    int nBytesReaded;
    int inputBlockSize=rsaEngine.getInputBlockSize();
    do
    {
        bytesLeidos = new byte[inputBlockSize];
        nBytesReaded=encryptedTextFile.read(bytesReaded);
        if(nBytesReaded>-1)
        {
                byte[] decryptedText=rsaEngine.processBlock(bytesReaded,0,inputBlockSize);          
                decryptedTextFile.write(decryptedText);                 
        }
    }while(nBytesReaded>-1);
    decryptedTextFile.flush();
    decryptedTextFile.close();
    encryptedTextFile.close();

提前致谢

2 个答案:

答案 0 :(得分:1)

RSAEngine不添加填充,因此您将丢失数据块中的任何前导零。您还需要使用其中一种编码模式。

我建议使用对称密钥算法,只使用RSA加密对称密钥。它会更快,并且取决于您的数据,也更安全。

此致

大卫

答案 1 :(得分:0)

我认为您需要更改此行:

   if(nBytesReaded>1)

到这个

   if(nBytesReaded>-1)

在decypt部分改变这一点,也许:

rsaEngine.init(false,clave);

到这个

rsaEngine.init(false,key);

但可能会有更多。如果最后一个块不是全尺寸,则您不会加密整个输入。

相关问题