Beispiel #1
0
void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout)
{
    std::vector<unsigned char> key = ParseHex(hexkey);
    std::vector<unsigned char> iv = ParseHex(hexiv);
    std::vector<unsigned char> in = ParseHex(hexin);
    std::vector<unsigned char> correctout = ParseHex(hexout);
    std::vector<unsigned char> realout(in.size() + AES_BLOCKSIZE);

    // Encrypt the plaintext and verify that it equals the cipher
    AES256CBCEncrypt enc(key.data(), iv.data(), pad);
    int size = enc.Encrypt(in.data(), in.size(), realout.data());
    realout.resize(size);
    BOOST_CHECK(realout.size() == correctout.size());
    BOOST_CHECK_MESSAGE(realout == correctout, HexStr(realout) + std::string(" != ") + hexout);

    // Decrypt the cipher and verify that it equals the plaintext
    std::vector<unsigned char> decrypted(correctout.size());
    AES256CBCDecrypt dec(key.data(), iv.data(), pad);
    size = dec.Decrypt(correctout.data(), correctout.size(), decrypted.data());
    decrypted.resize(size);
    BOOST_CHECK(decrypted.size() == in.size());
    BOOST_CHECK_MESSAGE(decrypted == in, HexStr(decrypted) + std::string(" != ") + hexin);

    // Encrypt and re-decrypt substrings of the plaintext and verify that they equal each-other
    for(std::vector<unsigned char>::iterator i(in.begin()); i != in.end(); ++i)
    {
        std::vector<unsigned char> sub(i, in.end());
        std::vector<unsigned char> subout(sub.size() + AES_BLOCKSIZE);
        int _size = enc.Encrypt(sub.data(), sub.size(), subout.data());
        if (_size != 0)
        {
            subout.resize(_size);
            std::vector<unsigned char> subdecrypted(subout.size());
            _size = dec.Decrypt(subout.data(), subout.size(), subdecrypted.data());
            subdecrypted.resize(_size);
            BOOST_CHECK(decrypted.size() == in.size());
            BOOST_CHECK_MESSAGE(subdecrypted == sub, HexStr(subdecrypted) + std::string(" != ") + HexStr(sub));
        }
    }
}
Beispiel #2
0
/*static*/ bool SkBitmapHasher::ComputeDigestInternal(const SkBitmap& bitmap,
                                                      SkHashDigest *result) {
    size_t pixelBufferSize = bitmap.width() * bitmap.height() * 4;
    size_t totalBufferSize = pixelBufferSize + 2 * sizeof(uint32_t);

    SkAutoMalloc bufferManager(totalBufferSize);
    char *bufferStart = static_cast<char *>(bufferManager.get());
    SkMemoryWStream out(bufferStart, totalBufferSize);

    // start with the x/y dimensions
    write_int_to_buffer(SkToU32(bitmap.width()), &out);
    write_int_to_buffer(SkToU32(bitmap.height()), &out);

    // add all the pixel data
    SkAutoTDelete<SkImageEncoder> enc(CreateARGBImageEncoder());
    if (!enc->encodeStream(&out, bitmap, SkImageEncoder::kDefaultQuality)) {
        return false;
    }

    *result = SkCityHash::Compute64(bufferStart, totalBufferSize);
    return true;
}
Beispiel #3
0
int main(int argc, char const *argv[])
{
    if(argc < 3)
    {
        cout << "Usage: encryptor InputFileName OutputFileName" << endl << "Terminating..." << endl;
        return 0;
    }
    
    //Text hiding method by guestgulkan on cplusplus forum
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
    DWORD mode = 0;
    GetConsoleMode(hStdin, &mode);
    SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));

    string key;
    string input;
    string output;
    
    FileHandler inputFile(true);
    if(!inputFile.setFileName(argv[1]))
    {
        return 0;
    }
    
    FileHandler outputFile(false);
    outputFile.setFileName(argv[2]);

    cout << "Please enter your session key:" << endl;
    getline(cin, key);

    input = *inputFile.get();

    Encryptor enc(key, input);

    output = enc.crypt();

    outputFile.write(output);
    return 0;
}
Beispiel #4
0
int main(int argc, char **argv) {
    if (argc > 1 && strcmp(argv[1], "-n") == 0) {
        cpu_force_no_simd( );
    }

    /* Read 1080p UYVY422 frames on stdin. Dump M-JPEG stream on stdout. */
    RawFrame frame(1920, 1080, RawFrame::CbYCrY8422);
    Mjpeg422Encoder enc(1920, 1080);
    Mjpeg422Decoder dec(1920, 1080);

    ssize_t ret;
    std::string comment;


    for (;;) {
        ret = frame.read_from_fd(STDIN_FILENO);

        if (ret < 0) {
            perror("frame.read_from_fd");
            exit(1);
        } else if (ret == 0) {
            break;
        } else {
            enc.set_comment("Hello JPEG world!");
            enc.encode(&frame);
            RawFrame *out = dec.decode(enc.get_data( ), enc.get_data_size( ));

            comment = "                      ";
            dec.get_comment(comment);
            fprintf(stderr, "comment: %s\n", comment.c_str( ));

            if (out->write_to_fd(STDOUT_FILENO) < 0) {
                perror("write_to_fd");
                break;
            }
            delete out;
        }            
    }
}
Beispiel #5
0
int main () {
  enable_uart(25);
  initENC();
  initservos(625,ON,ON);
  initPWM10();
  initADC();
  initcommsunit();
  SetDir('B',0,'O');
  SetDir('B',1,'O');
  SetDir('B',2,'O');
  SetDir('B',3,'O');
  SetDir('B',4,'I');
  SetDir('B',5,'I');
  uprintf("Type INIT <enter> to begin\r");
  while(strncmp(dumb,"INIT",4) == 1) {
    uscanf(dumb,10,ON);
  }
  //uprintf("AVR Initalized\r");
  op = 1;
  while (op == 1) {
    uscanf(ReceiveStr,50,ON);
    if(strncmp(ReceiveStr,"Forward",7) == 0) {Forward();}
	if(strncmp(ReceiveStr,"Backward",8) == 0) {Backward();}
	if(strncmp(ReceiveStr,"SpinL",5) == 0) {SpinL();}
	if(strncmp(ReceiveStr,"SpinR",5) == 0) {SpinR();}
	if(strncmp(ReceiveStr,"TurnL",5) == 0) {TurnL();}
	if(strncmp(ReceiveStr,"TurnR",5) == 0) {TurnR();}
	if(strncmp(ReceiveStr,"Stop",4) == 0) {Stop();}
    if(strncmp(ReceiveStr,"Tservop",7) == 0) {tservop();}
    if(strncmp(ReceiveStr,"Pservop",7) == 0) {pservop();}
    if(strncmp(ReceiveStr,"LGH",3) == 0) {lgh();}
    if(strncmp(ReceiveStr,"SNR",3) == 0) {snr();}
    if(strncmp(ReceiveStr,"BMP",3) == 0) {bmp();}
	if(strncmp(ReceiveStr,"ENC",3) == 0) {enc();}
	if(strncmp(ReceiveStr,"DISABLE",7) == 0) {op = 0;}
  }
  uprintf("Disaled\r");
  while (1) {}
}
Beispiel #6
0
bool Use_StreamCipher(_Stream_Cipher_Parameters_){
	
	if(	key == NULL ||
		plain == NULL ||
		cipher == NULL ||
		key_len == 0 ||
		key_len != AlgType::DEFAULT_KEYLENGTH ||
		plain_len == 0 ||
		cipher_len == 0 ||
		iv == NULL ||
		iv_len == 0
	) return false;
	
	if(direct){
		AlgType::Encryption enc(key,key_len,iv);
		enc.ProcessData(cipher,plain,cipher_len);
	}else{
		AlgType::Decryption dec(key,key_len,iv);
		dec.ProcessData(plain,cipher,plain_len);
	}
	return true;
};
Beispiel #7
0
const bool Decode(const std::string &encoded, std::vector<unsigned char> &data)
{

	std::string::size_type pos=0;
	unsigned char byte;
	int bytepart=0;
	std::string enc(encoded);

	// make upper case lower case
	for(std::string::iterator i=enc.begin(); i!=enc.end(); i++)
	{
		if((*i)>=65 && (*i)<71)
		{
			(*i)=(*i)+32;
		}
	}

	data.reserve(enc.size()/2);
	
	pos=enc.find_first_of(hexchars);

	while(pos!=std::string::npos)
	{
		if(bytepart==0)
		{
			byte=(hexchars.find(enc[pos]) << 4) & 0xF0;
			bytepart=1;
		}
		else
		{
			byte|=hexchars.find(enc[pos]) & 0x0F;
			data.push_back(byte);
			bytepart=0;
		}
		pos=enc.find_first_of(hexchars,pos+1);
	}
	return true;
}
Beispiel #8
0
      Test::Result run_one_test(const std::string& algo, const VarMap& vars) override
         {
         const std::vector<uint8_t> key      = get_req_bin(vars, "Key");
         const std::vector<uint8_t> nonce    = get_opt_bin(vars, "Nonce");
         const std::vector<uint8_t> input    = get_req_bin(vars, "In");
         const std::vector<uint8_t> expected = get_req_bin(vars, "Out");

         Test::Result result(algo);

         std::unique_ptr<Botan::Cipher_Mode> enc(Botan::get_cipher_mode(algo, Botan::ENCRYPTION));
         std::unique_ptr<Botan::Cipher_Mode> dec(Botan::get_cipher_mode(algo, Botan::DECRYPTION));

         if(!enc || !dec)
            {
            result.note_missing(algo);
            return result;
            }

         result.test_eq("mode not authenticated", enc->authenticated(), false);

         enc->set_key(key);
         enc->start(nonce);

         Botan::secure_vector<uint8_t> buf(input.begin(), input.end());
         // TODO: should first update if possible
         enc->finish(buf);

         result.test_eq("encrypt", buf, expected);

         buf.assign(expected.begin(), expected.end());

         dec->set_key(key);
         dec->start(nonce);
         dec->finish(buf);
         result.test_eq("decrypt", buf, input);

         return result;
         }
			static void encodeArray(it const ita, it const ite, std::ostream & out, std::iostream & indexout)
			{
				std::sort(ita,ite);

				this_type enc(out,indexout);

				it itl = ita;

				while ( itl != ite )
				{
					it ith = itl;

					while ( ith != ite && *ith == *itl )
						++ith;

					enc.encode(*itl,ith-itl);

					itl = ith;
				}

				enc.term();
				out.flush();
			}
