3

我正在尝试在充气城堡使用 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();

提前致谢

4

2 回答 2

1

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

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

问候,

大卫

于 2013-03-07T12:38:53.763 回答
0

我认为您需要更改此行:

   if(nBytesReaded>1)

对此

   if(nBytesReaded>-1)

并在 decypt 部分更改它,也许是:

rsaEngine.init(false,clave);

对此

rsaEngine.init(false,key);

但可能还有更多。如果最后一个块不是完整大小,则您不会加密整个输入。

于 2013-03-06T00:08:33.733 回答