- /* out_len = key_len + mac_len */
- unsigned char iv_full[16], mac_buf[8];
- unsigned int mac_len;
-
- EVP_CIPHER_CTX *ciph = NULL;
- EVP_MD_CTX *mac = NULL;
-
- int ret = 0;
-
- /* we expect IV of half length */
- memset(iv_full, 0, 16);
- memcpy(iv_full, iv, ivlen);
-
- mac = EVP_MD_CTX_new();
- if (mac == NULL) {
- GOSTerr(GOST_F_GOST_KEXP15, ERR_R_MALLOC_FAILURE);
- goto err;
- }
-
- if(EVP_DigestInit_ex(mac, EVP_get_digestbynid(mac_nid), NULL) <= 0
- || EVP_MD_CTX_ctrl(mac, EVP_MD_CTRL_SET_KEY, mac_key_len, mac_key) <= 0
- || EVP_DigestUpdate(mac, shared_key, shared_len) <= 0
- || EVP_DigestFinal_ex(mac, mac_buf, &mac_len) <= 0) {
- GOSTerr(GOST_F_GOST_KEXP15, ERR_R_INTERNAL_ERROR);
- goto err;
- }
-
- ciph = EVP_CIPHER_CTX_new();
- if (ciph == NULL) {
- GOSTerr(GOST_F_GOST_KEXP15, ERR_R_MALLOC_FAILURE);
- goto err;
- }
-
- if (EVP_CipherInit_ex(ciph, EVP_get_cipherbynid(cipher_nid), NULL, NULL, NULL, 1) <= 0
- || EVP_CipherInit_ex(ciph, NULL, NULL, cipher_key, iv_full, 1) <= 0
- || EVP_CipherUpdate(ciph, out, out_len, shared_key, shared_len) <= 0
- || EVP_CipherFinal_ex(ciph, out, out_len) <= 0) {
- GOSTerr(GOST_F_GOST_KEXP15, ERR_R_INTERNAL_ERROR);
- goto err;
- }
-
- memcpy(out + *out_len, mac_buf, mac_len);
- *out_len += mac_len;
-
- ret = 1;
+ unsigned char iv_full[16], mac_buf[16];
+ unsigned int mac_len;
+
+ EVP_CIPHER_CTX *ciph = NULL;
+ EVP_MD_CTX *mac = NULL;
+
+ int ret = 0;
+ int len;
+
+ mac_len = (cipher_nid == NID_magma_ctr) ? 8 :
+ (cipher_nid == NID_grasshopper_ctr) ? 16 : 0;
+
+ if (mac_len == 0) {
+ GOSTerr(GOST_F_GOST_KEXP15, GOST_R_INVALID_CIPHER);
+ goto err;
+ }
+
+ /* we expect IV of half length */
+ memset(iv_full, 0, 16);
+ memcpy(iv_full, iv, ivlen);
+
+ mac = EVP_MD_CTX_new();
+ if (mac == NULL) {
+ GOSTerr(GOST_F_GOST_KEXP15, ERR_R_MALLOC_FAILURE);
+ goto err;
+ }
+
+ if (EVP_DigestInit_ex(mac, EVP_get_digestbynid(mac_nid), NULL) <= 0
+ || omac_imit_ctrl(mac, EVP_MD_CTRL_SET_KEY, 32, mac_key) <= 0
+ || omac_imit_ctrl(mac, EVP_MD_CTRL_MAC_LEN, mac_len, NULL) <= 0
+ || EVP_DigestUpdate(mac, iv, ivlen) <= 0
+ || EVP_DigestUpdate(mac, shared_key, shared_len) <= 0
+ /* As we set MAC length directly, we should not allow overwriting it */
+ || EVP_DigestFinal_ex(mac, mac_buf, NULL) <= 0) {
+ GOSTerr(GOST_F_GOST_KEXP15, ERR_R_INTERNAL_ERROR);
+ goto err;
+ }
+
+ ciph = EVP_CIPHER_CTX_new();
+ if (ciph == NULL) {
+ GOSTerr(GOST_F_GOST_KEXP15, ERR_R_MALLOC_FAILURE);
+ goto err;
+ }
+
+ if (EVP_CipherInit_ex
+ (ciph, EVP_get_cipherbynid(cipher_nid), NULL, NULL, NULL, 1) <= 0
+ || EVP_CipherInit_ex(ciph, NULL, NULL, cipher_key, iv_full, 1) <= 0
+ || EVP_CipherUpdate(ciph, out, &len, shared_key, shared_len) <= 0
+ || EVP_CipherUpdate(ciph, out + shared_len, &len, mac_buf, mac_len) <= 0
+ || EVP_CipherFinal_ex(ciph, out + shared_len + len, out_len) <= 0) {
+ GOSTerr(GOST_F_GOST_KEXP15, ERR_R_INTERNAL_ERROR);
+ goto err;
+ }
+
+ *out_len = shared_len + mac_len;
+
+ ret = 1;