Beispiel #10
0
TEST(Dict, Compress) {

	const char* dictStr = "quickfoxdogjumps";

	DictFlex dict;
	dict.setDict( (const uint8_t*) dictStr, strlen(dictStr) );

	const char* toEncode = "The quick brown fox jumps over the lazy dog123";

	DictEncStream stream(1024*1024);
	DictEncoder enc(&dict);

	enc.append( (const uint8_t*) toEncode, strlen(toEncode), stream);

	dumpHex(std::cout, stream.data, stream.getNumBytes());

	// check
	ASSERT_EQ(42, stream.getNumBytes());
	ASSERT_EQ(0xFF, stream.data[4]);
	ASSERT_EQ(0x00, stream.data[5]);
	ASSERT_EQ(0x05, stream.data[6]);

	ASSERT_EQ(0xFF, stream.data[14]);
	ASSERT_EQ(0x00, stream.data[15]);
	ASSERT_EQ(0x53, stream.data[16]);		// (offset 5) * 16 + (length 3)

	ASSERT_EQ(0xFF, stream.data[18]);
	ASSERT_EQ(0x00, stream.data[19]);
	ASSERT_EQ(0xB5, stream.data[20]);		// (offset 11) * 16 + (length 5)

	ASSERT_EQ(0xFF, stream.data[36]);
	ASSERT_EQ(0x00, stream.data[37]);
	ASSERT_EQ(0x83, stream.data[38]);		// (offset 8) * 16 + (length 3)



}
Beispiel #11
0
bool TestHKDF(KeyDerivationFunction &kdf, const HKDF_TestTuple *testSet, unsigned int testSetSize)
{
	bool pass = true;

	for (unsigned int i=0; i<testSetSize; i++)
	{
		const HKDF_TestTuple &tuple = testSet[i];

		std::string secret, salt, info, expected;
		StringSource(tuple.hexSecret, true, new HexDecoder(new StringSink(secret)));
		StringSource(tuple.hexSalt ? tuple.hexSalt : "", true, new HexDecoder(new StringSink(salt)));
		StringSource(tuple.hexInfo ? tuple.hexInfo : "", true, new HexDecoder(new StringSink(info)));
		StringSource(tuple.hexExpected, true, new HexDecoder(new StringSink(expected)));

		SecByteBlock derived(expected.size());
		unsigned int ret = kdf.DeriveKey(derived, derived.size(),
                                         reinterpret_cast<const unsigned char*>(secret.data()), secret.size(),
                                         (tuple.hexSalt ? reinterpret_cast<const unsigned char*>(salt.data()) : NULL), salt.size(),
                                         (tuple.hexInfo ? reinterpret_cast<const unsigned char*>(info.data()) : NULL), info.size());

		bool fail = !VerifyBufsEqual(derived, reinterpret_cast<const unsigned char*>(expected.data()), derived.size());
		pass = pass && (ret == tuple.len) && !fail;

		HexEncoder enc(new FileSink(std::cout));
		std::cout << (fail ? "FAILED   " : "passed   ");
		std::cout << " " << tuple.hexSecret << " ";
		std::cout << (tuple.hexSalt ? (strlen(tuple.hexSalt) ? tuple.hexSalt : "<0-LEN SALT>") : "<NO SALT>");
		std::cout << " ";
		std::cout << (tuple.hexInfo ? (strlen(tuple.hexInfo) ? tuple.hexInfo : "<0-LEN INFO>") : "<NO INFO>");
		std::cout << " ";
		enc.Put(derived, derived.size());
		std::cout << std::endl;
	}

	return pass;
}
Beispiel #12
0
int main (){
 	
	

	BYTE  plainText[MAX_BLK_CNT*(BLOCK_SIZE/8)];
	BYTE *tmp;
	BYTE *ret_tmp;
	int i = 0;
	
	printf("*********************************************************************\n");
	printf("*********************************************************************\n");
	srand((unsigned) time(NULL));
	key_and_cipher_init(&ki,&ci);
	
	printf("byteCnt: %d\n",byteCnt);
	printf("-----------------------------------------------------------------------------\n");
	for (i=0;i<25;i++)		
		plainText[i]=(BYTE)((rand()%94)+32);

	tmp=enc(plainText,25);
	ret_tmp=dec(tmp,25);
	free(tmp);
	free(ret_tmp);
	/*printf("\n\n");printf("-----------------------------------------------------------------------------\n");
	
	int new_byteCnt=28;
	for (i=0;i<new_byteCnt;i++)		
		plainText[i]=(BYTE)('a');

	tmp=enc(plainText,new_byteCnt);
	ret_tmp=dec(tmp);
	free(tmp);
	free(ret_tmp);
*/
	return 1;
}	
int main()
{
	typedef CommData::InvokeOnRecvSound Enc;
	typedef RecvSoundEvent Evt;
	typedef EncoderTest<Enc, Evt> Test;


	RawSoundHeader h(2, 16000, 16, RAW_SOUND_LITTLE_ENDIAN); //TODO: Magic number
	RawSound sound(h, 50000); //TODO: Magic number
	Enc enc(1.000, "me", "you", sound);
	Evt evt;
	Test test;

	if (test(enc, evt)) {
		printf("time : %f\n", evt.time());
		printf("callter : %s\n", evt.getCaller());
		RawSound *s = evt.getRawSound();
		RawSoundHeader &h = s->getHeader();
		printf("channel num : %d\n", h.getChannelNum());
		printf("sampling rate : %d\n", h.getSamplingRate());
		printf("bits per sample : %d\n", h.getBitPerSample());
	}
	return 0;
}
			static std::vector<std::string> encodeArray(it const gita, it const gite, std::string const & fnprefix, uint64_t const tparts, uint64_t const blocksize = 64*1024)
			{
				std::sort(gita,gite);

				uint64_t const partsize = (gite-gita+tparts-1)/(tparts);

				std::vector<uint64_t> partstarts;
				it gitc = gita;
				while ( gitc != gite )
				{
					while ( gitc != gita && gitc != gite && (*(gitc-1)) == *gitc )
						++gitc;

					assert ( gitc == gita || gitc == gite || ((*(gitc-1)) != (*gitc)) );

					if ( gitc != gite )
						partstarts.push_back(gitc-gita);

					gitc += std::min(partsize,static_cast<uint64_t>(gite-gitc));
				}

				uint64_t const parts = partstarts.size();
				std::vector<std::string> partfn(parts);
				partstarts.push_back(gite-gita);

				for ( uint64_t p = 0; p < parts; ++p )
				{
					std::ostringstream fnostr;
					fnostr << fnprefix << "_" << std::setw(6) << std::setfill('0') << p;
					std::string const fn = fnostr.str();
					partfn[p] = fn;
					std::string const indexfn = fn+".idx";
					libmaus2::util::TempFileRemovalContainer::addTempFile(indexfn);

					libmaus2::aio::OutputStreamInstance COS(fn);
					libmaus2::aio::InputOutputStream::unique_ptr_type Pindexstr(
						libmaus2::aio::InputOutputStreamFactoryContainer::constructUnique(
							indexfn,std::ios::in|std::ios::out|std::ios::trunc|std::ios::binary
						)
					);
					// libmaus2::aio::CheckedInputOutputStream indexstr(indexfn);

					this_type enc(
						COS,*Pindexstr,
						(p==0)?(-1):gita[partstarts[p]-1],
						blocksize
					);

					it itl = gita + partstarts[p];
					it ite = gita + partstarts[p+1];

					while ( itl != ite )
					{
						it ith = itl;

						while ( ith != ite && *ith == *itl )
							++ith;

						enc.encode(*itl,ith-itl);

						itl = ith;
					}

					enc.term();
					COS.flush();

					Pindexstr.reset();
					libmaus2::aio::FileRemoval::removeFile(indexfn);
				}

				return partfn;
			}
