@@ -48,8 +48,36 @@ limitations under the License.
4848#include < unistd.h>
4949#endif
5050
51+ #include " aes.h"
52+ #include " modes.h"
53+ #include " cryptlib.h"
54+ #include " filters.h"
55+ #include " secblock.h"
56+
5157namespace tensorflow {
5258
59+ byte key[CryptoPP::AES::DEFAULT_KEYLENGTH] = {0x8b , 0x8b , 0x8b , 0x8b , 0x8b , 0x8b ,
60+ 0x8b , 0x8b , 0x8b , 0x8b , 0x8b , 0x8b ,
61+ 0x8b , 0x8b , 0x8b , 0x8b };
62+ byte iv[CryptoPP::AES::BLOCKSIZE] = {0x37 , 0x37 , 0x37 , 0x37 , 0x37 , 0x37 , 0x37 , 0x37 ,
63+ 0x37 , 0x37 , 0x37 , 0x37 , 0x37 , 0x37 , 0x37 , 0x37 };
64+
65+ Status decryptCBC (std::string cipher, byte key[], int keySize, byte iv[], std::string& recovered) {
66+ // Decryption
67+ try {
68+ CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption d;
69+ d.SetKeyWithIV (key, keySize, iv);
70+ // The StreamTransformationFilter removes
71+ // padding as required.
72+ CryptoPP::StringSource s (cipher, true ,
73+ new CryptoPP::StreamTransformationFilter (
74+ d, new CryptoPP::StringSink (recovered)));
75+ } catch (const CryptoPP::Exception& e) {
76+ return errors::DataLoss (" Can't decrypt binary proto" );
77+ }
78+ return Status::OK ();
79+ }
80+
5381// 128KB copy buffer
5482constexpr size_t kCopyFileBufferSize = 128 * 1024 ;
5583
@@ -541,14 +569,23 @@ Status WriteBinaryProto(Env* env, const string& fname,
541569
542570Status ReadBinaryProto (Env* env, const string& fname,
543571 protobuf::MessageLite* proto) {
544- std::unique_ptr<RandomAccessFile> file;
545- TF_RETURN_IF_ERROR (env->NewRandomAccessFile (fname, &file));
546- std::unique_ptr<FileStream> stream (new FileStream (file.get ()));
572+ // std::unique_ptr<RandomAccessFile> file;
573+ // TF_RETURN_IF_ERROR(env->NewRandomAccessFile(fname, &file));
574+ // std::unique_ptr<FileStream> stream(new FileStream(file.get()));
575+
576+ using google::protobuf::io::ArrayInputStream;
577+ string fileData;
578+ TF_RETURN_IF_ERROR (ReadFileToString (env, fname, &fileData));
579+ string plain;
580+ TF_RETURN_IF_ERROR (decryptCBC (fileData, key, sizeof (key), iv, plain));
581+ std::unique_ptr<ArrayInputStream> stream (
582+ new ArrayInputStream (plain.data (), plain.length ()));
583+
547584 protobuf::io::CodedInputStream coded_stream (stream.get ());
548585
549586 if (!proto->ParseFromCodedStream (&coded_stream) ||
550587 !coded_stream.ConsumedEntireMessage ()) {
551- TF_RETURN_IF_ERROR (stream->status ());
588+ // TF_RETURN_IF_ERROR(stream->status());
552589 return errors::DataLoss (" Can't parse " , fname, " as binary proto" );
553590 }
554591 return Status::OK ();
0 commit comments