예제 #1
0
/** Combined XEX mode encrypt/decrypt, since they're almost the same.
  * See xexEncryptInternal() and xexDecryptInternal() for a description of
  * what this does and what each parameter is.
  * \param out For encryption, this will be the resulting ciphertext. For
  *            decryption, this will be the resulting plaintext.
  * \param in For encryption, this will be the source plaintext. For
  *           decryption, this will be the source ciphertext.
  * \param n See xexEncryptInternal().
  * \param seq See xexEncryptInternal().
  * \param tweak_key See xexEncryptInternal().
  * \param encrypt_key See xexEncryptInternal().
  * \param is_decrypt To decrypt, use true. To encrypt, use false.
  */
static void xexEnDecrypt(uint8_t *out, uint8_t *in, uint8_t *n, uint8_t seq, uint8_t *tweak_key, uint8_t *encrypt_key, bool is_decrypt)
{
	uint8_t expanded_key[EXPANDED_KEY_SIZE];
	uint8_t delta[16];
	uint8_t buffer[16];
	uint8_t i;

	aesExpandKey(expanded_key, tweak_key);
	aesEncrypt(delta, n, expanded_key);
	for (i = 0; i < seq; i++)
	{
		doubleInGF(delta);
	}
	memcpy(buffer, in, 16);
	xor16Bytes(buffer, delta);
	aesExpandKey(expanded_key, encrypt_key);
	if (is_decrypt)
	{
		aesDecrypt(out, buffer, expanded_key);
	}
	else
	{
		aesEncrypt(out, buffer, expanded_key);
	}
	xor16Bytes(out, delta);
}
/*generate tag for plaintext with multiple block length*/
void tagGen(const u32 rk[], const u8 checksum[], const u8 Lprime[], const u8 U[], const u8 F[], u8 T[], unsigned long long int ptlen){
    u8 mask1[16], mask2[16];
    u8 temp[16];

    /*generate 3*Lprime and 7*Lprime and store them in mask1[] and mask2[] respectively*/
    memcpy(mask1, Lprime, 16);
    double_mask(mask1);
    memcpy(mask2, mask1, 16);
    xor_byte_string(Lprime, mask1, 16);

    double_mask(mask2);
    xor_byte_string(mask1, mask2, 16);

    /*generate 2^{lm+1}*3*Lprime and 2^{lm+1}*7*Lprime and store them in mask1[] and mask2[] respectively*/
    while(ptlen!=0){
        double_mask(mask1);
        double_mask(mask2);
        ptlen-=16;
    }
    double_mask(mask1);
    double_mask(mask2);

    /*produce the tag value*/
    xor_byte_string(checksum, mask1, 16);

    aesEncrypt(rk, mask1, temp);
    xor_byte_string(U, temp, 16);
    xor_byte_string(mask2, temp, 16);

    aesEncrypt(rk, temp, T);
    xor_byte_string(mask2, T, 16);
    xor_byte_string(F, T, 16);
}
/** Second part of deterministic 256 bit number generation.
  * See comments to generateDeterministic256() for details.
  * It was split into two parts to most efficiently use stack space.
  * \param out See generateDeterministic256().
  * \param hash See generateDeterministic256().
  * \param seed See generateDeterministic256().
  */
