示例#1
1
文件: aes_code.c 项目: abgood/sqgo
/* AES解密 */
char *aes_dec(char *pawd, int is_print) {
    char *plain = "yunwei@love7road";
    unsigned char iv[AES_BLOCK_SIZE] = {0};
    unsigned char *input;
    int len;
    AES_KEY key;

    /* 设置密钥 */
    if (AES_set_decrypt_key((const unsigned char *)plain, LEN_128, &key) < 0) {
        fprintf(stderr, "Unable to set encryption key in AES\n");
    }

    /* 待加密数据长度 */
    len = strlen(pawd);

    /* 态度分配明文串 */
    input = (unsigned char *)calloc(len, sizeof(unsigned char));
    char *string = (char *)calloc(len, sizeof(char *));

    /* 16进制字符串转换成byte */
    hexstr2byte(input, pawd, len);

    /* 解密 */
    AES_cbc_encrypt(input, (unsigned char *)string, len, &key, iv, AES_DECRYPT);
    if (is_print) {
        printf("%s\n", string);
    }
    return string;
}
示例#2
0
int aes_encrypt(void *in, size_t len, unsigned char **out, unsigned char *iv, unsigned char *key)
{
    AES_KEY aeskey;
    int ret;

    if (!len)
        return 0;

    ret = AES_set_encrypt_key(key, 256, &aeskey);
    assert(!ret);

    printf("(len: %ld pad: %ld)\n", len, len % 16);
    len += len % 16;

    *out = calloc(1, len); // consider padding..
    assert(*out);

#ifdef SKIP_LAST_WORD
    AES_cbc_encrypt(in, *out, len-4, &aeskey, iv, AES_ENCRYPT); 
    memcpy(*out + (len - 4), in + (len - 4), 4);
#else
    AES_cbc_encrypt(in, *out, len, &aeskey, iv, AES_ENCRYPT); 
#endif

    printf("\nplaintext (excerpt):\n");
    print_hex(in, 128, 0);

    printf("ciphertext (excerpt):\n");
    print_hex(*out, 128, 0);

    return 0;
}
示例#3
0
uint8_t *aos_cipher_decrypt(struct aos_encryption *enc, const uint8_t *in, unsigned int length)
{
	uint8_t *decrypted;
	unsigned int done = 0;
	
	decrypted = (uint8_t *)malloc(length);
	if(!decrypted)
		return NULL;
	
	while(done < length) {
		uint8_t iv[AES_BLOCK_SIZE];
		uint8_t data[AES_BLOCK_SIZE];
		struct aos_block *block = (struct aos_block *)&data;
		
		memcpy(iv, enc->iv, AES_BLOCK_SIZE);
		
		AES_cbc_encrypt(&in[done], data, AES_BLOCK_SIZE, &enc->key, iv, AES_DECRYPT);
		memcpy(&decrypted[done], &data, AES_BLOCK_SIZE);
		done += AES_BLOCK_SIZE;
		
		AES_cbc_encrypt(&in[done], &decrypted[done], block->length-AES_BLOCK_SIZE, &enc->key, iv, AES_DECRYPT);
		done += block->length-AES_BLOCK_SIZE;
	}
	
	return decrypted;
}
static int blockchain_decrypt(unsigned char *derived_key, unsigned char *data)
{
	unsigned char out[SAFETY_FACTOR];
	AES_KEY akey;
	unsigned char iv[16];
	memcpy(iv, cur_salt->data, 16);

	if(AES_set_decrypt_key(derived_key, 256, &akey) < 0) {
		fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n");
	}
	AES_cbc_encrypt(data + 16, out, 16, &akey, iv, AES_DECRYPT);
	/* various tests */
	if (out[0] != '{') // fast test
		return -1;

	// "guid" will be found in the first block
	if (memmem(out, 16, "\"guid\"", 6)) {
		memcpy(iv, cur_salt->data, 16); //IV has to be reset.
		AES_cbc_encrypt(data + 16, out, SAFETY_FACTOR, &akey, iv, AES_DECRYPT);
		if (memmem(out, SAFETY_FACTOR, "\"sharedKey\"", 11) &&
			memmem(out, SAFETY_FACTOR, "\"options\"", 9))
			// Note, we 'could' check that the guid and sharedKey values are
			// 'valid' GUID's, but there really is no point. We already have
			// 2^216 confidence in the simple text strings being found.
			return 0;
	}
	return -1;
}
示例#5
0
// main entrypoint
int main(int argc, char **argv)
{
    int keylength;
    printf("Give a key length [only 128 or 192 or 256!]:\n");
    scanf("%d", &keylength);

    /* generate a key with a given length */
    unsigned char aes_key[keylength/8];
    memset(aes_key, 0, keylength/8);
    if (!RAND_bytes(aes_key, keylength/8))
        exit(-1);

    /* input struct creation */
    size_t inputslength = sizeof(USR_TICKET);
    USR_TICKET ticket;
    ticket.ticketId = 1;
    time_t now = time(NULL);
    strftime(ticket.date, 20, "%Y-%m-%d", localtime(&now));
    strcpy(ticket.username, "Hello AES");

    printf("Username - %s\n", ticket.username);
    printf("Ticket Id - %d\n", ticket.ticketId);
    printf("Date - %s\n", ticket.date);

    /* init vector */
    unsigned char iv_enc[AES_BLOCK_SIZE], iv_dec[AES_BLOCK_SIZE];
    RAND_bytes(iv_enc, AES_BLOCK_SIZE);
    memcpy(iv_dec, iv_enc, AES_BLOCK_SIZE);

    // buffers for encryption and decryption
    const size_t encslength = ((inputslength + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
    unsigned char enc_out[encslength];
    unsigned char dec_out[inputslength];
    memset(enc_out, 0, sizeof(enc_out));
    memset(dec_out, 0, sizeof(dec_out));

    // so i can do with this aes-cbc-128 aes-cbc-192 aes-cbc-256
    AES_KEY enc_key, dec_key;
    AES_set_encrypt_key(aes_key, keylength, &enc_key);
    AES_cbc_encrypt((unsigned char *)&ticket, enc_out, encslength, &enc_key, iv_enc, AES_ENCRYPT);

    AES_set_decrypt_key(aes_key, keylength, &dec_key);
    AES_cbc_encrypt(enc_out, dec_out, encslength, &dec_key, iv_dec, AES_DECRYPT);

    printf("original:\t");
    hex_print((unsigned char *)&ticket, inputslength);

    printf("encrypt:\t");
    hex_print(enc_out, sizeof(enc_out));

    printf("decrypt:\t");
    hex_print(dec_out, sizeof(dec_out));

    USR_TICKET * dyc = (USR_TICKET *)dec_out;
    printf("Username - %s\n", dyc->username);
    printf("Ticket Id - %d\n", dyc->ticketId);
    printf("Date - %s\n", dyc->date);
    return 0;
}
int WXBizMsgCrypt::AES_CBCDecrypt( const char * sSource, const uint32_t iSize,
        const char * sKey, uint32_t iKeySize, std::string * poResult )
{
    if ( !sSource || !sKey || iSize < kAesKeySize || iSize % kAesKeySize != 0 || !poResult)
    {
        return -1;
    }
    
    poResult->clear();

    unsigned char * out = (unsigned char*)malloc( iSize );
    if(NULL == out)
    {
        return -1;
    }

    unsigned char key[ kAesKeySize ] = { 0 };
    unsigned char iv[ kAesIVSize ] = {0} ;
    memcpy( key, sKey, iKeySize > kAesKeySize ? kAesKeySize : iKeySize );
    memcpy(iv, key, sizeof(iv) < sizeof(key) ? sizeof(iv) : sizeof(key));

    int iReturnValue = 0;
    AES_KEY aesKey;
    AES_set_decrypt_key( key, 8 * kAesKeySize, &aesKey );
    AES_cbc_encrypt( (unsigned char *)sSource, out, iSize, &aesKey, iv ,AES_DECRYPT);
    if( out[iSize-1] > 0 && out[iSize-1] <= kAesKeySize && (iSize - out[iSize-1]) > 0 )
    {
        poResult->append( (char *)out , iSize - out[iSize-1] );
    } else {
        iReturnValue = -1;
    }

    FREE_PTR(out);
    return iReturnValue;
}
/*============================================================================
 * OpcUa_P_OpenSSL_AES_CBC_Encrypt
 *===========================================================================*/
OpcUa_StatusCode OpcUa_P_OpenSSL_AES_CBC_Encrypt(
    OpcUa_CryptoProvider*   a_pProvider,
    OpcUa_Byte*             a_pPlainText,
    OpcUa_UInt32            a_plainTextLen,
    OpcUa_Key*              a_key,
    OpcUa_Byte*             a_pInitalVector,
    OpcUa_Byte*             a_pCipherText,
    OpcUa_UInt32*           a_pCipherTextLen)
{
    AES_KEY         key;

    OpcUa_Byte      pInitalVector[16];

    OpcUa_InitializeStatus(OpcUa_Module_P_OpenSSL, "AES_CBC_Encrypt");

    OpcUa_ReferenceParameter(a_pProvider);

    OpcUa_ReturnErrorIfArgumentNull(a_pPlainText);
    OpcUa_ReturnErrorIfArgumentNull(a_key);
    OpcUa_ReturnErrorIfArgumentNull(a_key->Key.Data);
    OpcUa_ReturnErrorIfArgumentNull(a_pInitalVector);
    OpcUa_ReturnErrorIfArgumentNull(a_pCipherTextLen);

    if(a_plainTextLen % 16 != 0)
    {
        uStatus = OpcUa_BadInvalidArgument;
        OpcUa_GotoErrorIfBad(uStatus);
    }

    *a_pCipherTextLen = a_plainTextLen;

    /* if just the output length is needed for the caller of this function */
    if(a_pCipherText == OpcUa_Null)
    {
        OpcUa_ReturnStatusCode;
    }

    /* we have to pass the key length in bits instead of bytes */
    if(AES_set_encrypt_key(a_key->Key.Data, a_key->Key.Length * 8, &key) < 0)
    {
        uStatus = OpcUa_Bad;
        OpcUa_GotoErrorIfBad(uStatus);
    }

    /* copy the IV because the AES_cbc_encrypt function overwrites it. */
    OpcUa_P_Memory_MemCpy(pInitalVector, 16, a_pInitalVector, 16);

    /* encrypt data */
    AES_cbc_encrypt(    a_pPlainText,
                        a_pCipherText,
                        a_plainTextLen,
                        &key,
                        pInitalVector,
                        AES_ENCRYPT);

OpcUa_ReturnStatusCode;
OpcUa_BeginErrorHandling;

OpcUa_FinishErrorHandling;
}
示例#8
0
文件: aes.hpp 项目: JaewookYim/salm
			void decrypt(AES_KEY &ctx, decrypt_output_type &dst, const decrypt_input_type &src, iv_type &iv)
			{
				// 16 블록(bytes)의 배수가 아닐경우 예외, 패딩을 사용할 것.
				if (0 != src.size() % 16) throw salm::exception("block size should be a fixed multiple", salm::INVALID_BAD_MULTIPLE);

				AES_cbc_encrypt(&src[0], &dst[0], src.size(), &ctx, &iv[0], AES_DECRYPT);
			}
static int akcdecrypt(unsigned char *derived_key, unsigned char *data)
{
	unsigned char out[CTLEN];
	int pad, n, i, key_size;
	AES_KEY akey;
	unsigned char iv[16];
	memcpy(iv, data + CTLEN - 32, 16);

	if(AES_set_decrypt_key(derived_key, 128, &akey) < 0) {
		fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n");
	}
	AES_cbc_encrypt(data + CTLEN - 16, out + CTLEN - 16, 16, &akey, iv, AES_DECRYPT);

	// now check padding
	pad = out[CTLEN - 1];
	if(pad < 1 || pad > 16) /* AES block size is 128 bits = 16 bytes */
		// "Bad padding byte. You probably have a wrong password"
		return -1;
	n = CTLEN - pad;
	key_size = n / 8;
	if(key_size != 128 && key_size != 192 && key_size != 256)
		// "invalid key size"
		return -1;
	for(i = n; i < CTLEN; i++)
		if(out[i] != pad)
			// "Bad padding. You probably have a wrong password"
			return -1;
	return 0;
}
示例#10
0
void Ipdb::EncMsg(GT M, string Msg, string fname)
{
	Big aes_key_big = pfc->hash_to_aes_key(M);
	char aes_key_char[AES_SECURITY/8];
	aes_key_char << aes_key_big;

	// Crypt using openssl cbc
	/* init vector */
	unsigned char iv_enc[AES_BLOCK_SIZE];
	for(int i=0;i<AES_BLOCK_SIZE;i++)
		iv_enc[i]=0;

	// Create sha256 for Msg and add first 128 bit at the end of it
	string sha = stdsha256(Msg);
	sha = sha.substr(0,16);
	Msg = Msg+sha;

	// buffers for encryption
	size_t inputslength = Msg.size();
	const size_t encslength = ((inputslength + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
	unsigned char enc_out[encslength];
	memset(enc_out, 0, sizeof(enc_out));

	// so i can do with this aes-cbc-128 aes-cbc-192 aes-cbc-256
	AES_KEY enc_key;
	AES_set_encrypt_key((const unsigned char *)aes_key_char, AES_SECURITY, &enc_key);
	AES_cbc_encrypt((const unsigned char *)Msg.c_str(), enc_out, inputslength, &enc_key, iv_enc, AES_ENCRYPT);

	append_file(fname,enc_out, encslength, NULL);
}
示例#11
0
文件: aes_jh.c 项目: rmayur/TORUpload
/*
 * class_AES_decrypt:
 * decrypt IN of LEN bytes
 * into a newly malloc'ed buffer
 * that is returned in OUT of OUT_LEN bytes long
 * using DEC_KEY.
 *
 * It is the *caller*'s job to free(out).
 * In and out lengths will always be different because of manditory padding.
 */
void class_AES_decrypt_with_padding(unsigned char *in, int len, unsigned char **out, int *out_len, AES_KEY *dec_key)
{
	unsigned char ivec[AES_KEY_LENGTH_IN_BITS/8];
	/*
	 * Don't use a 0 IV in the real world,
	 * see http://en.wikipedia.org/wiki/Initialization_vector for why. 
	 * Fortunately class projects are not the real world.
	 */
	memset(ivec, 0, sizeof(ivec));

	*out = (unsigned char *)malloc(len);
	assert(*out);

	AES_cbc_encrypt(in, *out, len, dec_key, ivec, AES_DECRYPT);

	/*
	 * Now undo padding.
	 */
	int padding_used = (int)(*out)[len-1];
	assert(padding_used > 0 && padding_used <= AES_KEY_LENGTH_IN_CHARS); /* or corrupted data */
	*out_len = len - padding_used;
	/*
	 * We actually return a malloc'ed buffer that is longer
	 * then out_len, but the memory system takes care of that for us. 
	 */

}
示例#12
0
/**
 * mega_aes_key_decrypt_cbc:
 * @aes_key: a #MegaAesKey
 * @cipher: UBase64 encoded ciphertext.
 *
 * Decrypt UBase64 encoded ciphertext blocks using AES key in CBC mode with zero IV.
 *
 * Returns: (transfer full): UBase64 encoded ciphertext.
 */
GBytes* mega_aes_key_decrypt_cbc(MegaAesKey* aes_key, const gchar* cipher)
{
    guchar iv[AES_BLOCK_SIZE] = {0};
    guchar* cipher_raw;
    guchar* plain;
    gsize cipherlen = 0;

    g_return_val_if_fail(MEGA_IS_AES_KEY(aes_key), NULL);
    g_return_val_if_fail(cipher != NULL, NULL);

    cipher_raw = mega_base64urldecode(cipher, &cipherlen);
    if (cipher_raw == NULL)
        return NULL;

    if (cipherlen % 16 != 0)
    {
        g_free(cipher_raw);
        return NULL;
    }

    plain = g_malloc0(cipherlen + 1);
    AES_cbc_encrypt(cipher_raw, plain, cipherlen, &aes_key->priv->dec_key, iv, 0);
    g_free(cipher_raw);

    return g_bytes_new_take(plain, cipherlen);
}
示例#13
0
static void cacheChunk(FileVaultInfo* info, uint32_t chunk) {
	unsigned char buffer[info->blockSize];
	unsigned char msgDigest[FILEVAULT_MSGDGST_LENGTH];
	uint32_t msgDigestLen;

	if(chunk == info->curChunk) {
		return;
	}

	if(info->dirty) {
		writeChunk(info);
	}

	info->file->seek(info->file, chunk * info->blockSize + info->dataOffset);
	info->file->read(info->file, buffer, info->blockSize);

	info->curChunk = chunk;

	FLIPENDIAN(chunk);
	HMAC_Init_ex(&(info->hmacCTX), NULL, 0, NULL, NULL);
	HMAC_Update(&(info->hmacCTX), (unsigned char *) &chunk, sizeof(uint32_t));
	HMAC_Final(&(info->hmacCTX), msgDigest, &msgDigestLen);

	AES_cbc_encrypt(buffer, info->chunk, info->blockSize, &(info->aesKey), msgDigest, AES_DECRYPT);
}
示例#14
0
/**
  Performs AES decryption on a data buffer of the specified size in CBC mode.

  This function performs AES decryption on data buffer pointed by Input, of specified
  size of InputSize, in CBC mode.
  InputSize must be multiple of block size (16 bytes). This function does not perform
  padding. Caller must perform padding, if necessary, to ensure valid input data size.
  Initialization vector should be one block size (16 bytes).
  AesContext should be already correctly initialized by AesInit(). Behavior with
  invalid AES context is undefined.

  If AesContext is NULL, then return FALSE.
  If Input is NULL, then return FALSE.
  If InputSize is not multiple of block size (16 bytes), then return FALSE.
  If Ivec is NULL, then return FALSE.
  If Output is NULL, then return FALSE.

  @param[in]   AesContext  Pointer to the AES context.
  @param[in]   Input       Pointer to the buffer containing the data to be encrypted.
  @param[in]   InputSize   Size of the Input buffer in bytes.
  @param[in]   Ivec        Pointer to initialization vector.
  @param[out]  Output      Pointer to a buffer that receives the AES encryption output.

  @retval TRUE   AES decryption succeeded.
  @retval FALSE  AES decryption failed.

**/
BOOLEAN
EFIAPI
AesCbcDecrypt (
  IN   VOID         *AesContext,
  IN   CONST UINT8  *Input,
  IN   UINTN        InputSize,
  IN   CONST UINT8  *Ivec,
  OUT  UINT8        *Output
  )
{
  AES_KEY  *AesKey;
  UINT8    IvecBuffer[AES_BLOCK_SIZE];

  //
  // Check input parameters.
  //
  if (AesContext == NULL || Input == NULL || (InputSize % AES_BLOCK_SIZE) != 0) {
    return FALSE;
  }

  if (Ivec == NULL || Output == NULL || InputSize > INT_MAX) {
    return FALSE;
  }

  AesKey = (AES_KEY *) AesContext;
  CopyMem (IvecBuffer, Ivec, AES_BLOCK_SIZE);

  //
  // Perform AES data decryption with CBC mode
  //
  AES_cbc_encrypt (Input, Output, (UINT32) InputSize, AesKey + 1, IvecBuffer, AES_DECRYPT);

  return TRUE;
}
示例#15
0
char *BasketUtils::openssl_crypt(char *data, int datalen, char *key, char *iv, int enc)
{
    char *temp_iv = new char[16];
    bastrcpy(temp_iv, iv, 16);

    AES_KEY aes_key;
    if ( enc == AES_ENCRYPT )
        AES_set_encrypt_key((unsigned char*)key, qstrlen(key)*8, &aes_key);
    else
        AES_set_decrypt_key((unsigned char*)key, qstrlen(key)*8, &aes_key);

    quint8 *out_data = new quint8[datalen];
    if ( !out_data ) {
        errorMsg = trUtf8("Ошибка выделения памяти для выходного буфера!");
        errorState = true;
        return NULL;
    }

    AES_cbc_encrypt((unsigned char*)data, (unsigned char*)out_data, datalen, &aes_key, (unsigned char *)temp_iv, enc);
    if ( !out_data ) {
        errorMsg = trUtf8("Ошибка процесса расшифровки данных!");
        errorState = true;
        return NULL;
    }
    delete [] temp_iv;

    return (char *)out_data;
}
示例#16
0
文件: htcaes.c 项目: 0x2b/ruuveal
int htc_aes_encrypt_chunk(char *buf, int size, char *key, char *iv)
{
    AES_KEY enc_key;

    AES_set_encrypt_key(key, 8*HTC_AES_KEYSIZE, &enc_key);
    AES_cbc_encrypt(buf, buf, size, &enc_key, iv, AES_ENCRYPT);
}
示例#17
0
void decrypt_chunk(uint8_t *ctext, uint8_t *ptext, uint32_t chunk_no)
{
  uint8_t iv[CIPHER_BLOCKSIZE];

  compute_iv(chunk_no, iv);
  AES_cbc_encrypt(ctext, ptext, CHUNK_SIZE, &aes_decrypt_key, iv, AES_DECRYPT);
}
示例#18
0
文件: aes_code.c 项目: abgood/sqgo
/* AES加密 */
void aes_enc(char *string) {
    char *plain = "yunwei@love7road";
    unsigned char iv[AES_BLOCK_SIZE] = {0};
    unsigned char *output;
    int len;
    AES_KEY key;

    /* 设置密钥 */
    if (AES_set_encrypt_key((const unsigned char *)plain, LEN_128, &key) < 0) {
        fprintf(stderr, "Unable to set encryption key in AES\n");
    }

    /* 待加密数据长度 */
    if ((strlen(string) + 1) % AES_BLOCK_SIZE == 0) {
        len = strlen(string) + 1;
    } else {
        len = ((strlen(string) + 1) / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE;
    }

    /* 动态分配密文串 */
    output = (unsigned char *)calloc(len, sizeof(unsigned char));
    char *pawd = (char *)calloc(len, sizeof(char *));

    /* 加密 */
    AES_cbc_encrypt((unsigned char *)string, output, len, &key, iv, AES_ENCRYPT);

    /* byte转换16进制字符串 */
    byte2hexstr(pawd, output, len);
    printf("Your Message is Encrypted: %s\n", pawd);

}
示例#19
0
static void crypt_all(int count)
{
	int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
	for (index = 0; index < count; index++)
#endif
	{
		unsigned char master[32];
		unsigned char output[1024];
		unsigned char *iv_in;
		unsigned char iv_out[16];
		int size;
		int page_sz = 1008; /* 1024 - strlen(SQLITE_FILE_HEADER) */
		int reserve_sz = 16; /* for HMAC off case */
		AES_KEY akey;
		pbkdf2((unsigned char *)saved_key[index],  strlen(saved_key[index]), cur_salt->salt, 16, ITERATIONS, (uint32_t *)master);
		memcpy(output, SQLITE_FILE_HEADER, FILE_HEADER_SZ);
		size = page_sz - reserve_sz;
		iv_in = cur_salt->data + size + 16;
		memcpy(iv_out, iv_in, 16);

		if (AES_set_decrypt_key(master, 256, &akey) < 0) {
			fprintf(stderr, "AES_set_derypt_key failed!\n");
		}
		/* decrypting 24 bytes is enough */
		AES_cbc_encrypt(cur_salt->data + 16, output + 16, 24, &akey, iv_out, AES_DECRYPT);
		if (verify_page(output) == 0) {
			cracked[index] = 1;
		}
		else
			cracked[index] = 0;
	}
}
示例#20
0
void  My_AES_CBC_Encrypt(u8 *key, u8 *InputMessage,  u32 InputMessageLength, u8 * OutputMessage)
{
	u8 * InBuf_ptr = InputMessage;
	int  length_in_pad = 0;
	AES_KEY   ass_key;
	u8 iv[CRL_AES_BLOCK] = {0};
//	printf("key:%s\n", key);
	int i;
//	printf("IV:");
	for(i = 0; i < CRL_AES_BLOCK; i++){
		iv[i] = IV[i];
//		printf("%d ", iv[i]);
	}
//	printf("\n");
//	printf("KEYB:");
	for(i = 0; i < CRL_AES_BLOCK; i++){
//		printf("%d ", KEY.KEYB[i]);
	}
//	printf("\n");
	memset(&ass_key, 0, sizeof(AES_KEY));
	if(AES_set_encrypt_key(key, 128, &ass_key)<0){
		printf("AES set key error...\n");
		return ;
	}
	
	AES_cbc_encrypt(InputMessage, OutputMessage, InputMessageLength, &ass_key, iv, AES_ENCRYPT);
}
示例#21
0
文件: 8900.c 项目: mucit/opensn0w
AbstractFile *createAbstractFileFrom8900(AbstractFile * file)
{
	Info8900 *info;
	unsigned char ivec[16];
	AbstractFile *toReturn;

	if (!file) {
		return NULL;
	}

	info = (Info8900 *) malloc(sizeof(Info8900));
	info->file = file;
	file->seek(file, 0);
	file->read(file, &(info->header), sizeof(info->header));
	flipApple8900Header(&(info->header));
	if (info->header.magic != SIGNATURE_8900) {
		free(info);
		return NULL;
	}

	AES_set_encrypt_key(key837, sizeof(key837) * 8,
			    &(info->encryptKey));
	AES_set_decrypt_key(key837, sizeof(key837) * 8,
			    &(info->decryptKey));

	info->buffer = malloc(info->header.sizeOfData);
	file->read(file, info->buffer, info->header.sizeOfData);

	if (info->header.format == 3) {
		memset(ivec, 0, 16);
		AES_cbc_encrypt(info->buffer, info->buffer,
				info->header.sizeOfData, &(info->decryptKey),
				ivec, AES_DECRYPT);
	}

	info->dirty = FALSE;
	info->exploit = FALSE;

	info->offset = 0;

	file->seek(file,
		   sizeof(info->header) + info->header.footerSignatureOffset);
	file->read(file, info->footerSignature, 0x80);

	info->footerCertificate =
	    (unsigned char *)malloc(info->header.footerCertLen);
	file->seek(file, sizeof(info->header) + info->header.footerCertOffset);
	file->read(file, info->footerCertificate, info->header.footerCertLen);

	toReturn = (AbstractFile *) malloc(sizeof(AbstractFile));
	toReturn->data = info;
	toReturn->read = read8900;
	toReturn->write = write8900;
	toReturn->seek = seek8900;
	toReturn->tell = tell8900;
	toReturn->getLength = getLength8900;
	toReturn->close = close8900;
	toReturn->type = AbstractFileType8900;
	return toReturn;
}
示例#22
0
void closeImg3(AbstractFile* file) {
	Img3Info* info = (Img3Info*) file->data;

	if(info->dirty) {
		if(info->encrypted) {
			uint32_t sz = info->data->header->dataSize;
			if (info->decryptLast) {
				sz = info->data->header->size;
			}
			uint8_t ivec[16];
			memcpy(ivec, info->iv, 16);
			AES_cbc_encrypt(info->data->data, info->data->data, (sz / 16) * 16, &(info->encryptKey), ivec, AES_ENCRYPT);
		}

		info->file->seek(info->file, 0);
		info->root->header->dataSize = 0;	/* hack to make certain writeImg3Element doesn't preallocate */
		info->root->header->size = 0;
		writeImg3Element(info->file, info->root, info);
	}

	info->root->free(info->root);
	info->file->close(info->file);
	free(info);
	free(file);
}
示例#23
0
void CWiiSaveCrypted::WriteHDR()
{
	if (!b_valid) return;
	memset(&_header, 0, HEADER_SZ);

	u32 bannerSize = File::GetSize(BannerFilePath);
	_header.hdr.BannerSize =  Common::swap32(bannerSize);

	_header.hdr.SaveGameTitle = Common::swap64(m_TitleID);
	memcpy(_header.hdr.Md5, MD5_BLANKER, 0x10);
	_header.hdr.Permissions = 0x35;

	File::IOFile fpBanner_bin(BannerFilePath, "rb");
	if (!fpBanner_bin.ReadBytes(_header.BNR, bannerSize))
	{
		PanicAlertT("Failed to read banner.bin");
		b_valid = false;
		return;
	}
	
	md5((u8*)&_header, HEADER_SZ, md5_calc);
	memcpy(_header.hdr.Md5, md5_calc, 0x10);

	AES_cbc_encrypt((const unsigned char *)&_header, (u8*)&_encryptedHeader, HEADER_SZ, &m_AES_KEY, SD_IV, AES_ENCRYPT);
	
	File::IOFile fpData_bin(pathData_bin, "wb");
	if (!fpData_bin.WriteBytes(&_encryptedHeader, HEADER_SZ))
	{
		PanicAlertT("Failed to write header for %s", pathData_bin);
		b_valid = false;
	}
}
示例#24
0
static int qcrypto_cipher_decrypt_aes(QCryptoCipher *cipher,
                                      const void *in,
                                      void *out,
                                      size_t len,
                                      Error **errp)
{
    QCryptoCipherBuiltin *ctxt = cipher->opaque;

    switch (cipher->mode) {
    case QCRYPTO_CIPHER_MODE_ECB:
        qcrypto_cipher_aes_ecb_decrypt(&ctxt->state.aes.key.dec,
                                       in, out, len);
        break;
    case QCRYPTO_CIPHER_MODE_CBC:
        AES_cbc_encrypt(in, out, len,
                        &ctxt->state.aes.key.dec,
                        ctxt->state.aes.iv, 0);
        break;
    case QCRYPTO_CIPHER_MODE_XTS:
        xts_decrypt(&ctxt->state.aes.key,
                    &ctxt->state.aes.key_tweak,
                    qcrypto_cipher_aes_xts_encrypt,
                    qcrypto_cipher_aes_xts_decrypt,
                    ctxt->state.aes.iv,
                    len, out, in);
        break;
    default:
        g_assert_not_reached();
    }

    return 0;
}
示例#25
0
void setKeyImg3(AbstractFile2* file, const unsigned int* key, const unsigned int* iv) {
	Img3Info* info = (Img3Info*) file->super.data;
	if (!info->kbag) {
		return;
	}

	int i;
	uint8_t bKey[32];
	int keyBits = ((AppleImg3KBAGHeader*)info->kbag->data)->key_bits;

	for(i = 0; i < 16; i++) {
		info->iv[i] = iv[i] & 0xff;
	}

	for(i = 0; i < (keyBits / 8); i++) {
		bKey[i] = key[i] & 0xff;
	}

	AES_set_encrypt_key(bKey, keyBits, &(info->encryptKey));
	AES_set_decrypt_key(bKey, keyBits, &(info->decryptKey));

	info->decryptLast = Img3DecryptLast;
	if(!info->encrypted) {
		uint32_t sz = info->data->header->dataSize;
		if (info->decryptLast) {
			sz = info->data->header->size;
		}
		uint8_t ivec[16];
		memcpy(ivec, info->iv, 16);
		AES_cbc_encrypt(info->data->data, info->data->data, (sz / 16) * 16, &(info->decryptKey), ivec, AES_DECRYPT);
	}

	info->encrypted = TRUE;
}
示例#26
0
/**
 * Encrypt a password that can be stored in the MaxScale configuration file.
 *
 * Note the return is always a malloc'd string that the caller must free
 *
 * @param password	The password to encrypt
 * @return	The encrypted password
 */
char *
encryptPassword(char *password)
{
MAXKEYS		*keys;
AES_KEY		aeskey;
int		padded_len;
char		*hex_output;
unsigned char	padded_passwd[80];
unsigned char	encrypted[80];

	if ((keys = secrets_readKeys()) == NULL)
		return NULL;

	memset(padded_passwd, 0, 80);
	strcpy((char *)padded_passwd, password);
	padded_len = ((strlen(password) / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE;

	AES_set_encrypt_key(keys->enckey, 8 * MAXSCALE_KEYLEN, &aeskey);

	AES_cbc_encrypt(padded_passwd, encrypted, padded_len, &aeskey, keys->initvector, AES_ENCRYPT);
	hex_output = (char *)malloc(padded_len * 2);
	gw_bin2hex(hex_output, encrypted, padded_len);
	free(keys);

	return	hex_output;
}
示例#27
0
//aes解密
unsigned char *utDecryptAes(unsigned char *in,unsigned char *pKey)
{
	 static unsigned char out[2560];
	 unsigned char caKey[2560];
   unsigned char ivec[2560],data[2048];
   long iReturn;
 //  printf("lCount=%d\n",lCount);
	memset(out,0,sizeof(out));

	 AES_KEY *key;
   key=(AES_KEY *)malloc(sizeof(AES_KEY));
	 iReturn=AES_set_decrypt_key(pKey,256,key);
   if(iReturn!=0){
   	free(key);
   	return &out[0];
   }
    memset(ivec,0,sizeof(ivec));
    memset(data,0,sizeof(data));
   iReturn=pasStrCvtHex2Bin(in,data); 
      
 //   printf("iReturnlen=%d\n",iReturn);
    if(iReturn<16){
    	free(key);
    	return &out[0];
    }
    memcpy(ivec,data,16);
   
    AES_cbc_encrypt(data+16, out,iReturn-16, key,ivec,AES_DECRYPT);
   
    free(key);
//    utStrReplaceWith(out,"\x05","\0");
    return &out[0];
}   
示例#28
0
char * decrypt(char * buffer, char* iv_encPass, char * aes_keyPass)
{
    char * iv_dec = iv_encPass;
    
    char *aes_key = aes_keyPass;
    int keylength = 128;
    
    
    size_t inputslength = 0;
    
  const size_t encslength = 1000;
    
    inputslength = strlen(buffer);

//	const size_t encslength = inputslength;
    
    char * enc_out = buffer;
    
    unsigned char *dec_out = (unsigned char*)malloc(sizeof(unsigned char) *inputslength);
     memset(dec_out, 0, sizeof(dec_out));
    AES_KEY dec_key;
    AES_set_decrypt_key(aes_key, keylength, &dec_key);
    AES_cbc_encrypt(enc_out, dec_out, encslength, &dec_key, iv_dec, AES_DECRYPT);
    
    return dec_out;
    
}
void decrypt(char *data,int round_len)
{
	char *out=malloc(sizeof(char)*round_len);

	int key_len=16;

	memset(out, 0, round_len);
	//memset(buf, 0, round_len);
	//memcpy (buf, in, len );

	unsigned char IV[key_len];
	unsigned char key[key_len];

	MD5((const unsigned char*)key_text, strlen(key_text),(unsigned char *)key);
	MD5((const unsigned char*)iv_text, strlen(iv_text),(unsigned char *)IV);

	AES_KEY aeskey;

	AES_set_decrypt_key(key, key_len*8, &aeskey);
	AES_cbc_encrypt(data,out, round_len, &aeskey, IV, AES_DECRYPT);

	memcpy (data, out, round_len );
	//printf("decrypted: '%s'\n",data);
	free(out);


}
示例#30
-1
static int aes_decrypt(const char* src, int src_len, char** des)
{
	char* tmp = NULL;
	unsigned char key[AES_KEY_SIZE];
	unsigned char iv[AES_IV_SIZE];
	memcpy(iv, AES_IV_NAME, AES_IV_SIZE);
	memcpy(key, AES_KEY_NAME, AES_KEY_SIZE);
	do
	{
		tmp = (char*)malloc(src_len + AES_BLOCK_SIZE + sizeof(LOG_HEADER));
		if (!tmp)
			break;

		LPLOG_HEADER header = (LPLOG_HEADER)tmp;

		header->src_len = src_len;
		header->des_len = ((src_len / AES_BLOCK_SIZE) == 0) ? src_len : src_len + (AES_BLOCK_SIZE - (src_len % AES_BLOCK_SIZE));
		header->len = header->des_len + sizeof(LOG_HEADER);

		AES_KEY aes;
		if( AES_set_encrypt_key((unsigned char*)key, AES_KEY_SIZE * 8, &aes) < 0 )
			break;
		*des = tmp;

		AES_cbc_encrypt((const unsigned char*)src, (unsigned char*)(header->body), src_len, &aes, iv, AES_ENCRYPT);
		return header->len;
	}while(0);
	if (tmp)
		free(tmp);
	return -1;
}