/** * @ingroup TestOpenssl * @brief AES256 암호화 테스트 */ void AES256( ) { const char * pszKey = "12345678901234567890123456789012"; const char * pszIv = "1234567890123456"; const char * pszInput = "ABCD"; char szOutput[255]; int iOutputLen, iLen; OpenSSL_add_all_ciphers(); const EVP_CIPHER * psttCipher = EVP_get_cipherbyname( "aes256" ); EVP_CIPHER_CTX sttCtx; memset( szOutput, 0, sizeof(szOutput) ); EVP_CIPHER_CTX_init( &sttCtx ); EVP_EncryptInit( &sttCtx, psttCipher, (const unsigned char *)pszKey, (const unsigned char *)pszIv ); EVP_EncryptUpdate( &sttCtx, (uint8_t *)szOutput, &iOutputLen, (uint8_t *)pszInput, strlen(pszInput) ); EVP_EncryptFinal( &sttCtx, (uint8_t *)szOutput + iOutputLen, &iLen ); EVP_CIPHER_CTX_cleanup( &sttCtx ); iOutputLen += iLen; for( int i = 0; i < iOutputLen; ++i ) { printf( "%02X", (uint8_t)szOutput[i] ); } printf( "\n" ); EVP_cleanup(); }
DBT *encrypt(unsigned char *unenc, unsigned long size) { unsigned char *safepasswd; EVP_CIPHER_CTX ctx; DBT *encoded; int olen, tlen; FUNC; safepasswd = safepassword(); EVP_CIPHER_CTX_init(&ctx); EVP_EncryptInit(&ctx, EVP_bf_cbc(), safepasswd, config->iv); encoded = s_malloc(sizeof(DBT)); encoded->data = s_malloc(8 + size); //Blowfish can grow 64 bits if (EVP_EncryptUpdate(&ctx, encoded->data, &olen, unenc, size) != 1) { die_cryptoerr("error in encrypt update\n"); } if (EVP_EncryptFinal(&ctx, encoded->data + olen, &tlen) != 1) { die_cryptoerr("error in encrypt final\n"); } EVP_CIPHER_CTX_cleanup(&ctx); encoded->size = olen + tlen; if (encoded->size > 8 + size) { die_cryptoerr ("Unexpected fatal error : data has grown in size after encryption.\n"); } free(safepasswd); EFUNC; return encoded; }
ndn_Error ndn_AesAlgorithm_encrypt128Cbc (const uint8_t *key, size_t keyLength, const uint8_t *initialVector, size_t initialVectorLength, const uint8_t *plainData, size_t plainDataLength, uint8_t *encryptedData, size_t *encryptedDataLength) { EVP_CIPHER_CTX *ctx; int outLength1, outLength2; if (keyLength != ndn_AES_128_BLOCK_SIZE) return NDN_ERROR_Incorrect_key_size; if (initialVectorLength != ndn_AES_128_BLOCK_SIZE) return NDN_ERROR_Incorrect_initial_vector_size; ctx = EVP_CIPHER_CTX_new(); if (!ctx) return NDN_ERROR_Error_in_encrypt_operation; EVP_EncryptInit (ctx, EVP_aes_128_cbc(), (const unsigned char*)key, (const unsigned char*)initialVector); EVP_EncryptUpdate (ctx, (unsigned char*)encryptedData, &outLength1, (const unsigned char*)plainData, plainDataLength); EVP_EncryptFinal (ctx, (unsigned char*)encryptedData + outLength1, &outLength2); EVP_CIPHER_CTX_free(ctx); *encryptedDataLength = outLength1 + outLength2; return NDN_ERROR_success; }
static int lencrypt (lua_State *L) { size_t len = 0; const char *text = lua_tolstring (L, 1, &len); const char *key = lua_tostring (L, 2); EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); unsigned char iv[16] = { 0 }; char *output = malloc (len + AES_BLOCK_SIZE); int olen1; int olen2; EVP_EncryptInit (ctx, EVP_aes_128_cbc(), (unsigned char *)key, iv); EVP_EncryptUpdate (ctx, (unsigned char *)output, &olen1, (const unsigned char *)text, len); int ok = EVP_EncryptFinal (ctx, (unsigned char *)output + olen1, &olen2); if (!ok) { free (output); EVP_CIPHER_CTX_free (ctx); return 0; } lua_pushlstring (L, output, olen1 + olen2); free (output); EVP_CIPHER_CTX_free (ctx); return 1; }
int data_encrypt(unsigned char *src, unsigned char *dst, int len, struct peer *p) { int tlen, olen; if (encryption_disabled){ memcpy(dst,src,len); return len; } if (!ctx_initialized) { EVP_CIPHER_CTX_init (&ctx); ctx_initialized = 1; } EVP_EncryptInit (&ctx, EVP_bf_cbc (), p->key, p->iv); if (EVP_EncryptUpdate (&ctx, dst, &olen, src, len) != 1) { fprintf (stderr,"error in encrypt update\n"); olen = -1; goto cleanup; } if (EVP_EncryptFinal (&ctx, dst + olen, &tlen) != 1) { fprintf (stderr,"error in encrypt final\n"); olen = -1; goto cleanup; } olen += tlen; cleanup: EVP_CIPHER_CTX_cleanup(&ctx); return olen; }
int Crypto::encrypt(unsigned char* input, int insize, unsigned char* output, int& outsize) { if (1 != m_iCoderType) return -1; unsigned char* ip = input; unsigned char* op = output; for (int ts = insize; ts > 0; ) { int unitsize = (ts < g_iEncBlockSize) ? ts : g_iEncBlockSize; int len; if (EVP_EncryptUpdate(&m_CTX, op, &len, ip, unitsize) != 1) { printf ("error in encrypt update\n"); return 0; } ip += unitsize; op += len; if (EVP_EncryptFinal(&m_CTX, op, &len) != 1) { printf ("error in encrypt final\n"); return 0; } op += len; ts -= unitsize; } outsize = op - output; return 1; }
// encrypt buffer static int cryptoEnc(struct s_crypto *ctx, unsigned char *enc_buf, const int enc_len, const unsigned char *dec_buf, const int dec_len, const int hmac_len, const int iv_len) { unsigned char iv[crypto_MAXIVSIZE]; unsigned char hmac[hmac_len]; const int hdr_len = (hmac_len + iv_len); int cr_len; int len; if(enc_len < (hdr_len + crypto_MAXIVSIZE + dec_len)) { return 0; } if(iv_len > crypto_MAXIVSIZE) { return 0; } memset(iv, 0, crypto_MAXIVSIZE); cryptoRand(iv, iv_len); memcpy(&enc_buf[hmac_len], iv, iv_len); if(!EVP_EncryptInit_ex(&ctx->enc_ctx, NULL, NULL, NULL, iv)) { return 0; } if(!EVP_EncryptUpdate(&ctx->enc_ctx, &enc_buf[(hdr_len)], &len, dec_buf, dec_len)) { return 0; } cr_len = len; if(!EVP_EncryptFinal(&ctx->enc_ctx, &enc_buf[(hdr_len + cr_len)], &len)) { return 0; } cr_len += len; if(!cryptoHMAC(ctx, hmac, hmac_len, &enc_buf[hmac_len], (iv_len + cr_len))) { return 0; } memcpy(enc_buf, hmac, hmac_len); return (hdr_len + cr_len); }
char * CGI_encrypt(const void *p, int len, const char *password) { EVP_CIPHER_CTX ctx; unsigned char md[DIGEST_SIZE]; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char key[EVP_MAX_KEY_LENGTH]; unsigned char *out; char *b64; int offset, rlen; if (p == 0 || len <= 0 || password == 0 || *password == 0) { return 0; } out = malloc(SALT_SIZE + DIGEST_SIZE + len + EVP_MAX_BLOCK_LENGTH); init_salt(out); digest(p, len, password, out, md); EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), out, (unsigned char *) password, strlen(password), 1, key, iv); EVP_EncryptInit(&ctx, EVP_aes_256_cbc(), key, iv); offset = SALT_SIZE; EVP_EncryptUpdate(&ctx, out + offset, &rlen, md, DIGEST_SIZE); offset += rlen; EVP_EncryptUpdate(&ctx, out + offset, &rlen, p, len); offset += rlen; EVP_EncryptFinal(&ctx, out + offset, &rlen); b64 = CGI_encode_base64(out, offset + rlen); free(out); return b64; }
enum snmp_code snmp_pdu_encrypt(const struct snmp_pdu *pdu) { int32_t err, olen; uint8_t iv[SNMP_PRIV_AES_IV_SIZ]; const EVP_CIPHER *ctype; EVP_CIPHER_CTX ctx; err = snmp_pdu_cipher_init(pdu, pdu->scoped_len, &ctype, iv); if (err < 0) return (SNMP_CODE_EDECRYPT); else if (err == 0) return (SNMP_CODE_OK); if (EVP_EncryptInit(&ctx, ctype, pdu->user.priv_key, iv) != 1) return (SNMP_CODE_FAILED); if (EVP_EncryptUpdate(&ctx, pdu->scoped_ptr, &olen, pdu->scoped_ptr, pdu->scoped_len) != 1 || EVP_EncryptFinal(&ctx, pdu->scoped_ptr + olen, &olen) != 1) { EVP_CIPHER_CTX_cleanup(&ctx); return (SNMP_CODE_FAILED); } EVP_CIPHER_CTX_cleanup(&ctx); return (SNMP_CODE_OK); }
const char* encrypt(unsigned char* inbuff, int inbuff_len, unsigned char* key, unsigned char* iv) { EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); EVP_EncryptInit(&ctx, EVP_bf_cbc(), key, iv); unsigned char* outbuf = (unsigned char *)malloc(sizeof(unsigned char) * BUF_SIZE); memset(outbuf, 0, BUF_SIZE); int olen=0, tlen=0; if (EVP_EncryptUpdate(&ctx, outbuf, &olen, inbuff, inbuff_len) != 1) { LOGE("Error in encrypt update"); return 0; } if (EVP_EncryptFinal(&ctx, outbuf + olen, &tlen) != 1) { std::ostringstream err; err << "Error in encrypt final: " << strerror(errno); LOGE(err.str().c_str()); return 0; } EVP_CIPHER_CTX_cleanup(&ctx); return (const char*) outbuf; }
bool AesCbcCipher::encrypt(const Vuc& in, Vuc& out) { // according to the openssl docs: // the amount of data written may be as large as (in.size() + cipher_block_size - 1) size_t outSize = in.size() + AES_BLOCK_SIZE - 1; // the output buffer must also be a multiple of blocksize if ((outSize % AES_BLOCK_SIZE) != 0) outSize = ((outSize / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE; out.resize(outSize, 0); // init encryption ScopedOpenSSL<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free> ctx(EVP_CIPHER_CTX_new()); EVP_EncryptInit(ctx.get(), getCipher(), &key_[0], &iv_[0]); // do the encrypt; must keep track of the number of bytes produced int nBytes = 0; EVP_EncryptUpdate(ctx.get(), &out[0], &nBytes, &in[0], in.size()); int nTotalBytes = nBytes; EVP_EncryptFinal(ctx.get(), &out[nBytes], &nBytes); nTotalBytes += nBytes; // the actual output size is in nTotalBytes assert(nTotalBytes); Vuc(out.begin(), out.begin()+nTotalBytes).swap(out); // shrink to fit return true; }
std::string encrypt_aes256(const std::string& plain,const std::string& key,const std::string& iv) { std::string cipher; cipher.resize((plain.size()/AES_BLOCK_SIZE+1)*AES_BLOCK_SIZE); EVP_CIPHER_CTX* ctx=nullptr; try { ctx=EVP_CIPHER_CTX_new(); if(key.size()!=AES256_KEY_SIZE) throw std::runtime_error("encrypt_aes256() - Given key size is invalid ("+ std::to_string(AES256_KEY_SIZE)+"bytes )."); int temp_length; int temp_unaligned_length; if(ctx==nullptr) throw std::runtime_error("encrypt_aes256() - Creating a EVP_CIPHER_CTX failed."); if(EVP_CIPHER_CTX_set_padding(ctx,1)==0) throw std::runtime_error("encrypt_aes256() - EVP_CIPHER_CTX_set_padding failed."); if(EVP_EncryptInit(ctx,EVP_aes_256_cbc(),(uint8_t*)key.data(),(uint8_t*)iv.data())==0) throw std::runtime_error("encrypt_aes256() - EVP_EncryptInit failed."); if(EVP_EncryptUpdate(ctx,(uint8_t*)cipher.data(),&temp_length,(uint8_t*)plain.data(),plain.size())==0) throw std::runtime_error("encrypt_aes256() - EVP_EncryptUpdate failed."); if(EVP_EncryptFinal(ctx,(uint8_t*)cipher.data()+temp_length,&temp_unaligned_length)==0) throw std::runtime_error("encrypt_aes256() - EVP_EncryptFinal failed."); cipher.resize(temp_length+temp_unaligned_length); } catch(...) { aes_cleanup(ctx); throw; } aes_cleanup(ctx); return cipher; }
/** * @brief Performs basic Encrypt-then-MAC style Authenticated Encryption. * * @param[in] ekey a buffer holding the ENC key * @param[in] ekey_len len of ekey buffer * @param[in] mkey a buffer holding the MAC key * @param[in] mkey_len len of mkey buffer * @param[in] input the plaintext message * @param[in] input_len len of message buffer * @param[in,out] ctxt an allocated buffer, will hold the ciphertext * @param[in,out] ctxt_len length of buffer, will hold length of ciphertext * @param[in,out] mac an allocated buffer, will hold the MAC * @param[in,out] mac_len length of buffer, will hold length of MAC * @param[in,out] iv a randomly chosen iv (optional) * @param[in] iv_len length of buffer for iv (optional) * @return 0 on success, non-zero on error **/ int encrypt_then_mac(const unsigned char *ekey, size_t ekey_len, const unsigned char *mkey, size_t mkey_len, const unsigned char *input, size_t input_len, unsigned char *ctxt, size_t *ctxt_len, unsigned char *mac, size_t *mac_len, unsigned char *iv, size_t iv_len) { EVP_CIPHER_CTX *ctx; ctx = EVP_CIPHER_CTX_new(); EVP_CIPHER *cipher = NULL; int len; if (!ekey || !ekey_len || !mkey || !mkey_len || !input_len || !ctxt || !ctxt_len || !mac || !mac_len) return -1; OpenSSL_add_all_algorithms(); EVP_CIPHER_CTX_init(ctx); switch(ekey_len){ case 16: cipher = (EVP_CIPHER *)EVP_aes_128_cbc(); break; case 24: cipher = (EVP_CIPHER *)EVP_aes_192_cbc(); break; case 32: cipher = (EVP_CIPHER *)EVP_aes_256_cbc(); break; default: return -1; } if (iv && iv_len) { if (!RAND_bytes(iv, iv_len)) goto cleanup; } if (!EVP_EncryptInit(ctx, cipher, ekey, iv)) goto cleanup; *ctxt_len = 0; if (!EVP_EncryptUpdate(ctx, ctxt, (int *) ctxt_len, input, input_len)) goto cleanup; EVP_EncryptFinal(ctx, ctxt + *ctxt_len, &len); *ctxt_len += len; // Do the HMAC-SHA1 *mac_len = 0; if (!HMAC(EVP_sha1(), mkey, mkey_len, ctxt, *ctxt_len, mac, (unsigned int *) mac_len)) goto cleanup; EVP_CIPHER_CTX_cleanup(ctx); return 0; cleanup: if (ctxt_len) *ctxt_len = 0; if (mac_len) *mac_len = 0; return 1; }
int main(int argc, char** argv) { // get data to encrypt. // if (argc != 3) { printf("Usage: %s <base64 enc key> <data to encryt>\n", argv[0]); return 0; } // base64 decode key // BIO *mbio = BIO_new_mem_buf(argv[1], strlen(argv[1])); BIO *b64bio = BIO_new(BIO_f_base64()); BIO_set_flags(b64bio, BIO_FLAGS_BASE64_NO_NL); BIO *bio = BIO_push(b64bio, mbio); char key[256]; size_t keylen = 0; keylen = BIO_read(bio, key, sizeof(key)); BIO_free(mbio); BIO_free(b64bio); // encrypt the data // char out[256]; int outlen = 0; EVP_CIPHER_CTX ctx; EVP_EncryptInit(&ctx, EVP_aes_256_ecb(), key, NULL); EVP_EncryptUpdate(&ctx, out, &outlen, argv[2], strlen(argv[2])); EVP_EncryptFinal(&ctx, out, &outlen); EVP_CIPHER_CTX_cleanup(&ctx); // base64 encode encrypted data // mbio = BIO_new(BIO_s_mem()); b64bio = BIO_new(BIO_f_base64()); BIO_set_flags(b64bio, BIO_FLAGS_BASE64_NO_NL); bio = BIO_push(b64bio, mbio); BIO_write(bio, out, outlen); BIO_flush(bio); char* data = NULL; size_t datalen = 0; datalen = BIO_get_mem_data(mbio, &data); data[datalen] = '\0'; printf("encrypted data: [%s]\n", data); BIO_free(mbio); BIO_free(b64bio); return 0; }
soter_status_t soter_sym_aead_ctx_final(soter_sym_ctx_t *ctx,bool encrypt){ uint8_t out_data[16]; size_t out_data_length=0; if(encrypt){ SOTER_CHECK(EVP_EncryptFinal(&(ctx->evp_sym_ctx), out_data, (int*)&out_data_length)!=0 && out_data_length==0); } else { SOTER_CHECK(EVP_DecryptFinal(&(ctx->evp_sym_ctx), out_data, (int*)&out_data_length)!=0 && out_data_length==0); } return SOTER_SUCCESS; }
static void sl_encrypt (void){ /* input types */ char *ctype; unsigned char *outbuf, *iiv, *ikey, *idata; SLang_BString_Type *iv, *key, *data; /* internal types */ EVP_CIPHER_CTX ctx; const EVP_CIPHER *cipher; int outlen, tmplen, dlen, i; /* output types */ SLang_BString_Type *output; if (SLang_Num_Function_Args != 4 || SLang_pop_slstring(&ctype) == -1 ){ return; } cipher = EVP_get_cipherbyname(ctype); if (!cipher){ SLang_verror(SL_UNDEFINED_NAME,"could not find cipher %s",ctype); return; } if (SLang_pop_bstring(&iv) == -1 || SLang_pop_bstring(&key) == -1 || SLang_pop_bstring(&data) == -1 ){ return; } iiv = SLbstring_get_pointer (iv,&i); ikey = SLbstring_get_pointer (key,&i); idata = SLbstring_get_pointer (data,&dlen); outbuf = (char*)malloc(dlen+EVP_CIPHER_block_size(cipher)); EVP_CIPHER_CTX_init(&ctx); EVP_EncryptInit_ex(&ctx, cipher, NULL, ikey, iiv); if (!EVP_EncryptUpdate(&ctx, outbuf, &outlen, idata, dlen)){ return; /*emit an error here*/ } if (!EVP_EncryptFinal(&ctx, outbuf + outlen, &tmplen)){ return; /*emit an error here*/ } outlen+=tmplen; output = SLbstring_create (outbuf, outlen); SLang_push_bstring(output); SLbstring_free(output); SLbstring_free(data); SLbstring_free(key); SLbstring_free(iv); free(outbuf); }
/* tlamijan */ int main(void) { unsigned char ot[1024]; // open text unsigned char st[1024]; // sifrovany text unsigned char key[EVP_MAX_KEY_LENGTH] = "Super tajny klic"; // klic pro sifrovani unsigned char iv[EVP_MAX_IV_LENGTH] = "vector unknown"; // inicializacni vektor const char * filename = "Mad_scientist.bmp"; const char * outfilename = "Mad_scientist_aes_cbc.bmp"; int otLength = 0; int stLength = 0; int tmpLength = 0; int readlen = 0; char header[14]; unsigned int offset = 0; EVP_CIPHER_CTX ctx; // struktura pro kontext FILE * fin = fopen(filename,"rb"); FILE * fout = fopen(outfilename,"w+b"); if(!fin){ printf("File not found"); } fread(header,1,14,fin); fwrite(header,1,14,fout); offset = (unsigned int)*(&header[10]); offset -= 14; while(offset > 1024){ fread(ot,1,1024,fin); fwrite(ot,1,1024,fout); offset -= 1024; } fread(ot,1,offset,fin); fwrite(ot,1,offset,fout); EVP_EncryptInit(&ctx, EVP_aes_256_cbc(), key, iv); // nastaveni kontextu pro sifrovani do{ readlen = fread(ot,1,1024,fin); EVP_EncryptUpdate(&ctx, st, &stLength, ot, readlen); // sifrovani ot fwrite(st,1,stLength,fout); }while(readlen == 1024); EVP_EncryptFinal(&ctx, &st[stLength], &tmpLength); // ziskani sifrovaneho textu z kontextu fwrite(&st[stLength],1,tmpLength,fout); stLength += tmpLength; fclose(fin); fclose(fout); exit(0); }
int encrypt_and_authentucate_secrets(CPOR_key *key, unsigned char *input, size_t input_len, unsigned char *ciphertext, size_t *ciphertext_len, unsigned char *authenticator, size_t *authenticator_len) { EVP_CIPHER_CTX ctx; EVP_CIPHER *cipher = NULL; int len; if(!key || !key->k_enc || !key->k_mac || !input || !input_len || !ciphertext || !ciphertext_len || !authenticator || !authenticator_len) return 0; OpenSSL_add_all_algorithms(); EVP_CIPHER_CTX_init(&ctx); switch(key->k_enc_size) { case 16: cipher = (EVP_CIPHER *)EVP_aes_128_cbc(); break; case 24: cipher = (EVP_CIPHER *)EVP_aes_192_cbc(); break; case 32: cipher = (EVP_CIPHER *)EVP_aes_256_cbc(); break; default: return 0; } //TODO: Fix the NULL IV if(!EVP_EncryptInit(&ctx, cipher, key->k_enc, NULL)) goto cleanup; *ciphertext_len = 0; if(!EVP_EncryptUpdate(&ctx, ciphertext, (int *)ciphertext_len, input, input_len)) goto cleanup; EVP_EncryptFinal(&ctx, ciphertext + *ciphertext_len, &len); *ciphertext_len += len; *authenticator_len = 0; /* Do the HMAC-SHA1 */ if(!HMAC(EVP_sha1(), key->k_mac, key->k_mac_size, ciphertext, *ciphertext_len, authenticator, (unsigned int *)authenticator_len)) goto cleanup; EVP_CIPHER_CTX_cleanup(&ctx); return 1; cleanup: *ciphertext_len = 0; *authenticator_len = 0; return 0; }
QByteArray JulyAES256::encrypt(const QByteArray &data, const QByteArray &password) { int outLen=0; QByteArray dataBuff;dataBuff.resize(data.size()+AES_BLOCK_SIZE); EVP_CIPHER_CTX evpCipherCtx; EVP_CIPHER_CTX_init(&evpCipherCtx); EVP_EncryptInit(&evpCipherCtx,EVP_aes_256_cbc(),(const unsigned char*)sha256(password).data(),(const unsigned char*)sha256("JulyAES"+password).data()); EVP_EncryptUpdate(&evpCipherCtx,(unsigned char*)dataBuff.data(),&outLen,(const unsigned char*)data.data(),data.size()); int tempLen=outLen; EVP_EncryptFinal(&evpCipherCtx,(unsigned char*)dataBuff.data()+tempLen,&outLen); tempLen+=outLen; EVP_CIPHER_CTX_cleanup(&evpCipherCtx); dataBuff.resize(tempLen); return dataBuff; }
unsigned char* sym_crypt(void* buf, int buf_size, unsigned char* key, int* cipher_len){ EVP_CIPHER_CTX* ctx; FILE* fd; unsigned char* ciphertext; int res, msg_len, n; int outlen, outlen_tot; int ct_bufsize; int block_size = EVP_CIPHER_block_size(SYM_CIPHER); //printf("block_size: %i\n", block_size); if(buf == NULL || key == NULL) return NULL; ctx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX)); EVP_CIPHER_CTX_init(ctx); EVP_EncryptInit(ctx, SYM_CIPHER, key, NULL); //Cosa fare con l' IV? /* Buffer allocation for the ciphertext */ msg_len = buf_size; ct_bufsize = msg_len + block_size; ciphertext = (unsigned char*)malloc(ct_bufsize); outlen = 0; outlen_tot = 0;//dimensione testo output(ciphertext) n=0;//dimensione testo input (plaintext) while(n/block_size < msg_len/block_size){//block size serve nel caso in cui msg_len < block_size allora non devo entrare nel ciclo EVP_EncryptUpdate(ctx, ciphertext + outlen_tot, &outlen, (unsigned char*)buf + n,block_size); outlen_tot += outlen; n += block_size; } EVP_EncryptUpdate(ctx, ciphertext + outlen_tot, &outlen, (unsigned char*)buf + n,msg_len % block_size);// cifro i byte restanti(quelli non multipli di block size outlen_tot += outlen; n += msg_len % block_size; EVP_EncryptFinal(ctx, ciphertext + outlen_tot, &outlen); outlen_tot += outlen; EVP_CIPHER_CTX_cleanup(ctx); free(ctx); *cipher_len = outlen_tot; return ciphertext; }
/* * This function encrypts a string before calling send_msg. * It also append the given IV for the ecnryption mode. * It returns the length of the cipher text (iv is not considered), -1 on error. * Errno is set appropriately */ int encrypt_msg(int sk, char format, unsigned char* plain, unsigned int plain_len, unsigned char* shared_secret) { EVP_CIPHER_CTX* ctx; unsigned char* iv; unsigned int iv_len = EVP_MAX_IV_LENGTH; unsigned char* outbuf = NULL; int outlen, outtot = 0; ctx = (EVP_CIPHER_CTX*)calloc(1, sizeof(EVP_CIPHER_CTX)); EVP_CIPHER_CTX_init(ctx); iv = (unsigned char*)calloc(1, iv_len); RAND_bytes(iv, iv_len); if (EVP_EncryptInit(ctx, EVP_aes_256_cbc(), shared_secret, iv) == 0) { goto fail; } outbuf = (unsigned char*)calloc(1, plain_len + EVP_CIPHER_block_size(EVP_aes_256_cbc()) + iv_len); if (EVP_EncryptUpdate(ctx, outbuf + iv_len, &outlen, plain, plain_len) == 0) { goto fail; } outtot += outlen; if (EVP_EncryptFinal(ctx, outbuf + iv_len + outtot, &outlen) == 0) { goto fail; } outtot += outlen; //We concatenate iv and cipher text together memcpy(outbuf, iv, iv_len); if (send_msg(sk, outbuf, outtot + iv_len, format) < outtot + iv_len) { goto fail; } EVP_CIPHER_CTX_cleanup(ctx); free(ctx); free(iv); free(outbuf); return outtot; fail: EVP_CIPHER_CTX_cleanup(ctx); free(ctx); free(iv); if (outbuf != NULL) { free(outbuf); } return -1; }
//******************************************************************************************** //**-------------------------------------FILE CRYPTION--------------------------------------** //******************************************************************************************** int crypt_file(const char *path, const char *fileName, unsigned char *key) { int outlen, inlen; FILE *file, *temp; file = fopen(fileName,"r+b"); if(file == NULL) { return -2; } char tempName[PATH_SIZE]; cnct(path,"TemP.TemP",tempName); temp = fopen(tempName,"wb"); unsigned char iv[8] = "DAJ-7l2"; /* вектор инициализации */ unsigned char inbuf[BUF_SIZE], outbuf[BUF_SIZE]; EVP_CIPHER_CTX ctx; const EVP_CIPHER * cipher; EVP_CIPHER_CTX_init(&ctx); cipher = EVP_bf_cbc(); EVP_EncryptInit(&ctx, cipher, key, iv); while(1) { inlen = fread(inbuf, 1, BUF_SIZE, file); if(inlen <= 0) break; if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, inbuf, inlen)) return 1; fwrite(outbuf, 1, outlen, temp); } if(!EVP_EncryptFinal(&ctx, outbuf, &outlen)) return 1; fwrite(outbuf, 1, outlen, temp); EVP_CIPHER_CTX_cleanup(&ctx); fclose(file); fclose(temp); remove(fileName); rename(tempName,fileName); return 0; }
soter_status_t soter_sym_ctx_final(soter_sym_ctx_t *ctx, void* out_data, size_t* out_data_length, bool encrypt){ if((ctx->alg&SOTER_SYM_PADDING_MASK)!=0){ if((*out_data_length)<EVP_CIPHER_CTX_block_size(&(ctx->evp_sym_ctx))){ (*out_data_length)=EVP_CIPHER_CTX_block_size(&(ctx->evp_sym_ctx)); return SOTER_BUFFER_TOO_SMALL; } } if(encrypt){ SOTER_CHECK(EVP_EncryptFinal(&(ctx->evp_sym_ctx), out_data, (int*)out_data_length)!=0); } else { SOTER_CHECK(EVP_DecryptFinal(&(ctx->evp_sym_ctx), out_data, (int*)out_data_length)!=0); } return SOTER_SUCCESS; }
bool Crypt(const wxString &sText, wxString &sCryptText) { GByte *pabyKey = GetKey(); GByte *pabyIV = GetIV(); EVP_CIPHER_CTX* ctx = CreateCTX(pabyKey, pabyIV, false); if(!ctx) { wxLogError(_("Crypt: Failed EVP_EncryptInit!")); CPLFree( pabyKey ); CPLFree( pabyIV ); return false; } CPLString pszText(sText.mb_str(wxConvUTF8)); int outlen; unsigned char outbuf[BUFSIZE]; bool bResult = EVP_EncryptUpdate(ctx, outbuf, &outlen, (const unsigned char*)pszText.data(), pszText.length() * sizeof(pszText[0]) + 1); if(!bResult) { wxLogError(_("Crypt: Failed EVP_EncryptUpdate!")); CPLFree( pabyKey ); CPLFree( pabyIV ); return bResult; } int nLen = outlen; bResult = EVP_EncryptFinal(ctx, &outbuf[outlen], &outlen); nLen += outlen; CPLString pszOutput(CPLBinaryToHex(nLen, outbuf)); sCryptText = wxString(pszOutput, wxConvUTF8); CPLFree( pabyKey ); CPLFree( pabyIV ); EVP_CIPHER_CTX_cleanup(ctx); //EVP_CIPHER_CTX_free(ctx); return bResult; }
array::array* aes_encrypt(const array::array* data, const array::array* iv, const array::array* key) { byte* ivec = new byte[iv->length]; memcpy(ivec, iv->data, iv->length); byte* outdata = new byte[data->length * 2]; int outLen1 = 0, outLen2 = 0; EVP_CIPHER_CTX ctx; EVP_EncryptInit(&ctx, EVP_aes_256_cbc(), key->data, ivec); EVP_EncryptUpdate(&ctx, outdata, &outLen1, data->data, data->length); EVP_EncryptFinal(&ctx,outdata + outLen1, &outLen2); delete[] ivec; array::array* lol = array::create(outLen1 + outLen2, outdata); delete[] outdata; return lol; }
string Sym_Encryption::generic_encrypt(unsigned char* k, unsigned char* msg, int msg_ll, string iv) { unsigned char* ciphertext; int ct_len; int nc; string str; EVP_EncryptInit(this->ctx, EVP_aes_128_cbc(), k, (unsigned char*)iv.data()); ct_len = msg_ll + EVP_CIPHER_CTX_block_size(this->ctx); ciphertext = (unsigned char *)malloc(ct_len); EVP_EncryptUpdate(this->ctx, ciphertext, &nc, msg, msg_ll); EVP_EncryptFinal(this->ctx, &ciphertext[nc], &nc); str.assign((const char *)ciphertext, ct_len); free (ciphertext); return str; }
QByteArray EncryptWrapper::encryptData(){ int outLen, inLen, finalLen; inLen = enData.count(); QByteArray outBuf(inLen+EVP_MAX_BLOCK_LENGTH,0); if(!EVP_EncryptUpdate(&encrypt, (unsigned char *)outBuf.data(), &outLen, (unsigned char *)enData.constData(), inLen)){ emit errors("EVP_EncryptUpdate failed"); return QByteArray(); } if(!EVP_EncryptFinal(&encrypt, ((unsigned char*)outBuf.data())+outLen,&finalLen)){ emit errors("EVP_EncryptFinal failed"); return QByteArray(); } outLen +=finalLen; EVP_CIPHER_CTX_cleanup(&encrypt); EVP_cleanup(); outBuf.resize(outLen); return outBuf; }
int encrypt (int infd, int outfd) { unsigned char outbuf[OP_SIZE]; int olen, tlen, n; unsigned char inbuff[IP_SIZE]; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); //EVP_CIPHER_CTX_init (ctx); EVP_EncryptInit (ctx, EVP_bf_cbc (), key, iv); for (;;) { bzero (&inbuff, IP_SIZE); if ((n = read (infd, inbuff, IP_SIZE)) == -1) { perror ("read error"); break; } else if (n == 0) break; if (EVP_EncryptUpdate (ctx, outbuf, &olen, inbuff, n) != 1) { printf ("error in encrypt update\n"); return 0; } if (EVP_EncryptFinal (ctx, outbuf + olen, &tlen) != 1) { printf ("error in encrypt final\n"); return 0; } olen += tlen; if ((n = write (outfd, outbuf, olen)) == -1) perror ("write error"); } //EVP_CIPHER_CTX_cleanup (ctx); return 1; }
int spider_encrypt(void) { unsigned char outbuf[LOG_MAX + EVP_MAX_BLOCK_LENGTH]; int olen,tlen,n; EVP_CIPHER_CTX ctx; struct logarray *p; struct logarray *tp; EVP_CIPHER_CTX_init (&ctx); EVP_EncryptInit(&ctx, EVP_bf_cbc(), KEY, IV); // walk through the log array, encrypting as we go. // when we finish, call EVP_EncryptFinal and write that to the log p = startlog; while (p && (strlen(p -> entry))) { n = strlen(p -> entry); if (EVP_EncryptUpdate(&ctx, outbuf, &olen, p -> entry, n) != 1) { return 0; } fwrite(outbuf, 1, olen, logfp); p = p -> next; } if (EVP_EncryptFinal(&ctx, outbuf+olen, &tlen) != 1) { return 0; } fwrite(outbuf+olen, 1, tlen, logfp); EVP_CIPHER_CTX_cleanup(&ctx); p = startlog; while (p) { tp = p -> next; p = realloc(p, 0); p = tp; } return 1; }
// a simple hex-print routine. could be modified to print 16 bytes-per-line void encrypt(FILE *ifp, FILE *ofp, unsigned char ckey[]) { //Get file size fseek(ifp, 0L, SEEK_END); int fsize = ftell(ifp); //set back to normal fseek(ifp, 0L, SEEK_SET); int outLen1 = 0; int outLen2 = 0; unsigned char *indata = (unsigned char *)malloc(fsize); unsigned char *outdata = (unsigned char *)malloc(fsize * 2); unsigned char ivec[] = "dontusethisinput"; //Read File fread(indata, sizeof(char), fsize, ifp);//Read Entire File //Set up encryption EVP_CIPHER_CTX ctx; EVP_EncryptInit(&ctx, EVP_aes_128_cbc(), ckey, ivec); EVP_EncryptUpdate(&ctx, outdata, &outLen1, indata, fsize); EVP_EncryptFinal(&ctx, outdata + outLen1, &outLen2); fwrite(outdata, sizeof(char), outLen1 + outLen2, ofp); }