Beispiel #15
0
// confirm certificate signature
bool CertDecoder::ConfirmSignature(Source& pub)
{
    HashType ht;
    mySTL::auto_ptr<HASH> hasher;

    if (signatureOID_ == MD5wRSA) {
        hasher.reset(NEW_TC MD5);
        ht = MD5h;
    }
    else if (signatureOID_ == MD2wRSA) {
        hasher.reset(NEW_TC MD2);
        ht = MD2h;
    }
    else if (signatureOID_ == SHAwRSA || signatureOID_ == SHAwDSA) {
        hasher.reset(NEW_TC SHA);
        ht = SHAh;
    }
    else if (signatureOID_ == SHA256wRSA || signatureOID_ == SHA256wDSA) {
        hasher.reset(NEW_TC SHA256);
        ht = SHA256h;
    }
#ifdef WORD64_AVAILABLE
    else if (signatureOID_ == SHA384wRSA) {
        hasher.reset(NEW_TC SHA384);
        ht = SHA384h;
    }
    else if (signatureOID_ == SHA512wRSA) {
        hasher.reset(NEW_TC SHA512);
        ht = SHA512h;
    }
#endif
    else {
        source_.SetError(UNKOWN_SIG_E);
        return false;
    }

    byte digest[MAX_SHA2_DIGEST_SIZE];      // largest size

    hasher->Update(source_.get_buffer() + certBegin_, sigIndex_ - certBegin_);
    hasher->Final(digest);

    if (keyOID_ == RSAk) {
        // put in ASN.1 signature format
        Source build;
        Signature_Encoder(digest, hasher->getDigestSize(), ht, build);

        RSA_PublicKey pubKey(pub);
        RSAES_Encryptor enc(pubKey);

        if (pubKey.FixedCiphertextLength() != sigLength_) {
            source_.SetError(SIG_LEN_E);
            return false;
        }

        return enc.SSL_Verify(build.get_buffer(), build.size(), signature_);
    }
    else  { // DSA
        // extract r and s from sequence
        byte seqDecoded[DSA_SIG_SZ];
        memset(seqDecoded, 0, sizeof(seqDecoded));
        DecodeDSA_Signature(seqDecoded, signature_, sigLength_);

        DSA_PublicKey pubKey(pub);
        DSA_Verifier  ver(pubKey);

        return ver.Verify(digest, seqDecoded);
    }
}
Beispiel #16
0
static krb5_error_code
krb5int_aes_encrypt_iov(const krb5_keyblock *key,
		        const krb5_data *ivec,
		        krb5_crypto_iov *data,
		        size_t num_data)
{
    aes_ctx ctx;
    char tmp[BLOCK_SIZE], tmp2[BLOCK_SIZE];
    int nblocks = 0, blockno;
    size_t input_length, i;
    struct iov_block_state input_pos, output_pos;

    if (aes_enc_key(key->contents, key->length, &ctx) != aes_good)
	abort();

    if (ivec != NULL)
	memcpy(tmp, ivec->data, BLOCK_SIZE);
    else
	memset(tmp, 0, BLOCK_SIZE);

    for (i = 0, input_length = 0; i < num_data; i++) {
	krb5_crypto_iov *iov = &data[i];

	if (ENCRYPT_IOV(iov))
	    input_length += iov->data.length;
    }

    IOV_BLOCK_STATE_INIT(&input_pos);
    IOV_BLOCK_STATE_INIT(&output_pos);

    nblocks = (input_length + BLOCK_SIZE - 1) / BLOCK_SIZE;
    if (nblocks == 1) {
	krb5int_c_iov_get_block((unsigned char *)tmp, BLOCK_SIZE,
				data, num_data, &input_pos);
	enc(tmp2, tmp, &ctx);
	krb5int_c_iov_put_block(data, num_data, (unsigned char *)tmp2,
				BLOCK_SIZE, &output_pos);
    } else if (nblocks > 1) {
	char blockN2[BLOCK_SIZE];   /* second last */
	char blockN1[BLOCK_SIZE];   /* last block */

	for (blockno = 0; blockno < nblocks - 2; blockno++) {
	    char blockN[BLOCK_SIZE];

	    krb5int_c_iov_get_block((unsigned char *)blockN, BLOCK_SIZE, data, num_data, &input_pos);
	    xorblock(tmp, blockN);
	    enc(tmp2, tmp, &ctx);
	    krb5int_c_iov_put_block(data, num_data, (unsigned char *)tmp2, BLOCK_SIZE, &output_pos);

	    /* Set up for next block.  */
	    memcpy(tmp, tmp2, BLOCK_SIZE);
	}

	/* Do final CTS step for last two blocks (the second of which
	   may or may not be incomplete).  */

	/* First, get the last two blocks */
	memset(blockN1, 0, sizeof(blockN1)); /* pad last block with zeros */
	krb5int_c_iov_get_block((unsigned char *)blockN2, BLOCK_SIZE, data, num_data, &input_pos);
	krb5int_c_iov_get_block((unsigned char *)blockN1, BLOCK_SIZE, data, num_data, &input_pos);

	/* Encrypt second last block */
	xorblock(tmp, blockN2);
	enc(tmp2, tmp, &ctx);
	memcpy(blockN2, tmp2, BLOCK_SIZE); /* blockN2 now contains first block */
	memcpy(tmp, tmp2, BLOCK_SIZE);

	/* Encrypt last block */
	xorblock(tmp, blockN1);
	enc(tmp2, tmp, &ctx);
	memcpy(blockN1, tmp2, BLOCK_SIZE);

	/* Put the last two blocks back into the iovec (reverse order) */
	krb5int_c_iov_put_block(data, num_data, (unsigned char *)blockN1, BLOCK_SIZE, &output_pos);
	krb5int_c_iov_put_block(data, num_data, (unsigned char *)blockN2, BLOCK_SIZE, &output_pos);

	if (ivec != NULL)
	    memcpy(ivec->data, blockN1, BLOCK_SIZE);
    }

    return 0;
}
Beispiel #17
0
int main(int argc,char** argv){
  const char* fname;
  if(argc==2)
    fname=argv[1];
  else if(argc==1)
    fname="/dev/stdout";
  else
    usage(1);

  mwg::bio::ftape tape(fname,"rb");
  if(!tape){
    std::fprintf(stderr,"failed to open the file %s.\n",fname);
    usage(1);
  }

  mwg::bio::tape_head<mwg::bio::ftape,mwg::bio::little_endian_flag> head(tape);

  struct gzip_member_header{
    mwg::byte id1;
    mwg::byte id2;
    mwg::byte cm;
    mwg::byte flg;
    mwg::u4t  mtime;
    mwg::byte xfl;
    mwg::byte os;
  } header={0};

  head.read(header.id1  );
  head.read(header.id2  );
  head.read(header.cm   );
  head.read(header.flg  );
  head.read(header.mtime);
  head.read(header.xfl  );
  head.read(header.os   );

  //mwg_assert(c1==31&&c2==139,"c1=%02x c2=%02x",c1,c2);
  if(!(header.id1==31&&header.id2==139)){
    std::fprintf(stderr,"gzcut: invalid ID1/ID2 %d/%d\n",header.id1,header.id2);
    std::exit(1);
  }
  if(header.cm!=8){
    std::fprintf(stderr,"gzcut: unrecognized compression method %d\n",header.cm);
    std::exit(1);
  }
  if(header.flg&0xE0){
    std::fprintf(stderr,"gzcut: unrecognized flag bits 0x%02X\n",header.flg&0xE0);
    std::exit(1);
  }
  if(!(header.xfl==2||header.xfl==4||header.xfl==0)){
    std::fprintf(stderr,"gzcut: unrecognized compression flag bits combination: 0x%02X\n",header.xfl);
    std::exit(1);
  }

  enum{
    FTEXT   =0x01,
    FHCRC   =0x02,
    FEXTRA  =0x04,
    FNAME   =0x08,
    FCOMMENT=0x10,
  };

  if(header.flg&FEXTRA){
    mwg::u4t xlen;
    head.read(xlen);
    head.seek(xlen,SEEK_CUR);
  }

  if(header.flg&FNAME){
    mwg::byte d=0;
    std::fprintf(stderr,"gzcut: filename: ");
    while(head.read(d)&&d!=0)putc(d,stderr);
    putc('\n',stderr);
  }

  if(header.flg&FCOMMENT){
    mwg::byte d=0;
    std::fprintf(stderr,"gzcut: comment: ");
    while(head.read(d)&&d!=0)putc(d,stderr);
    putc('\n',stderr);
  }

  if(header.flg&FHCRC){
    mwg::u2t crc16=0;
    head.read(crc16);
    std::fprintf(stderr,"gzcut: crc16: 0x%04X\n",crc16);
  }

  mwg::i8t csize=0;
  {
    mwg::i8t cur=head.tell();
    auto mark=head.mark();
    head.seek(-8,SEEK_END);
    csize=head.tell()-cur;

    mwg::u4t crc32;
    mwg::u4t isize;
    head.read(crc32);
    head.read(isize);

    std::fprintf(stderr,"gzcut: crc32: 0x%04X\n",crc32);
    std::fprintf(stderr,"gzcut: compressed size: %lld\n",(long long)csize);
    std::fprintf(stderr,"gzcut: original size: %lld mod 2^32\n",(long long)isize);
  }

  {
    a85encoder enc(stdout);
    mwg::byte b;
    for(mwg::i8t i=0;i<csize&&head.read(b);i++)
      enc.consume(b);
  }

  return 0;
}
Beispiel #18
0
// generate KeyA pair, return public key as ASCII
LPSTR __cdecl cpp_init_keya(HANDLE context, int features) {

	pCNTX ptr = get_context_on_id(context); if(!ptr) return NULL;
	pSIMDATA p = (pSIMDATA) cpp_alloc_pdata(ptr);

	int send_features = FEATURES;
	if(p->KeyP) send_features |= FEATURES_PSK;

	SAFE_DELETE(p->dh);
	if(features & FEATURES_NEWPG) {
		Integer p0("0x865734026113B4DF0082CED84C197718516088FBDA406CFDFD7F033694E11E46F01C8F01E0E5AE6B09F6284691C7DD30A5BA8A74BA4B780198624B84BC8DAF6E0DFF874C0440ABB5C043C82E9E9C9E6F1A470B6A2A6BCEAC9460C43B1BB1331DF0FFD898DB74D22E8A71DB2659F1B0F52F337718D233DED611DA25AEAA90F3BE0C42FA9E541D0487DF58A77E2F44D295AD0C54C369CE260C969CA12F690EAAFAEEF8676C631AF29A3DE3389D3000B94EFA775E31FCA879AEB00A4D05EEF50D4C084A049EB12EF4CDFBD48E36B29CEAF8978D535D6C70BB274D1FEA02ABD521D2EF482A76326C17AF597FCB9B8BF37D9110E22AB0746D6A9779DF5133822E3F15");
		Integer q0("0xF1515160E1BFC7636338C13AD5BA775318E287147A1F96B73CF0FB4D97EFFB9D1FCDCF31AB9D92C4F49C9F8D50F06E697D2313E2EBAC7781312A51F458D66FFC687960CAA86BDF150A36ED53D79FBDB4F501FD25E37C181B45F9555D7F1C6124CAB29A822AD1E7BF5DA93C2FDB12A61919B5E5359793CBB16E71516919040A7F");
		Integer g0("0x434158F2FF2CF667E3CC1A707770DDE7B56048F6C5005473C6DC4A5E3FC490667F2908C44F9ADC2071EB8A8A1EC6AD6901CDAAAFE806626E3F4C5E69D4FCBF9DF1B67D574DC61C687C4BEF3ACF77A7256752F4D3A7EAEEE5874ED4912AB10C5B122A24E698B14CAC3E0FD006E0DB02714E028AECCA25BAB9DDCA2CF6405E862B403C61BC381D64B46BD96D3FEFBE22B7497FCBDA2B49C840C1B2853502A5216B036F83D2EAD8F835B603FC5BA1EFB816C7634915B1D43963FDD1B1ED626F48CCF8F152392E4693D38C566016708FA9E9598AECF95A8B067212669247552418E538A706564F855D3D5D50717D356259A20D8FD0C6B2A9FCC045D3F7AED1E857C5");
		p->dh = new DH(p0,q0,g0);
	}
	else {
		Integer p0("0xD494AAFBCD2EAC6A36DB8E7DD4A2A64512A5BBB15B9BFB581C7C1CAFB647D4612973C3770C2166D75EEA695F67EA8261557591DB78BCF5A886AA5294F3AEE4D25B57C8EE8C7FE8DBF70C132CD7FFCB6F89426F807F552C5DAE2FB1F329E340094E4B30D8EF6265AB4D350E9837B151C86AC524DE4E1FC04746C668BE318275E420D51AEDDFBDF887D435CDEEF6AC81293DB45287132F8236A43AD8F4D6642D7CA6732DA06A1DE008259008C9D74403B68ADAC788CF8AB5BEFFC310DCCCD32901D1F290E5B7A993D2CF6A652AF81B6DA0FD2E70678D1AE086150E41444522F20621195AD2A1F0975652B4AF7DE5261A9FD46B9EA8B443641F3BBA695B9B020103");
		Integer g0("0x12A567BC9ABCDEF1234567823BCDEF1E");
		p->dh = new DH(p0,g0);
	}

	BYTE priv1[KEYSIZE];	// private key of 2048 bit
	BYTE publ1[KEYSIZE+2];	// public key of 2048 bit + faetures field

	memset(priv1,0,sizeof(priv1));
	memset(publ1,0,sizeof(publ1));

	AutoSeededRandomPool autorng;
	p->dh->GenerateKeyPair(autorng, priv1, publ1);

	SAFE_FREE(p->PubA);
	p->PubA = (PBYTE) malloc(KEYSIZE);
	memcpy(p->PubA,publ1,KEYSIZE);

	SAFE_FREE(p->KeyA);
	p->KeyA = (PBYTE) malloc(KEYSIZE);
	memcpy(p->KeyA,priv1,KEYSIZE);

	if(p->KeyP) {
		// encrypt PUBLIC use PSK
		string ciphered;
		CFB_Mode<AES>::Encryption enc(p->KeyP,Tiger::DIGESTSIZE,IV);
		StreamTransformationFilter cbcEncryptor(enc,new StringSink(ciphered));

		cbcEncryptor.Put(publ1,KEYSIZE);
		cbcEncryptor.MessageEnd();
		memcpy(publ1,ciphered.data(),ciphered.length());
#if defined(_DEBUG) || defined(NETLIB_LOG)
		Sent_NetLog("cpp_init_keya: %d %d",KEYSIZE,ciphered.length());
#endif
	}
	memcpy((PVOID)&publ1[KEYSIZE],(PVOID)&send_features,2);

	SAFE_FREE(ptr->tmp);
	if(ptr->mode & MODE_BASE64 || features & FEATURES_NEWPG)
		ptr->tmp = base64encode((LPSTR)&publ1,KEYSIZE+2);
	else
		ptr->tmp = base16encode((LPSTR)&publ1,KEYSIZE+2);

	return ptr->tmp;
}
Beispiel #19
0
      Test::Result run_one_test(const std::string& algo, const VarMap& vars) override
         {
         Test::Result result("OCB wide block long test");

         const std::vector<uint8_t> expected = vars.get_req_bin("Output");

         std::unique_ptr<Botan::BlockCipher> cipher;
         size_t bs = 0;

         if(algo == "SHACAL2")
            {
#if defined(BOTAN_HAS_SHACAL2)
            cipher = Botan::BlockCipher::create_or_throw("SHACAL2");
            bs = 32;
#else
            return {result};
#endif
            }
         else
            {
            if(algo == "Toy128")
               bs = 16;
            else if(algo == "Toy192")
               bs = 24;
            else if(algo == "Toy256")
               bs = 32;
            else if(algo == "Toy512")
               bs = 64;
            else
               throw Test_Error("Unknown cipher for OCB wide block long test");
            cipher.reset(new OCB_Wide_Test_Block_Cipher(bs));
            }

         Botan::OCB_Encryption enc(cipher.release(), std::min<size_t>(bs, 32));

         /*
         Y, string of length min(B, 256) bits

         Y is defined as follows.

         K = (0xA0 || 0xA1 || 0xA2 || ...)[1..B]
         C = <empty string>
         for i = 0 to 127 do
           S = (0x50 || 0x51 || 0x52 || ...)[1..8i]
           N = num2str(3i+1,16)
           C = C || OCB-ENCRYPT(K,N,S,S)
           N = num2str(3i+2,16)
           C = C || OCB-ENCRYPT(K,N,<empty string>,S)
           N = num2str(3i+3,16)
           C = C || OCB-ENCRYPT(K,N,S,<empty string>)
         end for
         N = num2str(385,16)
         Y = OCB-ENCRYPT(K,N,C,<empty string>)
         */

         std::vector<uint8_t> key(bs);
         for(size_t i = 0; i != bs; ++i)
            key[i] = 0xA0 + i;

         enc.set_key(key);

         const std::vector<uint8_t> empty;
         std::vector<uint8_t> N(2);
         std::vector<uint8_t> C;

         for(size_t i = 0; i != 128; ++i)
            {
            std::vector<uint8_t> S(i);
            for(size_t j = 0; j != S.size(); ++j)
               S[j] = 0x50 + j;

            Botan::store_be(static_cast<uint16_t>(3 * i + 1), &N[0]);

            ocb_encrypt(result, C, enc, N, S, S);
            Botan::store_be(static_cast<uint16_t>(3 * i + 2), &N[0]);
            ocb_encrypt(result, C, enc, N, S, empty);
            Botan::store_be(static_cast<uint16_t>(3 * i + 3), &N[0]);
            ocb_encrypt(result, C, enc, N, empty, S);
            }

         Botan::store_be(static_cast<uint16_t>(385), &N[0]);
         std::vector<uint8_t> final_result;
         ocb_encrypt(result, final_result, enc, N, empty, C);

         result.test_eq("correct value", final_result, expected);

         return result;
         }
