+ EVP_CIPHER_CTX_set_num(ctx, i);
+ ctr128_inc(iv_buffer->b);
+ }
+
+ return 1;
+}
+
+#define GRASSHOPPER_BLOCK_MASK (GRASSHOPPER_BLOCK_SIZE - 1)
+static inline void apply_acpkm_grasshopper(gost_grasshopper_cipher_ctx_ctr *ctx, unsigned int *num)
+{
+ if (!ctx->section_size ||
+ (*num < ctx->section_size))
+ return;
+ acpkm_next(&ctx->c);
+ *num &= GRASSHOPPER_BLOCK_MASK;
+}
+
+/* If meshing is not configured via ctrl (setting section_size)
+ * this function works exactly like plain ctr */
+int gost_grasshopper_cipher_do_ctracpkm(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ const unsigned char *in, size_t inl) {
+ gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
+ unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
+ unsigned int num = EVP_CIPHER_CTX_num(ctx);
+
+ while ((num & GRASSHOPPER_BLOCK_MASK) && inl) {
+ *out++ = *in++ ^ c->partial_buffer.b[num & GRASSHOPPER_BLOCK_MASK];
+ --inl;
+ num++;
+ }
+ size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
+ size_t i;
+
+ // full parts
+ for (i = 0; i < blocks; i++) {
+ apply_acpkm_grasshopper(c, &num);
+ grasshopper_encrypt_block(&c->c.encrypt_round_keys,
+ (grasshopper_w128_t *)iv, (grasshopper_w128_t *)out, &c->c.buffer);
+ grasshopper_append128((grasshopper_w128_t *)out, (grasshopper_w128_t *)in);
+ ctr128_inc(iv);
+ in += GRASSHOPPER_BLOCK_SIZE;
+ out += GRASSHOPPER_BLOCK_SIZE;
+ num += GRASSHOPPER_BLOCK_SIZE;