static NOINLINE void generateDeterministic256Part2(BigNum256 out, uint8_t *hash, uint8_t *seed)
{
	uint8_t expanded_key[EXPANDED_KEY_SIZE];

	aesExpandKey(expanded_key, &(seed[0]));
	aesEncrypt(&(out[0]), &(hash[0]), expanded_key);
	aesExpandKey(expanded_key, &(seed[16]));
	aesEncrypt(&(out[16]), &(hash[16]), expanded_key);
}
/*PX-MAC to process associated data*/
void PXMAC(const u32 mk[], const u32 sk[], const u8 L[], u8 V[], const u32 rk[], const u8 ad[], unsigned long long int adlen){

      int i=0;
      u8 pt[16], ct[16];
      u8 final_block_mask[16];


      memset(pt, 0, 16);
      memset(ct, 0, 16);

      /*process associated data except the last block*/
      memset(V, 0x00, 16);

      while(adlen>16){
            aesReducedEnc(mk+4*i, sk+12*i, ad, ct);
            xor_byte_string(ct, V, 16);

            ++i;
            ad+=16;
            adlen-=16;

            if(i==d){
                aesEncrypt(rk, V, ct);
                memcpy(V, ct, 16);
                i=0;
            }
      }

      /*process the last block*/
      memcpy(final_block_mask, L, 16);
      double_mask(final_block_mask);

      memcpy(pt, ad, adlen);

      if(adlen!=16){
            double_mask(final_block_mask);

            pt[adlen]=0x80;
            memset(pt+adlen+1, 0x00, 15-adlen);
      }

      aesReducedEnc(mk+4*i, sk+12*i, pt, ct);
      xor_byte_string(ct, V, 16);

      xor_byte_string(final_block_mask, V, 16);

      /*the finalization AES*/
      aesEncrypt(rk, V, ct);
      memcpy(V, ct, 16);

}
/*Setup the encryption key materials including mask key, and subkeys for SHELL-AES*/
void KeySetupEnc(u32 mk[], u32 sk[], u8 L[], u8 Lprime[], u8 keyprime[], const u32 rk[], const u8 key[]){

    u8 pt[16];
    u8 ct[16];

    int i;


    /* generate Keyprime for CENC*/
    for(i=0; i<16; ++i){
        keyprime[i]=key[i]^0xF0;
    }

    /* produce L for masks of AES*/
    memset(pt, 0x00, 16);
    aesEncrypt(rk, pt, L);

    /*produce the subkeys for auxiliary permutations*/
    for(i=1; i<=3*d; ++i){
        pt[15]=i;
        aesEncrypt(rk, pt, ct);

        sk[0]=GETU32(ct);
        sk[1]=GETU32(ct+4);
        sk[2]=GETU32(ct+8);
        sk[3]=GETU32(ct+12);

        sk=sk+4;
    }

    /*produce the mask keys for auxiliary permutations*/
    for(i=3*d+1; i<=4*d; ++i){
        pt[15]=i;

        aesEncrypt(rk, pt, ct);

        mk[0]=GETU32(ct);
        mk[1]=GETU32(ct+4);
        mk[2]=GETU32(ct+8);
        mk[3]=GETU32(ct+12);

        mk=mk+4;
    }

    /*produce Lprime for XEX layer*/

    memset(pt, 0xFF, 16);
    aesEncrypt(rk, pt, Lprime);
}
예제 #6
0
int main() { // todo add cli commands [-e encrypt][-d decrypt][-i filename][-k key][-o outfilename][-p print]
	std::string key("YELLOW SUBMARINE");

	aesEncrypt("eric.txt", key);
	system("pause");
	return 0;
}
예제 #7
0
void emberAfPluginAesMacAuthenticate(const uint8_t *key,
                                     const uint8_t *message,
                                     uint8_t messageLength,
                                     uint8_t *out)
{
  uint8_t key1[16];
  uint8_t key2[16];
  uint8_t lastBlock[16];
  uint8_t blockNum;
  bool isLastBlockComplete;
  uint8_t i;

  // Step 1
  generateSubKey(key, key1, key2);

  // Step 2 (we perform ceil(x/y) by doing: (x + y - 1) / y).
  blockNum = (messageLength + 15) / 16;

  // Step 3
  if (blockNum == 0) {
    blockNum = 1;
    isLastBlockComplete = false;
  } else {
    isLastBlockComplete = ((messageLength % 16) == 0);
  }

  // Step 4
  if (isLastBlockComplete) {
    xor128(message + (blockNum - 1)*16, key1, lastBlock);
  } else {
    padding(message + (blockNum - 1)*16, messageLength % 16, lastBlock);
    xor128(lastBlock, key2, lastBlock);
  }

  // Step 5
  initToConstZero(out);

  // Step 6
  for (i=0; i<blockNum - 1; i++) {
    xor128(out, message + i*16, out);
    aesEncrypt(out, key);
  }

  xor128(out, lastBlock, out);
  aesEncrypt(out, key);
}
/*PXENC layer*/
void PXENC(const u32 mk[], const u32 sk[], const u8 L[], u8 V[], u8 Z[], const u32 rk[], const u8 I[], unsigned long long int ptlen){

    int i=0;
    u8 ct[16];

    u8 final_block_mask[16];

    /*process I[] except the last block*/
    while(ptlen>16){
        aesReducedEnc(mk+4*i, sk+12*i, I, ct);
        xor_byte_string(ct, V, 16);

        memcpy(Z, V, 16);

        Z+=16;
        I+=16;
        ptlen-=16;
        ++i;

        if(i==d){
                aesEncrypt(rk, V, ct);
                memcpy(V, ct, 16);
                i=0;
        }

    }

    /*process the last block of I[]*/
    aesReducedEnc(mk+4*i, sk+12*i, I, ct);
    xor_byte_string(ct, V, 16);

    memcpy(final_block_mask, L, 16);
    double_mask(final_block_mask);
    double_mask(final_block_mask);
    double_mask(final_block_mask);

    xor_byte_string(final_block_mask, V, 16);

    memcpy(Z, V, 16);

    /*the finalization AES*/
    aesEncrypt(rk, V, ct);
    memcpy(V, ct, 16);

}
예제 #9
0
파일: Cypher.c 프로젝트: LanderlYoung/zasv
/*
 * Class:     Cypher
 * Method:    aesEncryption
 * Signature: ([B[B)[B
 */
JNIEXPORT void JNICALL Java_Cypher_aesEncryption
  (JNIEnv *env,  jclass obj, jbyteArray message, jbyteArray cypher) {
	  char *message_tmp = (char*)(*env)->GetByteArrayElements(env, message, 0);
	  char *cypher_tmp = (char*)(*env)->GetByteArrayElements(env, cypher, 0);
	  aesEncrypt(message_tmp, cypher_tmp);
	  (*env)->SetByteArrayRegion(env, cypher, 0, 16, cypher_tmp);
	  (*env)->ReleaseByteArrayElements(env, message, message_tmp, 0);
	  (*env)->ReleaseByteArrayElements(env, cypher, cypher_tmp, 0);
  }
