On Friday, September 14, 2018 at 5:41:45 AM UTC-4, hanlul...@gmail.com 
wrote:
>
> Hi,everyone. I need your help.
> I had problem when used stream cipher to encrypt  and decrypt file.
> I encrypted a file that is 2K, but it would become 3K when I decrypted the 
> cipher .
> I think the problem is that I maybe incorrectly use ifstream or ofstream?
> The following is my code.
> #include<chacha.h> //包含ChaCha20算法的头文件
> #include<iostream>//使用cin、cout
> #include<osrng.h> //使用AutoSeededRandomPool算法
> #include<secblock.h> //使用SecByteBlock
> #include<string>//使用string
> #include<fstream>//使用ifstream、ofstream
> using namespace std;//std是C++的命名空间
> using namespace CryptoPP;//CryptoPP是Cryptopp库的命名空间
> void EncOrDecFile(const string& srcfile,StreamTransformation& encdec,const 
> string& desfile);
> int main()
> {
> ChaCha20::Encryption enc;//定义加密对象
> ChaCha20::Decryption dec;//定义解密对象
> //定义一个随机数发生器,用于产生随机的密钥Key和初始向量IV
> AutoSeededRandomPool prng;
> //动态申请空间以存储接下来生成的密钥key和初始向量iv
> SecByteBlock key(enc.DefaultKeyLength()),iv(enc.DefaultIVLength());
> //产生随机的key和iv
> prng.GenerateBlock(key,key.size());
> prng.GenerateBlock(iv,iv.size());
> //加密和解密准备
> enc.SetKeyWithIV(key,key.size(),iv,iv.size());//设置加密key和iv
> dec.SetKeyWithIV(key,key.size(),iv,iv.size());//设置解密key和iv
> EncOrDecFile("stream_02.cpp",enc,"cipher.txt");
> EncOrDecFile("cipher.txt",dec,"recover.txt");
> return 0;
> }
> //参数srcfile:待加密或解密的文件
> //参数encdec:使用的流密码算法
> //参数desfile:存放加密或解密结果的文件   
> void EncOrDecFile(const string& srcfile,StreamTransformation& encdec,const 
> string& desfile)
> {//用流密码对象encdec实现对文件srcfile的加密或解密操作,并将操作的结果存放于文件desfile
> ifstream infile(srcfile,ios_base::binary);
> ofstream outfile(desfile,ios_base::binary);
> if(!infile || !outfile)
> {
> cout << "文件打开失败" << endl;
> return ;
> }
> int iread;
> SecByteBlock readstr(1024);
> while(infile)
> {//文件内容读取没有结束
> infile.read((char*)&readstr[0],readstr.size());
> iread=infile.gcount();
> iread = iread < readstr.size() ? iread : readstr.size();
> encdec.ProcessString(&readstr[0],iread);
> outfile.write((char*)&readstr[0],readstr.size());
> }
> infile.close();//关闭文件
> outfile.close();//关闭文件
> }
>

From a quick reading of the code above it looks like the issue with the way 
the streams are being used.

You might want to checkout https://www.cryptopp.com/wiki/Chacha20 and 
https://www.cryptopp.com/wiki/Pumping_Data .

Jeff

-- 
You received this message because you are subscribed to "Crypto++ Users". More 
information about Crypto++ and this group is available at 
http://www.cryptopp.com and 
http://groups.google.com/forum/#!forum/cryptopp-users.
--- 
You received this message because you are subscribed to the Google Groups 
"Crypto++ Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to cryptopp-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to