Beispiel #20
0
void PolynomialMod2::DEREncodeAsOctetString(BufferedTransformation &bt, size_t length) const
{
	DERGeneralEncoder enc(bt, OCTET_STRING);
	Encode(enc, length);
	enc.MessageEnd();
}
Beispiel #21
0
std::shared_ptr<Decoder> DecoderFactory::get(const std::string& chain) {
    // return a cached encoder if we have one
    auto i = Cache.find(chain);
    if (i != Cache.end()) {
        return i->second;
    }

    // parse the transformation chain
    std::vector<std::string> charchar, bytebyte;
    std::string charbyte;
    std::tie(charchar, charbyte, bytebyte) = parseChain(chain);

    // assemble the transformation chain
    std::unique_ptr<Decoder> enc(new ByteSource(nullptr, nullptr));

    for (auto bb = bytebyte.crbegin(); bb != bytebyte.crend(); ++bb) {
        if (*bb == "identity") {
            // do nothing
        }
        else if (*bb == "OCE") {
            enc.reset(new OCEDecoder(std::move(enc)));
        }
        else if (bb->substr(0, 3) == "XOR") {
            enc.reset(new XORDecoder(
                          boost::lexical_cast<byte>(bb->substr(3)), std::move(enc)
                      ));
        }
    }

    if (charbyte == "ASCII") {
        enc.reset(new ASCIIDecoder(std::move(enc)));
    }
    else if (charbyte == "UTF-8") {
        enc.reset(new UTF8Decoder(std::move(enc)));
    }
    else if (charbyte == "UTF-16LE") {
        enc.reset(new UTF16LEDecoder(std::move(enc)));
    }
    else if (charbyte == "UTF-16BE") {
        enc.reset(new UTF16BEDecoder(std::move(enc)));
    }
    else if (charbyte == "UTF-32LE") {
        enc.reset(new UTF32LEDecoder(std::move(enc)));
    }
    else if (charbyte == "UTF-32BE") {
        enc.reset(new UTF32BEDecoder(std::move(enc)));
    }
    else {
        enc.reset(new ICUDecoder(charbyte.c_str(), std::move(enc)));
    }

    for (auto cc = charchar.crbegin(); cc != charchar.crend(); ++cc) {
        if (*cc == "identity") {
            // do nothing
        }
        else if (cc->substr(0, 3) == "rot") {
            enc.reset(new RotDecoder(
                          boost::lexical_cast<uint32_t>(cc->substr(3)), std::move(enc)
                      ));
        }
    }

    return std::shared_ptr<Decoder>(std::move(enc));
}
Beispiel #22
0
Datei: k.c Projekt: geocar/qlua
static int enc(K*k,lua_State *L)
{
	switch (lua_type(L, -1)) {
	case LUA_TSTRING: 	{ size_t len;const char *str = lua_tolstring(L,-1,&len);(*k)=kpn(str,len);R 1;}	break;
	case LUA_TNUMBER:	{ F num = lua_tonumber(L,-1);(*k) = (num==floor(num))?kj((J)num):kf(num);R 1;} break;
	case LUA_TBOOLEAN:	{ (*k)=kb( lua_toboolean(L,-1) );R 1;}	break;
	case LUA_TNIL:		{ (*k)=ktn(0,0);R 1;}	break;
	case LUA_TTABLE:	{
		double p;
		int max = 0;
		int items = 0;
		int t_integer = 0, t_number = 0, t_boolean = 0, t_other= 0;

		lua_pushnil(L);
		/* table, startkey */
		while (lua_next(L, -2) != 0) {
			items++;

			/* table, key, value */
			switch (lua_type(L, -1)) {
			case LUA_TNUMBER:  t_number++; p = lua_tonumber(L,-1);  t_integer += (floor(p) == p); break;
			case LUA_TBOOLEAN: t_boolean++; break;
			default:   t_other++; break;	/* or anything else */
			};

			if (lua_type(L, -2) == LUA_TNUMBER &&
					(p = lua_tonumber(L, -2))) {
				/* Integer >= 1 ? */
				if (floor(p) == p && p >= 1) {
					if (p > max)
						max = p;
					lua_pop(L, 1);
					continue;
				}
			}

			/* Must not be an array (non integer key) */
			for (lua_pop(L,1); lua_next(L, -2) != 0; lua_pop(L,1)) ++items;
			max = 0;
			break;
		}
		lua_pushnil(L);
		if (max != items) {
			/* build K dictionary */
			K keys = ktn(KS,items);
			K values = ktn(0,items);
			int n = 0;
			/* table, startkey */
			while (lua_next(L, -2) != 0) {
				kS(keys)[n] = ss(lua_tostring(L, -2));
				if(!enc(kK(values)+n,L))R 0;
				lua_pop(L,1);
				++n;
			}
			*k = xD(keys,values);
			R 1;
		}
		/* build K list */
		if(t_other || ((!!t_boolean)+(!!t_number)) > 1) {
			K a = ktn(0,items);
			while (lua_next(L, -2) != 0) {
				p = lua_tonumber(L, -2);
				if(!enc(kK(a)+LI(p),L))R 0;
				lua_pop(L, 1);
			}
			*k = a;
			R 1;
		}
		if(t_boolean) {
			K a = ktn(KB,items);
			while (lua_next(L, -2) != 0) {
				p = lua_tonumber(L, -2);
				kG(a)[LI(p)] = lua_toboolean(L,-1);
				lua_pop(L, 1);
			}
			*k = a;
			R 1;
		}
		if(t_number == t_integer) {
			K a = ktn(KJ,items);
			while (lua_next(L, -2) != 0) {
				p = lua_tonumber(L, -2);
				kJ(a)[LI(p)] = (int)floor(lua_tonumber(L,-1));
				lua_pop(L, 1);
			}
			*k = a;
			R 1;
		}
		if(t_number) {
			K a = ktn(KF,items);
			while (lua_next(L, -2) != 0) {
				p = lua_tonumber(L, -2);
				kF(a)[LI(p)] = lua_tonumber(L,-1);
				lua_pop(L, 1);
			}
			*k = a;
			R 1;
		}
		*k = ktn(0,0);
		R 1;
	}; break;
	default:
		luaL_error(L, "Cannot serialise %s: %s", lua_typename(L, lua_type(L, -1)), "can't serialize type");
		R 0;
	};
}
Beispiel #23
0
std::string PackRpcValues(ArrayRef<std::shared_ptr<Value>> values) {
  WireEncoder enc(0x0300);
  for (auto& value : values) enc.WriteValue(*value);
  return enc.ToStringRef();
}
Beispiel #24
0
char * MAC(char* data,int dataLength, char * ran, char * key16)
{
	int key16Length =32 ;
	char keya[17];
	char keyb[17];
	char d3[17];
	char d4[17];
	char result[17];
	memcpy( keya ,key16, key16Length / 2);
	memcpy( keyb  , (char*)&key16[key16Length / 2],key16Length / 2);
	keya[16]=0;
	keyb[16]=0;
	memset( d3 ,0x00,sizeof(d3));
	memset( d4 ,0x00,sizeof(d3));
	memset( result,0x00,sizeof(16));
	echomac("bb");
	if (dataLength >= 16)
	{
		unsigned char Ran9[9];
		unsigned char PrTemp[17];
		memcpy(d3, data, 16);
		PrTemp[16] = 0x00;
		d3[16]=0;
		XOR(PadRight(Substring(ran,0,8,Ran9), 16, '0',PrTemp),  d3,16,result);
		echomac("bb");
		if (dataLength % 16 == 0)
		{
			int i ;
			for ( i = 1; i <dataLength / 16; i++)
			{
				unsigned char resultBin[8],keyaBin[8] ;				;
				enc(Hex2Bin(keya,keyaBin), Hex2Bin(result,resultBin));
				Bin2Hex(resultBin,8,result);
				printf( result);
				Substring(data,i * 16, 16,d3);
				XOR(result, d3,16,result);
				memcpy(d4 , (char*)&"8000000000000000",16);
				echomac("bb");
			}
			if (dataLength == 16) 
			{
				memcpy(d4 ,"8000000000000000",16);
			}
			echomac("bb");
			unsigned char temp222[8];Hex2Bin(result,temp222);
			unsigned char keyaXXX[8];Hex2Bin(keya,keyaXXX);
			unsigned char keybXXX[8];Hex2Bin(keyb,keybXXX);
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);			
			XOR(result, d4,16,result);			
			Hex2Bin(result,temp222);
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);			
			dec(keybXXX, temp222);
			Bin2Hex(temp222,8,result);			
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);	
			echomac("bb");
		}
		else
		{
			
			int i ;
			unsigned char keyaXXX1[8];Hex2Bin(keya,keyaXXX1);
			unsigned char keybXXX1[8];Hex2Bin(keyb,keybXXX1);
			echomac("bb");
			for ( i = 1; i < dataLength / 16; i++)
			{
				unsigned char temp4441[8];Hex2Bin(result,temp4441);
				unsigned char temp4442keya[8];Hex2Bin(keya,temp4442keya);
				enc(temp4442keya, temp4441);
				Bin2Hex(temp4441,8,result);
				Substring(data, i * 16, 16,d3);
				XOR(result, d3,16,result);
			}
			Substring(data,dataLength - dataLength % 16, dataLength % 16,d4);
			strcat(d4,"8");//可能有问题
			PadRight(d4,16, '0',d4);
			unsigned char temp555[8];Hex2Bin(result,temp555);
			enc(keyaXXX1, temp555);
			Bin2Hex(temp555,8,result);
			XOR(result,  d4,16,result);
			Hex2Bin(result,temp555);//temp555=Hex2Bin(result);
			enc(keyaXXX1, temp555);
			dec(keybXXX1, temp555);
			enc(keyaXXX1, temp555);
			Bin2Hex(temp555,8,result);
			echomac("bb");
		}
	}
	else
	{
		echomac("bb");
		unsigned char Ran9[9];
		unsigned char temp4442keya[8];Hex2Bin(keya,temp4442keya);
		unsigned char temp4442keyb[8];Hex2Bin(keyb,temp4442keyb);
		sprintf(d3,"%s%s",data,"8");
		PadRight(d3,16, '0',d3);
		PadRight(Substring(ran,0,8,Ran9),16,'0',result);
		XOR( result, d3,16,result);
		unsigned char temp777[8];Hex2Bin(result,temp777);
		enc(temp4442keya, temp777);
		Bin2Hex(temp777,8,result);;
		dec(temp4442keyb, temp777);
		Bin2Hex(temp777,8,result);
		enc(temp4442keya, temp777);
		Bin2Hex(temp777,8,result);
		echomac("bb");
	}
	memset(___MAC,0x00,9);
	memcpy(___MAC,result,8);
	return ___MAC;

}
Beispiel #25
0
EXPORT char *   MAC8(char * data,int dataLength, char * ran, char * key8)
{
	char result[17] ;
	char d3[17] ;
	char d4[17];
	unsigned char Ran9[9];
	unsigned char Prtwmp[17];
	unsigned char key8aaa[strlen(key8)/2];Hex2Bin(key8,key8aaa);
	if (dataLength >= 16)
	{
		
		Substring(data,0, 16,d3);
		Prtwmp[16] = 0x00;
		XOR(PadRight( Substring(ran,0,8,Ran9),16,'0',Prtwmp),d3,dataLength,result);
		result[16]=0;
		if (dataLength % 16 == 0)
		{
			unsigned char temp777[8];
			int i;
			for (  i = 1; i < dataLength / 16; i++)
			{
				Hex2Bin(result,temp777);//temp777=Hex2Bin(result);
				enc(key8aaa, temp777);
				Bin2Hex(temp777,8,result);
				Substring(data,i * 16, 16,d3);
				XOR(result, d3,16,result);
				memcpy(d4,(char *)"8000000000000000",16);
				d4[16] = 0x00;
			}
			if (dataLength == 16) 
			{
				memcpy(d4,(char*)"8000000000000000",16);
				d4[16] = 0x00;
			}
			Hex2Bin(result,temp777);
			enc(key8aaa, temp777);
			Bin2Hex(temp777,8,result);
			XOR(result, d4,16,result);
			Hex2Bin(result,temp777);
			enc(key8aaa, temp777);
			Bin2Hex(temp777,8,result);

		}
		else
		{
			int i;
			unsigned char tmp999[8];
			char *tmpx99x;
			unsigned char tmp999keya[strlen(key8)/2];Hex2Bin(key8,tmp999keya);
			for ( i= 1; i < dataLength / 16; i++)
			{
				unsigned char tmp888[8];Hex2Bin(result,tmp888);
				enc(key8aaa, tmp888);
				Substring(data,i * 16, 16,d3);
				Bin2Hex(tmp888,8,result);
				XOR(result, d3,16,result);

			}

			Substring(data,dataLength - dataLength % 16, dataLength % 16,d4);			
			strcat(d4,"8");
			PadRight(d4,16, '0',d4);
			Hex2Bin(result,tmp999);
			enc(tmp999keya, tmp999);
			Bin2Hex(tmp999,8,result);
			XOR(result, d4,16,result);
			Hex2Bin(result,tmp999);
			enc(tmp999keya, tmp999);
			Bin2Hex(tmp999,8,result);
		}
	}
	else
	{
		unsigned char tmp888111[8];
		unsigned char PdTemp[17];
		sprintf(d3,"%s%s", data, "8");
		PadRight(d3,16, '0',d3);
		PdTemp[16] = 0;
		XOR(PadRight( Substring(ran,0, 8,Ran9),16, '0',PdTemp), d3,16,result);
		Hex2Bin(result,tmp888111);
		enc(key8aaa, tmp888111);
		Bin2Hex(tmp888111,8,result);
	}
	memset(___MAC8,0x00,9);
	memcpy(___MAC8,result,8);
	return ___MAC8;
}
Beispiel #26
0
  bool VLFeat::CalculateCommon(int f, bool all, int l) {
    string msg = "VLFeat::CalculateCommon("+ToStr(f)+","+ToStr(all)+","+
      ToStr(l)+") : ";

    // if (!do_fisher && !do_vlad) {
    //   cerr << msg
    // 	   << "either encoding=fisher or encoding=vlad should be specified"
    // 	   << endl;
    //   return false;
    // }

    if (!gmm && !kmeans) {
      cerr << msg << "either gmm=xxx or kmeans=xxx option should be given"
	   << endl;
      return false;
    }

    cox::tictac::func tt(tics, "VLFeat::CalculateCommon");
    
    // obs! only some parameters here, should be in ProcessOptionsAndRemove()
    // too, also scales and geometry should be made specifiable...
    bool normalizeSift = false, renormalize = true, flat_window = true;
    size_t step = 3, binsize = 8;

    EnsureImage();

    int width = Width(true), height = Height(true);

    if (FrameVerbose())
      cout << msg+"wxh="
	   << width << "x" << height << "=" << width*height << endl;

    vector<float> rgbcoeff { 0.2989, 0.5870, 0.1140 };

    imagedata idata = CurrentFrame();
    idata.convert(imagedata::pixeldata_float);
    idata.force_one_channel(rgbcoeff);

    vector<float> dsift;
    size_t descr_size_orig = 0, descr_size_final = 0;
    vector<float> scales { 1.0000, 0.7071, 0.5000, 0.3536, 0.2500 };
    // vector<float> scales { 1.0000 };
    for (size_t i=0; i<scales.size(); i++) {
      if (KeyPointVerbose())
	cout << "Starting vl_dsift_process() in scale " << scales[i] << endl;
      
      imagedata simg = idata;
      if (scales[i]!=1) {
	scalinginfo si(simg.width(), simg.height(),
		       (int)floor(scales[i]*simg.width()+0.5),
		       (int)floor(scales[i]*simg.height()+0.5));
	simg.rescale(si, 1);
      }

      // VlDsiftFilter *sf = vl_dsift_new(simg.width(), simg.height());
      VlDsiftFilter *sf = vl_dsift_new_basic(simg.width(), simg.height(),
					     step, binsize);

      // opts.scales = logspace(log10(1), log10(.25), 5) ;
      // void vl_dsift_set_bounds	(	VlDsiftFilter * 	self,
      // 					int 	minX,
      // 					int 	minY,
      // 					int 	maxX,
      // 					int 	maxY 
      // 					);	
      
      // VlDsiftDescriptorGeometry geom = { 8, 4, 4, 0, 0 };
      // vl_dsift_set_geometry(sf, &geom);
      
      //vl_dsift_set_steps(sf, 3, 3);

      //vl_dsift_set_window_size(sf, 8);

      vl_dsift_set_flat_window(sf, flat_window); // aka fast in matlab

      vector<float> imgvec = simg.get_float();
      const float *img_fp = &imgvec[0];
      // cout << "IMAGE = " << img_fp[0] << " " << img_fp[1] << " "
      //      << img_fp[2] << " ... " << img_fp[41] << endl;

      vl_dsift_process(sf, img_fp);
      
      // if opts.rootSift // false
      // 		descrs{si} = sqrt(descrs{si}) ;
      // end
      // 	if opts.normalizeSift //true
      // 		  descrs{si} = snorm(descrs{si}) ;
      // end

      descr_size_orig = sf->descrSize;
      size_t nf = sf->numFrames;
      const VlDsiftKeypoint *k = sf->frames;
      float *d  = sf->descrs;
      
      if (KeyPointVerbose())
	cout << "  found " << sf->numFrames << " 'frames' in "
	     << simg.info() << endl
	     << "  descriptor dim " << descr_size_orig << endl;
      
      if (PixelVerbose())
	for (size_t i=0; i<nf; i++) {
	  cout << "  i=" << i << " x=" << k[i].x << " y=" << k[i].y
	       << " s=" << k[i].s << " norm=" << k[i].norm;
	  if (FullVerbose()) {
	    cout << " RAW";
	    for (size_t j=0; j<descr_size_orig; j++)
	      cout << " " << d[i*descr_size_orig+j];
	  }
	  cout << endl;
	}

      if (normalizeSift) {
	for (size_t i=0; i<nf; i++) {
	  if (PixelVerbose())
	    cout << "  i=" << i << " x=" << k[i].x << " y=" << k[i].y
		 << " s=" << k[i].s << " norm=" << k[i].norm;
	  double mul = 0.0;
	  for (size_t j=0; j<descr_size_orig; j++)
	    mul += d[i*descr_size_orig+j]*d[i*descr_size_orig+j];
	  if (mul)
	    mul = 1.0/sqrt(mul);
	  if (FullVerbose())
	    cout << " NORM";
	  for (size_t j=0; j<descr_size_orig; j++) {
	    d[i*descr_size_orig+j] *= mul;
	    if (FullVerbose())
	      cout << " " << d[i*descr_size_orig+j];
	  }
	  if (PixelVerbose())
	    cout << endl;
	}
      }

      if (!pca.vector_length()) {
	dsift.insert(dsift.end(), d, d+nf*descr_size_orig);
	descr_size_final = descr_size_orig;

      } else {
	for (size_t i=0; i<nf; i++) {
	  vector<float> vin(d+i*descr_size_orig, d+(i+1)*descr_size_orig);
	  vector<float> vout = pca.projection_coeff(vin);
	  dsift.insert(dsift.end(), vout.begin(), vout.end());
	}
	descr_size_final = pca.base_size();
      }
	  
      vl_dsift_delete(sf);
    }

    size_t numdata = dsift.size()/descr_size_final;
    const float *datain = &dsift[0];

    vector<float> enc((do_fisher?2:1)*descriptor_dim()*nclusters());
    float *dataout = &enc[0];
      
    if (do_fisher) {
      if (FrameVerbose())
	cout << msg << "fisher encoding " << numdata
	     << " descriptors of size " << descr_size_orig
	     << " => " << descr_size_final
	     << " with gmm dimensionality " << descriptor_dim()
	     << endl;
      
      if (descr_size_final!=descriptor_dim()) {
	cerr << msg << "dimensionality mismatch descr_size_final="
	     << descr_size_final << " descriptor_dim()=" << descriptor_dim() 
	     << endl;
	return false;
      }

      vl_fisher_encode(dataout, VL_TYPE_FLOAT, means(), descriptor_dim(),
		       nclusters(), covariances(), priors(),
		       datain, numdata, VL_FISHER_FLAG_IMPROVED) ;
    }

    if (do_vlad) {
      //obs! correct use of pca?

      if (FrameVerbose())
	cout << msg << "vlad encoding " << numdata
	     << " descriptors of size " << descr_size_final << endl;

      vector<vl_uint32> indexes(numdata);
      vector<float> distances(numdata);

      if (kdtree)
	vl_kdforest_query_with_array(kdtree, &indexes[0], 1, numdata, &distances[0], datain);
      else
	vl_kmeans_quantize(kmeans, &indexes[0], &distances[0], datain, numdata);

      vector<float> assignments(numdata*nclusters());
      for (size_t i=0; i<numdata; i++)
	assignments[i * nclusters() + indexes[i]] = 1;
      
      int vlad_flags = VL_VLAD_FLAG_SQUARE_ROOT|VL_VLAD_FLAG_NORMALIZE_COMPONENTS;

      vl_vlad_encode(dataout, VL_TYPE_FLOAT, means(), descriptor_dim(),
		     nclusters(), datain, numdata, &assignments[0],
		     vlad_flags);
    }

    if (renormalize) {
      if (PixelVerbose())
	cout << " RENORM:";
      double mul = 0.0;
      for (size_t j=0; j<enc.size(); j++)
	mul += enc[j]*enc[j];
      if (mul)
	mul = 1.0/sqrt(mul);
      for (size_t j=0; j<enc.size(); j++) {
	if (PixelVerbose())
	  cout << " " << enc[j];
	enc[j] *= mul;
	if (PixelVerbose())
	  cout << "->" << enc[j];
      }
      if (PixelVerbose())
	cout << endl;
    }

    ((VectorData*)GetData(0))->setVector(enc);
    
    return true;
  }