/*PXDEC layer: the decryption of PXENC*/
void PXDEC(const u32 mk[], const u32 isk[], const u8 L[], u8 V[], const u8 Z[], const u32 rk[], u8 I[], unsigned long long int ctlen){

    int i=0;

    u8 ct[16];
    u8 final_block_mask[16];

    /*process the output Z[] of XEXLayerDec except the last block*/
    while(ctlen>16){
        xor_byte_string(Z, V, 16);
        aesReducedDec(mk+4*i, isk+12*i, V, ct);

        memcpy(I, ct, 16);
        memcpy(V, Z, 16);

        Z+=16;
        I+=16;
        ctlen-=16;
        ++i;

        if(i==d){
            i=0;
            aesEncrypt(rk, V, ct);
            memcpy(V, ct, 16);
        }
    }

    /*process the last block*/
    memcpy(final_block_mask, L, 16);
    double_mask(final_block_mask);
    double_mask(final_block_mask);
    double_mask(final_block_mask);


    xor_byte_string(Z, V, 16);
    xor_byte_string(final_block_mask, V, 16);

    aesReducedDec(mk+4*i, isk+12*i, V, I);

    /*apply the finalization AES*/
    memcpy(V, Z, 16);
    aesEncrypt(rk, V, ct);
    memcpy(V, ct, 16);
}
void test_beecrypt_rijndael_ecb()
{
    aesParam encctx;
    aesSetup(&encctx, (byte*)enckey, 256, ENCRYPT);

    for(unsigned int p = 0; p < bufferlen; p += 16)
	aesEncrypt(&encctx, (uint32_t*)(buffer + p), (uint32_t*)(buffer + p));

    aesParam decctx;
    aesSetup(&decctx, (byte*)enckey, 256, DECRYPT);

    for(unsigned int p = 0; p < bufferlen; p += 16)
	aesDecrypt(&decctx, (uint32_t*)(buffer + p), (uint32_t*)(buffer + p));
}
예제 #12
0
size32_t aesEncryptWithRSAEncryptedKey(MemoryBuffer &out, size32_t inSz, const void *inBytes, const CLoadedKey &publicKey)
{
    // create random AES key and IV
    char randomAesKey[aesMaxKeySize];
    char randomIV[aesBlockSize];
    fillRandomData(aesMaxKeySize, randomAesKey);
    fillRandomData(aesBlockSize, randomIV);

    size32_t startSz = out.length();
    DelayedSizeMarker mark(out);
    publicKeyEncrypt(out, aesMaxKeySize, randomAesKey, publicKey);
    mark.write();
    out.append(aesBlockSize, randomIV);

    DelayedSizeMarker aesSz(out);
    aesEncrypt(out, inSz, inBytes, aesMaxKeySize, randomAesKey, randomIV);
    aesSz.write();
    return out.length()-startSz;
}
예제 #13
0
파일: testaes.c 프로젝트: codeguru85/keygen
int main()
{
	int i, failures = 0;
	aesParam param;
	byte key[32];
	byte src[16];
	byte dst[16];
	byte chk[16];
	size_t keybits;

	for (i = 0; i < NVECTORS; i++)
	{
		keybits = fromhex(key, table[i].key) << 3;

		if (aesSetup(&param, key, keybits, table[i].op))
			return -1;

		fromhex(src, table[i].input);
		fromhex(chk, table[i].expect);

		switch (table[i].op)
		{
		case ENCRYPT:
			if (aesEncrypt(&param, (uint32_t*) dst, (const uint32_t*) src))
				return -1;
			break;
		case DECRYPT:
			if (aesDecrypt(&param, (uint32_t*) dst, (const uint32_t*) src))
				return -1;
			break;
		}

		if (memcmp(dst, chk, 16))
		{
			printf("failed vector %d\n", i+1);
			failures++;
		}

	}

	return failures;
}
예제 #14
0
int encoding(char* in, int inlen, char** out, int* outlen) {
    int ret;
    char* aes;
    int aes_len;
    char* b64;
    int b64_len;

    aes_len = (inlen / 16 + 1) * 16;
    aes = get_pre_aes_buffer(aes_len);

    if (aes == NULL) {
        syslog(LOG_ERR, "get aes buffer for aesEncrypt failed\n");
        return -1;
    }

    ret = aesEncrypt(in, inlen, aes, &aes_len);

    if (ret < 0) {
        syslog(LOG_ERR, "aesEncrypt failed ret %d\n", ret);
        return -2;
    }

    b64_len = (aes_len + 2) / 3 * 4; /* max base64 encode len */
    b64 = (char*)malloc(b64_len + 4);  /* 4 bytes for length field */

    if (b64 == NULL) {
        syslog(LOG_ERR, "malloc buffer for Base64Encode failed\n");
        return -3;
    }

    ret = Base64Encode(aes, aes_len, b64 + 4, &b64_len);

    if (ret < 0) {
        syslog(LOG_ERR, "Base64Encode failed ret %d\n", ret);
        return -4;
    }

    *out = b64;
    *(int*)b64 = htonl(b64_len);
    *outlen = b64_len + 4;
    return 0;
}
예제 #15
0
void initFlashData(int *success){
	int aesErr = 0; //error handling
	int rsaErr = 0;

//	hello(REP_TRUSTED_NAME);
	printf("In trusted mode initFlashData\n");
//	TRUSTED_DATA static char data[50000] = "Messenger: Choose your next words carefully, Leonidas. They may be your last as king.\nKing Leonidas: [to himself: thinking] \"Earth and water\"?\n[Leonidas unsheathes and points his sword at the Messenger's throat]\nMessenger: Madman! You're a madman!\nKing Leonidas: Earth and water? You'll find plenty of both down there.\nMessenger: No man, Persian or Greek, no man threatens a messenger!\nKing Leonidas: You bring the crowns and heads of conquered kings to my city steps. You insult my queen. You threaten my people with slavery and death! Oh, I've chosen my words carefully, Persian. Perhaps you should have done the same!\nMessenger: This is blasphemy! This is madness!\nKing Leonidas: Madness...?\n[shouting]\nKing Leonidas: THIS IS SPARTA!\n[Kicks the messenger down the well]\n";

//	32 bytes HEX key digits used as key to AES-128
//  TRUSTED_DATA static char sessionKey[33] = "0123456789abcdeffedcba9876543210"; AES key
    char sessionKey[32];
    generateAESKey(sessionKey); //generates a random 16 byte AES key (AES-128)

    nbytes = strlen(data);	//setting the global variable, used in aesDecrypt

    printf("\nEncrypting message with random generated AES-128 one time session key:\n%s",sessionKey);
	aesErr = aesEncrypt(sessionKey,data,encrypted);
	memcpy(contract,encrypted,nbytes);
#if 1
	if(aesErr != 0){
		printf("AES encryption failed.\n");
//		*success = 0;
	}
	else{
		printf("\nTry to print encrypted data! \n %s \n\n", encrypted);
		printf("\n Encrypting AES session key with RSA\n");
		rsaErr = rsaEncrypt(sessionKey,g_e,g_modulus,encryptedAESKey);
	}
	if(rsaErr != 0){
		printf("RSA encryption failed.\n");
		//*success = 0;
	}
	else if(aesErr == 0 && rsaErr == 0){
	//	*success = 1;
	}
#endif

}
/* XEX layer to produce ciphertext*/
void XEXLayerEnc(const u32 rk[], const u8 Lprime[], const u8 Z[], u8 C[], unsigned long long int ctlen){

    u8 mask[16];
    u8 temp[16];
    u8 ct[16];

    memcpy(mask, Lprime, 16);

    while(ctlen!=0){
        double_mask(mask);

        memcpy(temp, Z, 16);

        xor_byte_string(mask, temp, 16);
        aesEncrypt(rk, temp, ct);
        xor_byte_string(mask, ct, 16);
        memcpy(C, ct, 16);

        C+=16;
        Z+=16;
        ctlen-=16;
    }
}
예제 #17
0
파일: GCrypto.c 프로젝트: Ghost233/GCrypto
JNIEXPORT jbyteArray Java_com_ghost_GCrypto_GCrypto_JNIEncryptWithAES(JNIEnv* env, jobject obj, jbyteArray dataString, jbyteArray passwordString)
{
	crypto_cstring data;
	data.length  = (*env)->GetArrayLength(env, dataString);
	data.context = (jbyte *)malloc(data.length * sizeof(jbyte));
	(*env)->GetByteArrayRegion(env, dataString,0,data.length,data.context);

	crypto_cstring password;
	password.length  = (*env)->GetArrayLength(env, passwordString);
	password.context = (jbyte *)malloc(password.length * sizeof(jbyte));
	(*env)->GetByteArrayRegion(env, passwordString,0,password.length,password.context);

	crypto_cstring tmp = aesEncrypt(data.context, data.length, password.context, password.length);

	jbyte *by = (jbyte*) tmp.context;
	jbyteArray jarray = (*env)->NewByteArray(env, tmp.length);
	(*env)->SetByteArrayRegion(env, jarray, 0, tmp.length, by);

	free(data.context);
	free(password.context);

	return jarray;
}
예제 #18
0
HIDDEN void generateSubKey(const uint8_t *key, uint8_t *outKey1, uint8_t *outKey2)
{
  uint8_t L[16];
  uint8_t constRb[16];

  initToConstRb(constRb);

  // Step 1
  initToConstZero(L);
  aesEncrypt(L, key);

  // Step 2
  oneBitLeftShift(L, outKey1); // // K1:= L << 1;

  if (MSB(L)) { // K1:= (L << 1) XOR const_Rb;
    xor128(outKey1, constRb, outKey1);
  }
  // Step 3
  oneBitLeftShift(outKey1, outKey2); // // K2 := K1 << 1;

  if (MSB(outKey1)) { // K2 := (K1 << 1) XOR const_Rb;
    xor128(outKey2, constRb, outKey2);
  }
}
/*XLS function to process the non-full last block of plaintexts*/
void XLS(const u32 rk[], const u8 Lprime[], const u8 p[], unsigned long long int fb_ptlen, unsigned int nfb_ptlen, u8 c[], u8 tag[]){
    u8 mask1[16], mask2[16];
    u8 temp[16];
	// CHANGE VLA allocation changed to dynamic (for MSVC compiler)
	// u8 pt[16], ct[16], byte1[nfb_ptlen], byte2[nfb_ptlen];
	u8 pt[16], ct[16];
	u8* byte1 = new u8[nfb_ptlen];
	u8* byte2 = new u8[nfb_ptlen];
    int i;

    /*produce mask 3^2*Lprime, and save it to mask1[]*/
    memcpy(mask1, Lprime, 16);
    for(i=0; i<2; ++i){
        memcpy(temp, mask1, 16);
        double_mask(mask1);
        xor_byte_string(temp, mask1, 16);
    }

    /*produce mask 7^2*Lprime, and save it to mask2[]*/
    memcpy(mask2, Lprime, 16);
    for(i=0; i<2; ++i){
        memcpy(temp, mask2, 16);
        double_mask(mask2);
        xor_byte_string(mask2, temp, 16);
        double_mask(mask2);
        xor_byte_string(temp, mask2, 16);
    }

    /*produce the masks for E' and E'', and save them to mask1[] and mask2[] respectively*/
    while(fb_ptlen!=0){
        double_mask(mask1);
        double_mask(mask2);
        fb_ptlen-=16;
    }
    double_mask(mask1);
    double_mask(mask2);

    /*First round of XLS*/

    memcpy(pt, p, nfb_ptlen);
    memcpy(pt+nfb_ptlen, tag, 16-nfb_ptlen);

    /*apply E'*/
    xor_byte_string(mask1, pt, 16);
    aesEncrypt(rk, pt, ct);
    xor_byte_string(mask1, ct, 16);

    /*flip one bit*/
    ct[15-nfb_ptlen]^=0x01;

    memcpy(byte1, ct+16-nfb_ptlen, nfb_ptlen);
    memcpy(byte2, tag+16-nfb_ptlen, nfb_ptlen);

    /*MIX function*/
    MIX(byte1, byte2, nfb_ptlen);

    memcpy(ct+16-nfb_ptlen, byte1, nfb_ptlen);

    memcpy(pt, ct, 16);

    /*Second round of XLS*/

    /*apply E''*/
    xor_byte_string(mask2, pt, 16);
    aesEncrypt(rk, pt, ct);
    xor_byte_string(mask2, ct, 16);

    ct[15-nfb_ptlen]^=0x01;

    memcpy(byte1, ct+16-nfb_ptlen, nfb_ptlen);
    MIX(byte1, byte2, nfb_ptlen);

    memcpy(ct+16-nfb_ptlen, byte1, nfb_ptlen);
    memcpy(pt, ct, 16);

    /*the third round of XLS*/

    xor_byte_string(mask1, pt, 16);
    aesEncrypt(rk, pt, ct);
    xor_byte_string(mask1, ct, 16);

    /*produce ciphertext and tag*/
    memcpy(c, ct, nfb_ptlen);
    memcpy(tag, ct+nfb_ptlen, 16-nfb_ptlen);
    memcpy(tag+16-nfb_ptlen, byte2, nfb_ptlen);

	// CHANGE memory management (VLA allocation changed to dynamic)
	delete[] byte1;
	delete[] byte2;
}
/*
SHELL-AES decryption for plaintexts shorter than one blocks long:
parameters follow those of function shellaesEnc
*/
int shellaesDec_short(const u8 key[], const u8 nonce[], const u8 ad[], unsigned long long int adlen, const u8 c[], unsigned long long int ctlen, u8 p[], const u8 tag[]){

    u8 V[16], F[16], keyprime[16], L[16], Lprime[16], S[16], I[16];
    u32 mk[4*d], sk[12*d], rk[44], irk[44], rkprime[44];
    u8  pt1[16], pt2[16], ct1[16], ct2[16];
    u8 mask[16], mask1[16];
    u8 temp[16];

    int i, flag;

    /* key setup */
    aesKeySetupEnc(rk, key);
    KeySetupEnc(mk, sk, L, Lprime, keyprime, rk, key);
    aesKeySetupDec(irk, key);
    aesKeySetupEnc(rkprime, keyprime);

    memset(V, 0, 16);

    /*PX-MAC*/
    PXMAC(mk, sk, L, V, rk, ad, adlen);

    /*derive the block of ciphertext and save it to ct1[]*/

    memcpy(ct1, c, ctlen);
    for(i=ctlen; i<16; ++i){
        ct1[i]=tag[i-ctlen];
    }

    /*produce mask 3^3*Lprime*/
    memcpy(mask, Lprime, 16);
    for(i=0; i<3; ++i){
        memcpy(temp, mask, 16);
        double_mask(mask);
        xor_byte_string(temp, mask, 16);
    }

    /*produce mask 2^2*3^3*Lprime*/
    memcpy(mask1, mask, 16);
    double_mask(mask1);
    double_mask(mask1);

    /*decrypt to obtain I[]*/
    xor_byte_string(mask1, ct1, 16);
    aesDecrypt(irk, ct1, pt1);
    xor_byte_string(mask1, pt1, 16);

    xor_byte_string(V, pt1, 16);
    memcpy(ct1, pt1, 16);

    xor_byte_string(ct1, V, 16);

    xor_byte_string(mask, ct1, 16);
    aesDecrypt(irk, ct1, pt1);
    xor_byte_string(mask, pt1, 16);

    memcpy(I, pt1, 16);

    /*decrypt the plaintext*/
    CENC(rkprime, S, F, nonce, 16);
    xor_byte_string(S, pt1, 16);
    memcpy(p, pt1, ctlen);

    /*verify the validness of tag*/
    memcpy(pt2, I, 16);
    double_mask(mask);

    xor_byte_string(mask, pt2, 16);
    aesEncrypt(rk, pt2, ct2);
    xor_byte_string(mask, ct2, 16);

    xor_byte_string(V, ct2, 16);

    memcpy(pt2, ct2, 16);

    double_mask(mask1);

    xor_byte_string(mask1, pt2, 16);
    aesEncrypt(rk, pt2, ct2);
    xor_byte_string(mask1, ct2, 16);

    xor_byte_string(F, ct2, 16);


    flag=1;

    if(pt1[ctlen]!=0x80){
        flag=0;
    }

    for(i=ctlen+1; i<16; ++i){
        if(pt1[i]!=0){
            flag=0;
        }
    }

    for(i=0; i<ctlen; ++i){
        if(ct2[i]!=tag[i+16-ctlen]){
            flag=0;
        }
    }

    /*
     if(flag){
        printf("the plaintext is:\n");
        printf_byte_string(p, ctlen);
    }
    else{
        printf("the tag is invalid!");
    }
    */

    return flag;
}
/*
SHELL-AES encryption for plaintexts shorter than one blocks long:
parameters follow those of function shellaesEnc
*/
void shellaesEnc_short(const u8 key[], const u8 nonce[], const u8 ad[], unsigned long long int adlen, const u8 p[], unsigned long long int ptlen, u8 c[], u8 tag[]){

         u8 V[16], F[16], keyprime[16], L[16], Lprime[16], S[16], I[16];

         u32 mk[4*d], sk[12*d], rk[44], rkprime[44];

         u8 pt[16], pt1[16], pt2[16], ct1[16], ct2[16];
         u8 mask[16];
         u8 temp[16];
         int i;

         /*key setup*/
         aesKeySetupEnc(rk, key);
         KeySetupEnc(mk, sk, L, Lprime, keyprime, rk, key);
         aesKeySetupEnc(rkprime, keyprime);

         /*PXMAC: process the associated data and save output to V[]*/
         memset(V, 0, 16);
         PXMAC(mk, sk, L, V, rk, ad, adlen);

         /*CENC: process nonce and save the output to S[] and F[]*/
         CENC(rkprime, S, F, nonce, 16);


         /*pad p[] to a full block and save it to pt[]*/
         memset(pt, 0, 16);
         memcpy(pt, p, ptlen);
         pt[ptlen]=0x80;

         /*mask pt[] by xoring the output S[] of CENC, and save it to I[] */
         memcpy(I, S, 16);
         xor_byte_string(pt, I, 16);

         /*compute 3^3*Lprime and save it to mask[]*/
         memcpy(mask, Lprime, 16);
         for(i=0; i<3; ++i){
            memcpy(temp, mask, 16);
            double_mask(mask);
            xor_byte_string(temp, mask, 16);
         }

         /*compute XEX cipher with tweak of 3^3*Lprime and input I[], and save the output to ct1[]*/

         memcpy(pt1, I, 16);
         xor_byte_string(mask, pt1, 16);
         aesEncrypt(rk, pt1, ct1);
         xor_byte_string(mask, ct1, 16);

         /*compute XEX cipher with tweak of 2*3^3*Lprime and input I[], and save the output to ct2[]*/
         double_mask(mask);
         memcpy(pt2, I, 16);
         xor_byte_string(mask, pt2, 16);
         aesEncrypt(rk, pt2, ct2);
         xor_byte_string(mask, ct2, 16);

         /*compute XEX cipher with tweak of 2^2*3^3*Lprime and input of xoring ct1 and the output V of PX-MAC,
           and save the output to ct1[]*/
         xor_byte_string(ct1, V, 16);
         memcpy(pt1, V, 16);
         double_mask(mask);
         xor_byte_string(mask, pt1, 16);
         aesEncrypt(rk, pt1, ct1);
         xor_byte_string(mask, ct1, 16);

        /*compute XEX cipher with tweak of 2^3*3^3*Lprime and input of xoring ct2 and the updated V,
          and save the output to ct2[]*/
         xor_byte_string(ct2, V, 16);
         memcpy(pt2, V, 16);
         double_mask(mask);
         xor_byte_string(mask, pt2, 16);
         aesEncrypt(rk, pt2, ct2);
         xor_byte_string(mask, ct2, 16);

         /*xor ct2 with the output F of CENC*/
         xor_byte_string(F, ct2, 16);

         /*tag splitting:
         produce the ciphertext and tag from ct1 and ct2*/
         memcpy(c, ct1, ptlen);
         for(i=ptlen; i<16; ++i){
            tag[i-ptlen]=ct1[i];
         }
         for(i=0; i<ptlen; ++i){
            tag[16-ptlen+i]=ct2[i];
         }

        /*
        printf("ciphertext is: \n");
        printf_byte_string(c, ptlen);

        printf("tag value is: \n");
        printf_byte_string(tag, 16);
        */

}
예제 #22
0
파일: ExAnl.c 프로젝트: jasongwq/DacPhone
void Ex_Anl(u8 *data_buf)
{
    switch (*(data_buf + 2))
    {
    case 0X10:
    {
        AbsoluteOpticalEncoder_VAL = *(data_buf + 4);
        for (int i = 0; i < 8; ++i)
        {
            if (AbsoluteOpticalEncoder_VAL < AbsoluteOpticalEncoder_Apart[i])
            {
                RelayStata = i;
                break;
            }
        }
        Sys_Printf(Printf_USART, "\r\nAbsoluteOpticalEncoder_VAL:%d", AbsoluteOpticalEncoder_VAL);
        Sys_Printf(Printf_USART, "\r\nRelayStata:%d", RelayStata);
        break;
    }
    case 0X11:
    {
        if (*(data_buf + 4) < 8)
            AbsoluteOpticalEncoder_Apart[*(data_buf + 4)] = *(data_buf + 5);
        Sys_Printf(Printf_USART, "\r\nAbsoluteOpticalEncoder_Apart:\r\n");
        for (int i = 0; i < 8; i++)Sys_Printf(Printf_USART, " %d", AbsoluteOpticalEncoder_Apart[i]);
        break;
    }
    case 0X12:
    {
        TimeUnlock = *(data_buf + 4);
        Sys_Printf(Printf_USART, "\r\nTimeUnlock:%d", TimeUnlock);
        break;
    }
    case 0X13:
    {
        srand(SysTick_Clock());
        Sys_Printf(USART1, (char *)"\r\n%d", rand());

        unsigned char dat[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        unsigned char chainCipherBlock[16];
        unsigned char i;
        for (i = 0; i < 32; i++) AES_Key_Table[i] = i; //做运算之前先要设置好密钥,这里只是设置密钥的DEMO。

        memset(chainCipherBlock, 0x00, sizeof(chainCipherBlock));
        aesEncInit();//在执行加密初始化之前可以为AES_Key_Table赋值有效的密码数据
        aesEncrypt(dat, chainCipherBlock);//AES加密,数组dat里面的新内容就是加密后的数据。
        //aesEncrypt(dat+16, chainCipherBlock);//AES源数据大于16字节时,把源数据的指针+16就好了

        Sys_Printf(USART1, (char *)"\r\n");
        for (int i = 0; i < 16; ++i)   Sys_Printf(USART1, (char *)"%X ", dat[i]);

        memset(chainCipherBlock, 0x00, sizeof(chainCipherBlock)); //这里要重新初始化清空
        aesDecInit();//在执行解密初始化之前可以为AES_Key_Table赋值有效的密码数据
        aesDecrypt(dat, chainCipherBlock);//AES解密,密文数据存放在dat里面,经解密就能得到之前的明文。

        Sys_Printf(USART1, (char *)"\r\n");
        for (int i = 0; i < 16; ++i)   Sys_Printf(USART1, (char *)"%X ", dat[i]);
        break;
    }
    case 0X14:
    {
        ChipUniqueID32[2] = *(__IO u32 *)(0X1FFFF7E8); // 低字节
        ChipUniqueID32[1] = *(__IO u32 *)(0X1FFFF7EC); //
        ChipUniqueID32[0] = *(__IO u32 *)(0X1FFFF7F0); // 高字节
        Sys_Printf(USART1, (char *)"ChipUniqueID: %X %X %X", ChipUniqueID32[0], ChipUniqueID32[1], ChipUniqueID32[2]);
        Sys_Printf(USART1, (char *)"ChipUniqueID: %X %X %X %X %X %X %X %X %X %X %X %X", ChipUniqueID8[0], ChipUniqueID8[1], ChipUniqueID8[2],ChipUniqueID8[3], ChipUniqueID8[4], ChipUniqueID8[5],ChipUniqueID8[6], ChipUniqueID8[7], ChipUniqueID8[8],ChipUniqueID8[9], ChipUniqueID8[10], ChipUniqueID8[11]);
        break;
    }
    }
}
/*CENC to process nonce*/
void CENC(const u32 rkprime[], u8 S[], u8 F[], const u8 nonce[], unsigned long long int ptlen){

    u8 ctr[16];
    u8 G[16];
    u8 ct[16];
    int i, j=0;

    /*initialize ctr*/
    memset(ctr, 0, 16);
    memcpy(ctr, nonce, byte_length_nonce);

    /*produce the output S except the last block*/
    aesEncrypt(rkprime, ctr, G);

    while(ptlen>16){
        /*increase ctr by adding 1*/
        if(++ctr[15]==0){
            i=14;
            while(++ctr[i]==0){
                --i;
            }
        }
        /*update the value of G*/
        if(j==w){
            aesEncrypt(rkprime, ctr, G);
            j=0;
            continue;
        }

        aesEncrypt(rkprime, ctr, S);

        xor_byte_string(G, S, 16);

        S+=16;

        ptlen-=16;
        ++j;
    }

    /*produce the last block of S*/

    if(++ctr[15]==0){
          i=14;
          while(++ctr[i]==0){
               --i;
          }
    }

    if(j==w){
         aesEncrypt(rkprime, ctr, G);
         j=0;
         if(++ctr[15]==0){
            i=14;
            while(++ctr[i]==0){
                    --i;
            }
        }
    }

    aesEncrypt(rkprime, ctr, ct);
    xor_byte_string(G, ct, 16);

    memcpy(S, ct, ptlen);

    ++j;

    /*produce the value of F*/

    if(++ctr[15]==0){
          i=14;
          while(++ctr[i]==0){
               --i;
          }
    }

    if(j==w){
         aesEncrypt(rkprime, ctr, G);
         j=0;
         if(++ctr[15]==0){
            i=14;
            while(++ctr[i]==0){
                    --i;
            }
        }
    }

    aesEncrypt(rkprime, ctr, F);
    xor_byte_string(G, F, 16);

}
예제 #24
0
파일: main.c 프로젝트: sutajiokousagi/cpid
void doInteraction() {
  char *cmd;
  // i/o
  opRec oprec;
  unsigned char dataStr[256];
  // aes
  aesParam aesparam;
  byte aesSrc[16];
  byte aesDst[16];
  // rsa
  rsakp keypair;
  mpnumber m, cipher, signature;
  // sha1
  byte digest[20];
  char digestHex[41];
  sha1Param sha1param;
  
  int i;

  oprec.data = dataStr;
  oprec.dataLen = MAXDATLEN;

  while(1) {
    // reset the data string
    for( i = 0; i < MAXDATLEN; i++ ) {
      oprec.data[i] = '0';
    }
    oprec.dataLen = MAXDATLEN;

    // grab the string and parse it
    cmd = getString();
    if(parseString(cmd, &oprec) != 1) {
      oprec.dataLen = MAXDATLEN;
      continue;
    }
    
    switch(oprec.cipherType) {
    case CH_AES:
      for( i = 0; i < 16; i++ ) {
	aesSrc[i] = 0;
      }
      if(aesSetup(&aesparam, AESkeyTable[oprec.keyIndex].key, 128, oprec.opType == CH_ENCRYPT ? ENCRYPT : DECRYPT ))
	continue;
      fromhex(aesSrc, oprec.data);
      if( oprec.opType == CH_ENCRYPT ) {
	if( aesEncrypt(&aesparam, (uint32_t *)aesDst, (uint32_t *)aesSrc) )
	  continue;
      } else {
	if( aesDecrypt(&aesparam, (uint32_t *)aesDst, (uint32_t *)aesSrc) )
	  continue;
      }
      for( i = 0; i < 16; i++ ) {
	printf("%02X", aesDst[i] );
      }
      printf( "\n" );
      break;
    case CH_SGN:
      // init sha1
      if( sha1Reset( &sha1param ) )
	continue;
      if( sha1Update( &sha1param, oprec.data, oprec.dataLen ))
	continue;
      if( sha1Digest( &sha1param, digest ) )
	continue;
      
      // digest now contains the 160-bit message we want to sign
      toHex(digest, digestHex, 20);
      // digestHex now has the correct large number representation of the message
#if TESTING
      fprintf( stderr, "sha1 of message: %s\n", digestHex );
#endif
      // init rsa
      rsakpInit(&keypair);
      
      mpbsethex(&keypair.n, RSAkeyTable[oprec.keyIndex].rsa_n);
      mpnsethex(&keypair.e, RSAkeyTable[oprec.keyIndex].rsa_e);
      mpbsethex(&keypair.p, RSAkeyTable[oprec.keyIndex].rsa_p);
      mpbsethex(&keypair.q, RSAkeyTable[oprec.keyIndex].rsa_q);
      mpnsethex(&keypair.dp, RSAkeyTable[oprec.keyIndex].rsa_dp);
      mpnsethex(&keypair.dq, RSAkeyTable[oprec.keyIndex].rsa_dq);
      mpnsethex(&keypair.qi, RSAkeyTable[oprec.keyIndex].rsa_qi);

      mpnzero(&m);
      mpnzero(&cipher);
      mpnzero(&signature);

      mpnsethex(&m, digestHex);
      
      // we are now all set to do the signing
      // need to:
      // write signing alg here
      // make test case
      // this link is very helpful in writing this code:
      // http://tools.ietf.org/html/rfc3447#page-12
      rsapricrt(&keypair.n, &keypair.p, &keypair.q, &keypair.dp, &keypair.dq, &keypair.qi, &m, &signature);
      for( i = 0; i < signature.size; i++ ) {
	printf("%08X", signature.data[i] );
      }
      printf( "\n" );

#if TESTING
      mpnfree(&m);
      mpnzero(&m);
      rsapub(&keypair.n, &keypair.e, &signature, &m);
      for( i = 0; i < m.size; i++ ) {
	printf("%08X", m.data[i] );
      }
      printf( "\n" );
#endif

      rsakpFree(&keypair);
      break;
    case CH_VRF:
      rsakpInit(&keypair);
      
      mpbsethex(&keypair.n, RSAkeyTable[oprec.keyIndex].rsa_n);
      mpnsethex(&keypair.e, RSAkeyTable[oprec.keyIndex].rsa_e);
      mpbsethex(&keypair.p, RSAkeyTable[oprec.keyIndex].rsa_p);
      mpbsethex(&keypair.q, RSAkeyTable[oprec.keyIndex].rsa_q);
      mpnsethex(&keypair.dp, RSAkeyTable[oprec.keyIndex].rsa_dp);
      mpnsethex(&keypair.dq, RSAkeyTable[oprec.keyIndex].rsa_dq);
      mpnsethex(&keypair.qi, RSAkeyTable[oprec.keyIndex].rsa_qi);

      mpnzero(&m);
      mpnzero(&cipher);
      mpnzero(&signature);

      mpnsethex(&m, oprec.data);
      rsapub(&keypair.n, &keypair.e, &m, &cipher);

      for( i = 0; i < cipher.size; i++ ) 
	printf("%08X", cipher.data[i]);
      printf( "\n" );
      break;
      
    case CH_SHA:
      // init sha1
      if( sha1Reset( &sha1param ) )
	continue;
      if( sha1Update( &sha1param, oprec.data, oprec.dataLen ))
	continue;
      if( sha1Digest( &sha1param, digest ) )
	continue;
      
      // digest now contains the 160-bit message we want to sign
      toHex(digest, digestHex, 20);
      printf( "%s\n", digestHex );
      break;
      
    default:
      fprintf( stderr, "unknown cipher type caught.\n" );
    } // switch
    
    // prevent the leak!
#if (TESTING == 0)
    if( cmd != NULL )
      free(cmd);
#endif
  } // while
  
}