+ case EVP_CTRL_TLSTREE:
+ {
+ unsigned char newkey[32];
+ int mode = EVP_CIPHER_CTX_mode(ctx);
+ struct ossl_gost_cipher_ctx *ctr_ctx = NULL;
+ gost_ctx *c = NULL;
+
+ unsigned char adjusted_iv[8];
+ unsigned char seq[8];
+ int j, carry, decrement_arg;
+ if (mode != EVP_CIPH_CTR_MODE)
+ return -1;
+
+ ctr_ctx = (struct ossl_gost_cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx);
+ c = &(ctr_ctx->cctx);
+
+ /*
+ * 'arg' parameter indicates what we should do with sequence value.
+ *
+ * When function called, seq is incremented after MAC calculation.
+ * In ETM mode, we use seq 'as is' in the ctrl-function (arg = 0)
+ * Otherwise we have to decrease it in the implementation (arg = 1).
+ */
+ memcpy(seq, ptr, 8);
+ decrement_arg = arg;
+ if(!decrement_sequence(seq, decrement_arg)) {
+ GOSTerr(GOST_F_MAGMA_CIPHER_CTL, GOST_R_CTRL_CALL_FAILED);
+ return -1;
+ }
+
+ if (gost_tlstree(NID_magma_cbc, (const unsigned char *)c->master_key, newkey,
+ (const unsigned char *)seq) > 0) {
+ memset(adjusted_iv, 0, 8);
+ memcpy(adjusted_iv, EVP_CIPHER_CTX_original_iv(ctx), 4);
+ for (j = 3, carry = 0; j >= 0; j--)
+ {
+ int adj_byte = adjusted_iv[j] + seq[j+4] + carry;
+ carry = (adj_byte > 255) ? 1 : 0;
+ adjusted_iv[j] = adj_byte & 0xFF;
+ }
+ EVP_CIPHER_CTX_set_num(ctx, 0);
+ memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), adjusted_iv, 8);
+
+ magma_key(c, newkey);
+ return 1;
+ }
+ }
+ return -1;