Beispiel #27
0
static krb5_error_code
krb5int_camellia_encrypt(krb5_key key, const krb5_data *ivec,
                         krb5_crypto_iov *data, size_t num_data)
{
    unsigned char tmp[BLOCK_SIZE], tmp2[BLOCK_SIZE];
    int nblocks = 0, blockno;
    size_t input_length, i;
    struct iov_block_state input_pos, output_pos;

    if (key->cache == NULL) {
        key->cache = malloc(sizeof(struct camellia_key_info_cache));
        if (key->cache == NULL)
            return ENOMEM;
        CACHE(key)->enc_ctx.keybitlen = CACHE(key)->dec_ctx.keybitlen = 0;
    }
    if (CACHE(key)->enc_ctx.keybitlen == 0) {
        if (camellia_enc_key(key->keyblock.contents, key->keyblock.length,
                             &CACHE(key)->enc_ctx) != camellia_good)
            abort();
    }
    if (ivec != NULL)
        memcpy(tmp, ivec->data, BLOCK_SIZE);
    else
        memset(tmp, 0, BLOCK_SIZE);

    for (i = 0, input_length = 0; i < num_data; i++) {
        krb5_crypto_iov *iov = &data[i];

        if (ENCRYPT_IOV(iov))
            input_length += iov->data.length;
    }

    IOV_BLOCK_STATE_INIT(&input_pos);
    IOV_BLOCK_STATE_INIT(&output_pos);

    nblocks = (input_length + BLOCK_SIZE - 1) / BLOCK_SIZE;
    if (nblocks == 1) {
        krb5int_c_iov_get_block(tmp, BLOCK_SIZE, data, num_data, &input_pos);
        enc(tmp2, tmp, &CACHE(key)->enc_ctx);
        krb5int_c_iov_put_block(data, num_data, tmp2, BLOCK_SIZE, &output_pos);
    } else if (nblocks > 1) {
        unsigned char blockN2[BLOCK_SIZE];   /* second last */
        unsigned char blockN1[BLOCK_SIZE];   /* last block */

        for (blockno = 0; blockno < nblocks - 2; blockno++) {
            unsigned char blockN[BLOCK_SIZE], *block;

            krb5int_c_iov_get_block_nocopy(blockN, BLOCK_SIZE,
                                           data, num_data, &input_pos, &block);
            xorblock(tmp, block);
            enc(block, tmp, &CACHE(key)->enc_ctx);
            krb5int_c_iov_put_block_nocopy(data, num_data, blockN, BLOCK_SIZE,
                                           &output_pos, block);

            /* Set up for next block.  */
            memcpy(tmp, block, BLOCK_SIZE);
        }

        /* Do final CTS step for last two blocks (the second of which
           may or may not be incomplete).  */

        /* First, get the last two blocks */
        memset(blockN1, 0, sizeof(blockN1)); /* pad last block with zeros */
        krb5int_c_iov_get_block(blockN2, BLOCK_SIZE, data, num_data,
                                &input_pos);
        krb5int_c_iov_get_block(blockN1, BLOCK_SIZE, data, num_data,
                                &input_pos);

        /* Encrypt second last block */
        xorblock(tmp, blockN2);
        enc(tmp2, tmp, &CACHE(key)->enc_ctx);
        memcpy(blockN2, tmp2, BLOCK_SIZE); /* blockN2 now contains first block */
        memcpy(tmp, tmp2, BLOCK_SIZE);

        /* Encrypt last block */
        xorblock(tmp, blockN1);
        enc(tmp2, tmp, &CACHE(key)->enc_ctx);
        memcpy(blockN1, tmp2, BLOCK_SIZE);

        /* Put the last two blocks back into the iovec (reverse order) */
        krb5int_c_iov_put_block(data, num_data, blockN1, BLOCK_SIZE,
                                &output_pos);
        krb5int_c_iov_put_block(data, num_data, blockN2, BLOCK_SIZE,
                                &output_pos);

        if (ivec != NULL)
            memcpy(ivec->data, blockN1, BLOCK_SIZE);
    }

    return 0;
}
Beispiel #28
0
int ClientSession::run(std::string strUsername, std::string strPassword)
{
	int rval;
	San2::Utils::bytes request, response;
	San2::Utils::bytes srpA;
	San2::Utils::bytes username, password;
	char line[SH_TERMINAL_MAXLINLEN];
	
	username = strUsername;
	password = strPassword;
	sca = srpclient.getAuthenticator(username, password);
	srpA = sca.getA();
				
	rval = enc_construct_A_message(strUsername, srpA, request);
			
	if (rval)
	{
		printf("ClientSession::run:enc_construct_A_message failed: %d\n", rval);
		return -1;
	}
			
	if (m_swtx.sendReliableMessage(request, response) == false)
	{
		printf("sending A message failed\n");
		return -2;
	}
	
	unsigned char errorCode;
	San2::Utils::bytes srpB;
	San2::Utils::bytes srpSalt;
	
	rval = enc_parse_P_message(response, srpSalt, srpB, errorCode);
	
	if (rval)
	{
		printf("ClientSession::run:enc_parse_P_message failed: %d\n", rval);
		return -3;
	}
	
	if (errorCode == SH_ERRORCODE_USERNOTFOUND)
	{
		printf("User was not found in the servers database\n");
		return -9;
	}
	
	if (errorCode)
	{
		printf("ClientSession::run:enc_parse_P_message errorCode is non zero: %d\n", errorCode);
		return -4;
	}
	
	San2::Utils::bytes srpM1;
	
	try
	{
		srpM1 = srpclient.getM1(srpSalt, srpB, sca);
	}
	catch(DragonSRP::DsrpException &e)
	{
		std::cout << "DsrpException: " << e.what() << std::endl;
		return -5;
	}
	
	rval = enc_construct_B_message(srpM1, request);
	
	if (rval)
	{
		printf("ClientSession::run:enc_construct_B_message failed: %d\n", rval);
		return -6;
	}
	
	if (m_swtx.sendReliableMessage(request, response) == false)
	{
		printf("sending B message failed\n");
		return -7;
	}
	
	San2::Utils::bytes srpM2;
	
	rval = enc_parse_Q_message(response, srpM2, errorCode);
	
	if (rval)
	{
		printf("ClientSession::run:enc_parse_Q_message failed: %d\n", rval);
		return -8;
	}
	
	if (errorCode == SH_ERRORCODE_AUTHENTICATIONFAILED)
	{
		printf("Authentication FAILED - bad password\n");
		return -9;
	}
	
	if (errorCode)
	{
		printf("ClientSession::run:enc_parse_Q_message errorCode is non zero: %d\n", errorCode);
		return -9;
	}
	
	// check M2
	
	San2::Utils::bytes K; // session key
	
	try 
	{
		K = sca.getSessionKey(srpM2); 
	}
	catch(DragonSRP::DsrpException &e)
	{
		std::cout << "Authentication failed - bad password or other protocol failure." << std::endl;
		std::cout << "DsrpException: " << e.what() << std::endl;
		return -10;
	}
	
	std::cout << "Authentication SUCCESSFUL." << std::endl;
		
	// ==============================================================================
	
	// Setup key derivator
	DragonSRP::HashKeyDerivator keydrv(K, SH_AES256_KEYLEN, SH_IVLEN, SH_SHA1_OUTPUTLEN);
	
	
	// Oposite keys on server!
	// Uses client keys!
	DragonSRP::DatagramEncryptor enc(keydrv.getClientEncryptionKey(), keydrv.getClientIV(), keydrv.getClientMacKey());
	// Uses server keys!
	DragonSRP::DatagramDecryptor dec(keydrv.getServerEncryptionKey(), keydrv.getServerIV(), keydrv.getServerMacKey());
	
	// ==============================================================================
	
	
	San2::Utils::bytes shellRequest, shellResponse;
	
	shellRequest = "hostname";
	getShellServerResponse(enc, dec, shellRequest, shellResponse);
	
	std::string shell = San2::Utils::bytes::bytes2string(shellResponse) + ">";
	
	while(1)
	{
		std::cout << shell;
		
		std::cin.getline(line, SH_TERMINAL_MAXLINLEN);
		
		if (strlen(line) == 0) continue;
		
		if (strcmp(line, "exit") == 0)
		{
			return 0; // ??
		}
		
		shellRequest = line;
		if (getShellServerResponse(enc, dec, shellRequest, shellResponse))
		{
			break;
		}
		
		for (unsigned int b = 0; b < shellResponse.size(); b++) printf("%c", shellResponse[b]); printf("\n");
	}
	
	
	// shellRequest = "This is a sample message";
	// getShellServerResponse(enc, dec, shellRequest, shellResponse);
	// printf("decpacket: "); for (int b = 0; b < shellResponse.size(); b++) printf("%c", shellResponse[b]); printf("\n");
	
	return 0;
}
void C1AffineSet<MatrixType, Policies>::move(DynSysType & dynsys, C1AffineSet& result) const
{
  // important: here we assume that m_r contains zero
  // this is assured by each constructor and each step of this algorithm

  const size_type dim = m_x.dimension();
  VectorType y(dim), rem(dim), enc(dim);
  MatrixType jacPhi(dim,dim), jacEnc(dim,dim), jacRem(dim,dim);
  MatrixType B(dim,dim), Q(dim,dim);

  VectorType xx = VectorType(*this);

  // the following function can throw an exception leaving output parameters in an inconsistent state
  // do not overwrite parameters of the set until we are sure that they are computed correctly
  dynsys.encloseC1Map(this->getCurrentTime(),
                    this->m_x, xx,          // input parameters
                    y, rem, enc,            // C^0 output
                    jacPhi, jacRem, jacEnc  // C^1 output
                    );


  result.m_x = y + rem;
  B = result.m_B = jacPhi * m_B;

  // ---------- C^0 - part -----------------

  // here we compute enclosure of the image after one iteration of the map/flow
  result.m_currentSet = result.m_x + result.m_B*this->m_r;

  // here we compute representation for the new set
  // xx is unnecessary now
  split(result.m_x, xx);

  // we assume that Policies provides algorithms for computation
  // of B, its inverse invB and updates
  this->Policies::computeBinvB(result.m_B,result.m_invB,this->m_r);

  // eventually we compute new representation of r
  result.m_r = (result.m_invB * B) * m_r + result.m_invB * xx;

  // ---------- C^1 - part -----------------
  MatrixType J = jacPhi + jacRem;
  result.m_D = J*this->m_D;
  B = result.m_Bjac = J*this->m_Bjac;

  // here we compute enclosure of the image after one iteration of the map/flow
  result.m_currentMatrix = J*this->m_currentMatrix;
  intersection(result.m_currentMatrix,result.m_D + result.m_Bjac*m_R,result.m_currentMatrix);

  // here we compute representation for the new set
  // jacRem is unnecessary now
  split(result.m_D, jacRem);

  // we assume that Policies provides algorithms for computation
  // of B, its inverse invB and updates
  this->Policies::computeBinvB(result.m_Bjac,result.m_invBjac,this->m_R);

  // eventually we compute new representation of r
  result.m_R = (result.m_invBjac * B) * m_R + result.m_invBjac * jacRem;

  result.setCurrentTime(this->getCurrentTime()+dynsys.getStep());
  result.setLastEnclosure(enc);
  result.setLastMatrixEnclosure(jacEnc);
}
Beispiel #30
0
Botan::SecureVector<boost::uint8_t> RsaEncoderDecoder::getEncodedSessionKey()
{
    Botan::PK_Encryptor_EME enc(*remoteKey_, "EME-PKCS1-v1_5");
    return enc.encrypt(sessionKey_.bits_of(), rng_);
}