+static inline void apply_acpkm_grasshopper(gost_grasshopper_cipher_ctx_ctr *ctx, unsigned int num)
+{
+ if (!ctx->section_size ||
+ (num & (ctx->section_size - 1)))
+ return;
+ if (ctx->skip_sections) {
+ /* In no master key mode first section is using original key */
+ --ctx->skip_sections;
+ return;
+ }
+ acpkm_grasshopper(ctx);
+}
+
+#define GRASSHOPPER_BLOCK_MASK (GRASSHOPPER_BLOCK_SIZE - 1)
+/* 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;
+ }
+
+ // last part
+ size_t lasted = inl - blocks * GRASSHOPPER_BLOCK_SIZE;
+ if (lasted > 0) {
+ apply_acpkm_grasshopper(c, num);
+ grasshopper_encrypt_block(&c->c.encrypt_round_keys,
+ (grasshopper_w128_t *)iv, &c->partial_buffer, &c->c.buffer);
+ for (i = 0; i < lasted; i++)
+ out[i] = c->partial_buffer.b[i] ^ in[i];
+ ctr128_inc(iv);
+ num += lasted;
+ }
+ EVP_CIPHER_CTX_set_num(ctx, num);
+
+ return 1;
+}
+